exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
efb63628a024d798eba0ccc5e92b5703
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.util.*; // scanner.nextInt(); public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int test_case = scanner.nextInt(); for(int z = 0; z < test_case; ++z) { int n = scanner.nextInt(); long[] array = new long[n]; int menos = 0; for(int i = 0; i < n; ++i) { int t = scanner.nextInt(); array[i] = t; if(t == -1) ++menos; } long k; long min = Long.MAX_VALUE; long max = Long.MIN_VALUE; if(menos == n) { k = 0L; } else { for(int i = 0; i < n; ++i) { if(array[i] != -1){ if(i == 0) { if(array[i+1] == -1) { min = Math.min(min,array[i]); max = Math.max(max,array[i]); } } else if(i == n-1) { if(array[i-1] == -1) { min = Math.min(min,array[i]); max = Math.max(max,array[i]); } } else { if(array[i-1] == -1 || array[i+1]==-1) { min = Math.min(min,array[i]); max = Math.max(max,array[i]); } } } } k = ((max+min)/2); } max= Long.MIN_VALUE; for(int i = 0; i < n-1; ++i) { if(array[i] == -1) array[i] = k; if(array[i+1] == -1) array[i+1] = k; max= Math.max(max, Math.abs(array[i]-array[i+1])); } System.out.println( max + " " + k); //String[] arr = {"a","b","c", "d","e", "f" , "g" , "h", "i" , "j" , "k" , "l", "m", "n", "o", "p", "q" , "r", "s", "t", "u" , "v", "w" ,"x", "y", "z"}; } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
7fe8963840640507caa8c3ce41d98d8c
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.io.*; import java.util.*; /** * Created by Katushka on 11.03.2020. */ public class B { static int[] readArray(int size, InputReader in) { int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = in.nextInt(); } return a; } static long[] readLongArray(int size, InputReader in) { long[] a = new long[size]; for (int i = 0; i < size; i++) { a[i] = in.nextLong(); } return a; } public static void main(String[] args) throws FileNotFoundException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = in.nextInt(); for (int ii = 0; ii < t; ii++) { int n = in.nextInt(); long[] a = readLongArray(n, in); double minX = -1; double minY = -1; double minDiff = 0; int j = 0; if (a[0] == -1) { while (j < a.length && a[j] == -1) { j++; } if (j == a.length) { out.println("0 0"); continue; } minX = a[j]; minY = 0; } long lastA = a[j]; j++; while (j < a.length) { if (a[j] > -1) { minDiff = Math.max(minDiff, Math.abs(a[j] - lastA)); } else { while (j < a.length && a[j] == -1) { j++; } double newX; double newY; if (j < a.length) { newX = (lastA + a[j]) * 1.0 / 2; newY = Math.abs(lastA - a[j]) * 1.0 / 2; } else { newX = lastA; newY = 0; } if (minX == -1) { minX = newX; minY = newY; } else { double tx = minX; double ty = minY; if (newX + newY < minX + minY && newY - newX > minY - minX) { tx = (minX + minY - (newY - newX)) / 2; ty = (minX + minY + (newY - newX)) / 2; } else if (newX + newY > minX + minY && newY - newX < minY - minX) { tx = ((newY + newX) - (minY - minX)) / 2; ty = (minY - minX + (newY + newX)) / 2; } else if (newX + newY >= minX + minY && newY - newX >= minY - minX) { tx = newX; ty = newY; } minX = tx; minY = ty; } } if (j < a.length) { lastA = a[j]; j++; } } minY = Math.max(minDiff, Math.ceil(minY)); out.println((int) minY + " " + (int) Math.ceil(minX)); } out.close(); } private static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextString() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().charAt(0); } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
f5541253c4364e881bc69af162aa0608
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.util.*; import java.io.*; public class lp{ static PrintWriter out = new PrintWriter(System.out); static int mod =1000000007; static int max = 1000000000; static int fun(int a[],int n,int x){ int min = 0; for(int i=0;i<n;i++){ if(a[i]==-1){ if((i-1)>=0&&a[i-1]!=-1&&abs(a[i-1]-x)>min) min = abs(a[i-1]-x); if((i+1)<n&&a[i+1]!=-1&&abs(a[i+1]-x)>min) min = abs(a[i+1]-x); } else{ if((i-1)>=0&&a[i-1]!=-1&&abs(a[i-1]-a[i])>min) min = abs(a[i-1]-a[i]); if((i+1)<n&&a[i+1]!=-1&&abs(a[i+1]-a[i])>min) min = abs(a[i+1]-a[i]); } } return min; } public static void main(String[] args){ int t =ni(); for(int o=1;o<=t;o++){ int n = ni(); int a[] = new int[n]; for(int i=0;i<n;i++) a[i]= ni(); HashSet<Integer> h = new HashSet(); for(int i=0;i<n;i++){ if(a[i]==-1){ if((i-1)>=0&&a[i-1]!=-1)h.add(a[i-1]); if((i+1)<n&&a[i+1]!=-1)h.add(a[i+1]); } } n=h.size(); if(n==0) { out.println("0 53"); continue;} Integer arr[] = new Integer[n]; int st=0; for(Integer I : h) arr[st++]=I; Arrays.sort(arr); int k = (arr[0]+arr[n-1])/2; int m = fun(a,a.length,k); out.println(m+" "+k); } out.flush(); } static int abs(int x){ if(x<0) x=-x; return x; } static long gcd(long a,long b){ if(b%a==0) return a; return gcd(b%a,a); } static long min(long a,long b){ return Math.min(a,b); } static long max(long a,long b){ return Math.max(a,b); } static long pow(long a,long b,long md){ long ans =1; while(b>0){ if(b%2==1) ans=(ans*a)%md; a=(a*a)%md; b=b/2; } return ans; } static FastReader sc=new FastReader(); static int ni(){ int x = sc.nextInt(); return(x); } static long nl(){ long x = sc.nextLong(); return(x); } static String n(){ String str = sc.next(); return(str); } static String ns(){ String str = sc.nextLine(); return(str); } static double nd(){ double d = sc.nextDouble(); return(d); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
2ccd814922ad723ffe8848d2dd1bae30
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner input = new Scanner(System.in); int t = input.nextInt(); while(t-->0){ int n = input.nextInt(); long[] a = new long[n]; for(int i=0;i<n;i++) a[i] = input.nextLong(); long diff = 0; long min = Integer.MAX_VALUE; long max = Integer.MIN_VALUE; if(a[0]!=-1 && n>1 && a[1]==-1){ min = a[0]; max = a[0]; } for(int i=1;i<n;i++){ if(a[i] == -1) continue; if(a[i-1] != -1) diff = Math.max(diff,Math.abs(a[i]-a[i-1])); if(a[i-1]==-1||(i<n-1&&a[i+1]==-1)){ min = Math.min(min,a[i]); max = Math.max(max,a[i]); } } if(min == Integer.MAX_VALUE){ System.out.println(Math.max(diff,0)+" "+1); } else{ long k = (min+max)/2; diff = Math.max(diff,Math.max(k-min,max-k)); System.out.println(diff+" "+k); } } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
decd3d664c789d1a52c094c61dff1881
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.util.Scanner; public class MotBirth { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t--!=0) { int n = sc.nextInt(); long[] arr = new long[n]; for(int i = 0; i < n; i++) arr[i] = sc.nextLong(); long min = (long)1e9; long max = 0; for(int i = 0; i < n; i++) { if(arr[i]!=-1) { if((i-1>=0 && arr[i-1]==-1) || (i+1<n && arr[i+1]==-1)) { min = Math.min(arr[i],min); max = Math.max(arr[i],max); } } } long mean = (min+max)/2; for(int i = 0; i < n; i++) if(arr[i]==-1) arr[i] = mean; long dif = 0; for(int i = 1; i < n; i++) { dif = Math.max(dif,Math.abs(arr[i]-arr[i-1])); } System.out.println(dif + " " + mean); } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
c7d30373cf3ae88874a7481a82f83b99
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jaynil */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BMotaracksBirthday solver = new BMotaracksBirthday(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class BMotaracksBirthday { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); ArrayList<Integer> a = new ArrayList<>(); HashSet<Integer> hs = new HashSet<>(); for (int i = 0; i < n; i++) a.add(in.nextInt()); if (a.get(0) == -1 && n >= 2 && a.get(1) != -1) hs.add(a.get(1)); for (int i = 1; i < n; i++) { if (a.get(i) == -1) { if (i + 1 < n && a.get(i + 1) != -1) hs.add(a.get(i + 1)); if (a.get(i - 1) != -1) hs.add(a.get(i - 1)); } } if (hs.size() == 0) { out.println(0 + " " + 1); return; } int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int x : hs) { min = Math.min(x, min); max = Math.max(x, max); } int k = (max + min) / 2; max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { if (a.get(i) == -1) { a.set(i, k); } } for (int i = 0; i < n - 1; i++) { max = Math.max(max, Math.abs(a.get(i + 1) - a.get(i))); } out.println(max + " " + k); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
9250b0b72572045cb55126aa22c78e4e
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; import java.io.*; public class Main { public static void main(String args[]) { InputReader obj = new InputReader(System.in); int t=obj.nextInt(); while(t-->0) { int n=obj.nextInt(); long a[] = new long[n]; long sum=0; long cnt=(long)1e9+5; boolean ch[] = new boolean[n]; for(int i=0;i<n;i++) { ch[i]=false; } for(int i=0;i<n;i++) { a[i]=obj.nextLong(); if(i>=1 && i<n-1 && a[i]==-1) { ch[i-1]=true; ch[i+1]=true; } } if(a[0]==-1) { ch[1]=true; } if(a[n-1]==-1) { ch[n-2]=true; } for(int i=0;i<n;i++) { if(a[i]!=-1 && ch[i]) { if(a[i]>sum) { sum=a[i]; } if(a[i]<cnt) { cnt=a[i]; } } } if(cnt==(long)1e9+5) { cnt=0; } long k=(sum+cnt)/2; long m=0; for(int i=0;i<n;i++) { if(a[i]==-1) { a[i]=k; } } for(int i=1;i<n;i++) { if(Math.abs(a[i]-a[i-1])>m) { m=Math.abs(a[i]-a[i-1]); } } System.out.println(m+" "+k); } } public static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
2e044cf954a1c07d4da361619d1e7540
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); for (int d = 0; d < t; d++) { int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } int min = Integer.MAX_VALUE; int max = -1; for (int i = 0; i <n; i++) { if (arr[i]==-1){ if (i-1 >=0 && arr[i-1]!=-1){ min = Math.min(min , arr[i-1]); max = Math.max(max , arr[i-1]); } if (i+1 <n && arr[i+1]!=-1){ min = Math.min(min , arr[i+1]); max = Math.max(max , arr[i+1]); } } } int mdiff = 0; int k = (max+min)/2; if (max == -1) k=0; for (int i = 0; i <n; i++) { if (arr[i]==-1)arr[i]=k; } for (int i = 0; i <n-1; i++) { mdiff = Math.max(mdiff , Math.abs(arr[i]-arr[i+1])) ; } System.out.println(mdiff + " " + k); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt(){return Integer.parseInt(next());} public long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
08e043c510b030b26c8e1da5cb8d0416
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.util.Scanner; //http://codeforces.com/problemset/problem/1301/B public class HBMotaraka { private static void fillMissedValues(Scanner sc) { int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; ++i) { arr[i] = sc.nextInt(); } int minA = Integer.MAX_VALUE; int maxA = Integer.MIN_VALUE; int NotMissedD = 0; for (int i = 0; i < n; ++i) { if (arr[i] == -1) { if (i > 0 && arr[i - 1] != -1) { minA = Math.min(minA, arr[i - 1]); maxA = Math.max(maxA, arr[i - 1]); } while (i < n && arr[i] == -1) { i += 1; } if (i < n) { minA = Math.min(minA, arr[i]); maxA = Math.max(maxA, arr[i]); } else { break; } } else { if (i > 0 && arr[i - 1] != -1) { NotMissedD = Math.max(NotMissedD, Math.abs(arr[i - 1] - arr[i])); } } } if (minA == Integer.MAX_VALUE) { System.out.println("0 42"); return; } int MissedD = (int) Math.ceil((maxA - minA) * 0.5); System.out.println(Math.max(MissedD, NotMissedD) + " " + (minA + MissedD)); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; ++i) { fillMissedValues(sc); } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
a5067bc2fa57beb5bbb356ca108c6119
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ProblemB { public static InputStream inputStream = System.in; public static OutputStream outputStream = System.out; public static void main(String[] args) { Scanner scanner = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); int t = scanner.nextInt(); for (int p = 0; p < t; p++) { int n = scanner.nextInt(); List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(scanner.nextInt()); } int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; int m = Integer.MIN_VALUE; for (int i = 1; i < n - 1; i++) { if (list.get(i) != -1 && (list.get(i - 1) == -1 || list.get(i + 1) == -1)) { min = Math.min(min, list.get(i)); max = Math.max(max, list.get(i)); } } if (list.get(1) == -1 && list.get(0) != -1) { min = Math.min(min, list.get(0)); max = Math.max(max, list.get(0)); } if (list.get(n - 2) == -1 && list.get(n - 1) != -1) { min = Math.min(min, list.get(n - 1)); max = Math.max(max, list.get(n - 1)); } for (int i = 1; i < n; i++) { if (list.get(i) != -1 && list.get(i - 1) != -1) { m = Math.max(m, Math.abs(list.get(i) - list.get(i - 1))); } } if (min == Integer.MAX_VALUE) { out.println("0 0"); } else { int x = (min + max) / 2; int r = Math.max(Math.abs(min - x), Math.abs(max - x)); out.println(Math.max(r, m) + " " + x); } } out.flush(); } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
9efd3486e44ef5628b764a38420728b0
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int tst = Integer.parseInt(br.readLine()); while(tst-->0){ int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int[] arr = new int[n]; for(int i = 0; i<n; i++){ arr[i] = Integer.parseInt(st.nextToken()); } ArrayList<Integer> lst = new ArrayList<>(); for(int i = 1; i<n-1; i++){ if(arr[i] != -1){ if(arr[i-1] == -1 || arr[i+1] == -1) lst.add(arr[i]); } } if(arr[1] == -1 && arr[0]!=-1) lst.add(arr[0]); if(arr[n-2] == -1 && arr[n-1]!=-1) lst.add(arr[n-1]); int max = 0, min = (int)1e9; for(int x: lst){ max = Math.max(max, x); min = Math.min(min, x); } int k = (max-min)/2 + min; for(int i = 0; i<n; i++){ if(arr[i] == -1){ arr[i] = k; } } int diff = 0; for(int i = 1; i<n; i++){ diff = Math.max(diff, Math.abs(arr[i-1]-arr[i])); } sb.append(diff).append(" ").append(k).append('\n'); } System.out.println(sb); } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
a01774acc0871379f9e2d033874cf932
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.io.*; import java.util.*; public class utkarsh { BufferedReader br; PrintWriter out; long mod = (long) (1e9 + 7), inf = (long) (3e18); void solve() { int t = ni(); A: while(t-- > 0) { int n = ni(); long a[] = new long[n]; for(int i = 0; i < n; i++) a[i] = nl(); long min = inf; long max = -1; for(int i = 0; i < n; i++) { if(a[i] == -1) continue; if((i > 0 && a[i-1] == -1) || (i < n-1 && a[i+1] == -1)) { min = Math.min(a[i], min); max = Math.max(a[i], max); } } if(max == -1) { out.println("0 0"); continue A; } long k = (max + min) / 2; long ans = 0; for(int i = 0; i < n-1; i++) { long u = (a[i] == -1) ? k : a[i]; long v = (a[i+1] == -1) ? k : a[i+1]; ans = Math.max(ans, Math.abs(v - u)); } out.println(ans +" "+ k); } } long mp(long b, long e) { long r = 1; while(e > 0) { if( (e&1) == 1 ) r = (r * b) % mod; b = (b * b) % mod; e >>= 1; } return r; } // -------- I/O Template ------------- char nc() { return ns().charAt(0); } String nLine() { try { return br.readLine(); } catch(IOException e) { return "-1"; } } double nd() { return Double.parseDouble(ns()); } long nl() { return Long.parseLong(ns()); } int ni() { return Integer.parseInt(ns()); } StringTokenizer ip; String ns() { if(ip == null || !ip.hasMoreTokens()) { try { ip = new StringTokenizer(br.readLine()); } catch(IOException e) { throw new InputMismatchException(); } } return ip.nextToken(); } void run() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) { new utkarsh().run(); } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
766c02c6cae7dc2d92bcb9407244e72d
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.util.Collections; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task4 solver = new Task4(); solver.solve(1, in, out); out.close(); } static class Task4 { public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { if (arr[i] == -1) { if (i - 1 >= 0 && arr[i - 1] != -1) list.add(arr[i - 1]); if (i + 1 < n && arr[i + 1] != -1) list.add(arr[i + 1]); } } // out.println(list); Collections.sort(list); if (list.size() == 0) { out.println("0" + " " + "0"); } else { int avg = (list.get(list.size() - 1) + list.get(0)) / 2; for (int i = 0; i < n; i++) { if (arr[i] == -1) { arr[i] = avg; } } int m = Integer.MIN_VALUE; for (int i = 1; i < n; i++) { m = Math.max(m, Math.abs(arr[i - 1] - arr[i])); } out.println(m + " " + avg); } } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
e3d81522b1f4fb280bde4a9faab422b1
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.util.*; import java.util.ArrayList; public class Main{ static class Pair { int x; int y; Pair(int x, int y){ this.x=x; this.y=y; } } public static void main(String[] args){ Scanner param = new Scanner(System.in); int end=param.nextInt(); c:while(end-->0){ int n=param.nextInt(); int arr[]=new int[n]; int count=0; int max=Integer.MIN_VALUE; int min=Integer.MAX_VALUE; for(int i=0;i<n;i++){ arr[i]=param.nextInt(); if(arr[i]==-1){ count++; } } if(count==n){ System.out.print(0+" "); System.out.println(5); continue c; } int diff=0; int j=-1; int k=-1; for(int i=0;i<n;i++){ if(arr[i]==-1){ continue; } else if((i-1>=0&&arr[i-1]==-1)||((i+1)<n&&arr[i+1]==-1)){ if(max<arr[i]){ max=arr[i]; } if(min>arr[i]){ min=arr[i]; } } } int c=((max+min)/2); for(int i=0;i<n;i++){ if(arr[i]==-1){ arr[i]=c; } } for(int i=0;i<n-1;i++){ diff=Math.max(diff,Math.abs(arr[i]-arr[i+1])); } System.out.print(diff+" "); System.out.println(c); } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
8d912b6df6daaa875946a3784ddd49f4
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.util.*; import java.math.*; import java.io.*; import java.lang.*; public class Main { public static void main(String[] args) { FastReader sc =new FastReader(); int t = sc.nextInt(); while(t-- > 0) { int n=sc.nextInt(); int a[]=sc.nextIntArray(n); boolean take[]=new boolean[n]; Arrays.fill(take,false); for(int i=0;i<n;i++) { if(a[i]==-1) { //all its neighbours as true; if(i>0) take[i-1]=true; if(i<n-1) take[i+1]=true; } } // System.out.println(Arrays.toString(take)); //long total=0; //int count=0; int min=Integer.MAX_VALUE; int max=Integer.MIN_VALUE; for(int i=0;i<n;i++) { if(take[i]==true && a[i]!=-1) { min=Math.min(a[i],min); max=Math.max(a[i],max); } } int k=0; if(min==Integer.MAX_VALUE && max==Integer.MIN_VALUE) { k=0; } else { k=(max+min)/2; } for(int i=0;i<n;i++) { if(a[i]==-1) a[i]=k; //if(a[i]==-1) c[i]=k2; } int maxDiff=Integer.MIN_VALUE; //int maxDiff2=Integer.MIN_VALUE; for(int i=1;i<n;i++) { maxDiff=Math.max(maxDiff,Math.abs(a[i]-a[i-1])); } System.out.println(maxDiff+" "+k); } } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (final IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (final IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(final int n) { final int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(next()); } return a; } } } //Templates for Comparator and Classes - @jagrit_07 /* Arrays.sort(newEmployees, new Comparator<Employee>() { @Override public int compare(Employee emp1, Employee emp2) { return emp1.getName().compareTo(emp2.getName()); } }); class Pair { long i; //index; long l; //left; long c; //cost; public Pair(long x,long y,long z) { this.i=x; this.l=y; this.c=z; } public String toString() { return this.i+" "+this.l+" "+this.c; } } class Comp implements Comparator<Pair> { public int compare(Pair p1, Pair p2) { if(p1.c!=p2.c) { return (int)(p1.c-p2.c); //sort acc to cost; } else{ return (int)(p1.i-p2.i); //sort acc to index; } } } */ /* HashMap - Put template - d.put(a1,d.getOrDefault(a1,0)+1); */
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
6f79ed9e42d4fa93a98a1b722f98ce80
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Iterator; import java.util.StringTokenizer; public class MotaracksBirthday { public static void main(String[] args) { FastReader input=new FastReader(); int t=input.nextInt(); while(t-->0) { int n=input.nextInt(); int a[]=new int[n]; int max=Integer.MIN_VALUE; for(int i=0;i<n;i++) { a[i]=input.nextInt(); if(i!=0) { if(a[i]!=-1 && a[i-1]!=-1) { int d=Math.abs(a[i]-a[i-1]); max=Math.max(max,d); } } } HashSet<Integer> set=new HashSet<>(); for(int i=0;i<n;i++) { if(i==0) { if(a[i]==-1) { if(a[i+1]!=-1) { set.add(a[i+1]); } } } else if(i==n-1) { if(a[i]==-1) { if(a[i-1]!=-1) { set.add(a[i-1]); } } } else { if(a[i]==-1) { if(a[i-1]!=-1) { set.add(a[i-1]); } if(a[i+1]!=-1) { set.add(a[i+1]); } } } } Iterator it=set.iterator(); long max1=Long.MIN_VALUE; long min1=Long.MAX_VALUE; double c=0; while(it.hasNext()) { int v=(int)it.next(); max1=Math.max(max1,v); min1=Math.min(min1,v); c++; } if(c==0) { System.out.println(0+" "+0); } else { long k=(long)(max1+min1)/2; int m = Integer.MIN_VALUE; Iterator i = set.iterator(); while (i.hasNext()) { int d = (int) Math.abs(k - (int) i.next()); m = Math.max(m, d); } if(max!=Integer.MIN_VALUE) { if(max>=m) { System.out.println(max+" "+k); } else { System.out.println(m+" "+k); } } else { System.out.println(m+" "+k); } } } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
83f2bdad654acb02c9e7e46dbf8b7e52
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.util.*; public class codeforce { public static void main(String args[]) { Scanner sj = new Scanner(System.in); int t = sj.nextInt(); while(t-->0){ int n = sj.nextInt(); long a[] = new long[n]; long min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; for(int i=0;i<n;i++){ a[i] = sj.nextLong(); } for(int i=0;i<n;i++){ if(i > 0 && a[i] == -1 && a[i - 1] != -1){ min = Math.min(min , a[i - 1]); max = Math.max(max , a[i - 1]); } if(i < n - 1 && a[i] == - 1 && a[i + 1] != -1){ min = Math.min(min , a[i + 1]); max = Math.max(max , a[i + 1]); } } long avg = (min+max)/2; for(int i=0;i<n;i++){ if(a[i]==-1) a[i] = avg; } long dif = Integer.MIN_VALUE; for(int i=0;i<n-1;i++){ dif = Math.max(dif, Math.abs(a[i]-a[i+1])); } System.out.println(dif+" "+avg); } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
5c55d9e79a870537ab2f137f42d63463
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.Collections; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Vishal Burman */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BMotaracksBirthday solver = new BMotaracksBirthday(); solver.solve(1, in, out); out.close(); } static class BMotaracksBirthday { public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); for (int i = 0; i < t; i++) { int n = in.nextInt(); int a[] = new int[n]; for (int j = 0; j < n; j++) { a[j] = in.nextInt(); } ArrayList<Integer> list = new ArrayList<>(); for (int j = 0; j < n; j++) { if (j == 0) { if (a[j] >= 0 && a[j + 1] == -1) list.add(a[j]); } else if (j > 0 && j < n - 1) { if (a[j] >= 0 && (a[j - 1] == -1 || a[j + 1] == -1)) list.add(a[j]); } else { if (a[j] >= 0 && a[j - 1] == -1) list.add(a[j]); } } Collections.sort(list); int fill = 0; if (list.size() > 0) { int l = list.get(0); int u = list.get(list.size() - 1); // out.println("Min="+l+" "+"Max="+u); fill = (l + u) / 2; } int max = Integer.MIN_VALUE; for (int j = 0; j < n; j++) { if (a[j] == -1) a[j] = fill; if (j >= 1) { max = Math.max(max, Math.abs(a[j] - a[j - 1])); } } out.println(max + " " + fill); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
29ff9c0b526b039d84f4ca422c29602a
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
// package Codef; import java.util.Scanner; public class B_1301 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = s.nextLong(); } long max = 0, dif = 0; long min = 1000000000; for (int i = 0; i < n; i++) { if(i>0 && a[i] ==-1 && a[i-1] !=-1) { min = Math.min(min, a[i-1]); max = Math.max(max, a[i-1]); } if(i<n-1 && a[i] ==-1 && a[i+1] !=-1) { min = Math.min(min, a[i+1]); max = Math.max(max, a[i+1]); } //System.out.println(min+" "+max); } dif = (min+max)/2; long ans = 0; for(int i=0;i<n;i++ ) { if(a[i] == -1) a[i] = dif; if(i>0) { ans = Math.max(Math.abs(a[i-1]-a[i]), ans); } } System.out.println(ans+" "+dif); } } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
d98883dcd96c5bc720cf8fbf8fddab1d
train_002.jsonl
1581604500
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?
256 megabytes
import java.util.Scanner; public class MainClass { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); for (; t > 0; t--) { int n = scan.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scan.nextInt(); } int down = 2000000000; int up = 0; for (int i = 1; i < n; i++) { if ((a[i - 1] != -1) && (a[i] == -1)) { down = Math.min(down, a[i - 1]); up = Math.max(up, a[i - 1]); } } for (int i = 0; i < n - 1; i++) { if ((a[i + 1] != -1) && (a[i] == -1)) { down = Math.min(down, a[i + 1]); up = Math.max(up, a[i + 1]); } } int k = (down + up) / 2; int ans = 0; if (a[0] == -1) { a[0] = k; } for(int i = 1; i < n; i++){ if(a[i] == -1) a[i] = k; ans = Math.max(ans, Math.abs(a[i] - a[i - 1])); } System.out.println(ans + " " + k); } scan.close(); } }
Java
["7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5"]
2 seconds
["1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4"]
NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$. $$$|a_1 - a_2| = |6 - 6| = 0$$$; $$$|a_2 - a_3| = |6 - 9| = 3$$$; $$$|a_3 - a_4| = |9 - 6| = 3$$$; $$$|a_4 - a_5| = |6 - 3| = 3$$$; $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.
Java 8
standard input
[ "binary search", "greedy", "ternary search" ]
8ffd80167fc4396788b745b53068c9d3
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.
1,500
Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.
standard output
PASSED
f7cca4a6d616c5351b174e152052625c
train_002.jsonl
1468514100
Barney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible. Initially, happiness level of Nora is 0. Nora loves some pickup lines like "I'm falling for you" and stuff. Totally, she knows n pickup lines, each consisting only of lowercase English letters, also some of them may be equal (in writing, but different in pronouncing or meaning though). Every time Nora sees i-th pickup line as a consecutive subsequence of Barney's text message her happiness level increases by ai. These substrings may overlap, for example, Nora will see the pickup line aa twice and the pickup line ab once in text message aaab.Due to texting app limits, Barney's text may have up to l characters.Barney asked you to help him make Nora as much happy as possible, it's gonna be legen...
256 megabytes
import java.io.IOException; import java.io.PrintStream; import java.util.Scanner; import java.util.SortedSet; import java.util.TreeSet; public class F { private static Scanner in = new Scanner(System.in); private static PrintStream out = System.out; public static class MatrixDP { private long best(long a, long b) { return Math.max(a, b); } private long combine(long a, long b) { if (a == -1 || b == -1) return -1; return a + b; } private long[][] multiply(long[][] a, long[][] b) { int n = a.length; long[][] ret = new long[n][n]; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { ret[i][j] = -1; for (int k = 0; k < n; ++k) ret[i][j] = best(ret[i][j], combine(a[i][k], b[k][j])); } return ret; } public long[][] solve(long[][] mtx, long power) { if (power <= 0) throw new RuntimeException(); long[][] ret = null; long[][] pow = mtx.clone(); while (power > 0) { if (power%2 == 1) ret = (ret == null) ? pow : multiply(ret, pow); pow = multiply(pow, pow); power /= 2; } return ret; } } public static void main(String[] args) throws IOException { // 9:05 int n = in.nextInt(); long length = in.nextLong(); int[] as = new int[n]; for (int i = 0; i < n; ++i) as[i] = in.nextInt(); String[] lines = new String[n]; for (int i = 0; i < n; ++i) lines[i] = in.next(); // create automaton SortedSet<String> set = new TreeSet<String>(); for (int idx = 0; idx < lines.length; ++idx) { String line = lines[idx]; for (int i = 0; i <= line.length(); ++i) { String prefix = line.substring(0, i); set.add(prefix); } } int sz = set.size(); String[] prefixes = set.toArray(new String[0]); long[] scores = new long[sz]; for (int i = 0; i < sz; ++i) for (int j = 0; j < lines.length; ++j) if (prefixes[i].endsWith(lines[j])) scores[i] += as[j]; long[][] mtx = new long[sz][sz]; for (int i = 0; i < sz; ++i) for (int j = 0; j < sz; ++j) { String s = prefixes[i]; String t = prefixes[j]; boolean reachable = true; if (t.length() > 0) reachable = s.endsWith(t.substring(0, t.length() - 1)); mtx[i][j] = (reachable) ? scores[j] : -1; } // solve via matrix DP MatrixDP solver = new MatrixDP(); long[][] pow = solver.solve(mtx, length); long ans = 0; for (int i = 0; i < sz; ++i) if (pow[0][i] != -1) ans = Math.max(ans, pow[0][i]); out.println(ans); } }
Java
["3 6\n3 2 1\nheart\nearth\nart", "3 6\n3 2 8\nheart\nearth\nart"]
6 seconds
["6", "16"]
NoteAn optimal answer for the first sample case is hearth containing each pickup line exactly once.An optimal answer for the second sample case is artart.
Java 8
standard input
[ "dp", "data structures", "strings" ]
24a59fe61d996a5fd0a8fa64995f13e4
The first line of input contains two integers n and l (1 ≤ n ≤ 200, 1 ≤ l ≤ 1014) — the number of pickup lines and the maximum length of Barney's text. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100), meaning that Nora's happiness level increases by ai after every time seeing i-th pickup line. The next n lines contain the pickup lines. i-th of them contains a single string si consisting of only English lowercase letter. Summary length of all pickup lines does not exceed 200. All strings are not empty.
2,500
Print the only integer — the maximum possible value of Nora's happiness level after reading Barney's text.
standard output
PASSED
56683a715f211004fd127da96c146e12
train_002.jsonl
1468514100
Barney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible. Initially, happiness level of Nora is 0. Nora loves some pickup lines like "I'm falling for you" and stuff. Totally, she knows n pickup lines, each consisting only of lowercase English letters, also some of them may be equal (in writing, but different in pronouncing or meaning though). Every time Nora sees i-th pickup line as a consecutive subsequence of Barney's text message her happiness level increases by ai. These substrings may overlap, for example, Nora will see the pickup line aa twice and the pickup line ab once in text message aaab.Due to texting app limits, Barney's text may have up to l characters.Barney asked you to help him make Nora as much happy as possible, it's gonna be legen...
256 megabytes
import java.io.PrintStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; // Q: how do we even know we can do this matrix thing? public class F { private static Scanner in = new Scanner(System.in); private static PrintStream out = System.out; private static final long NINF = -Long.MAX_VALUE/2; private static class V { public String s; public int val = 0; public Set<V> children = new HashSet<V>(); public V(String s) { this.s = s; } public void addChild(V v) { children.add(v); } } private static boolean isSuffix(String s, String suf) { if (s.length() < suf.length()) return false; if (suf.length() == 0) return true; return s.substring(s.length() - suf.length()).equals(suf); } private static long[][] matrixMult(long[][] A, long[][] B) { int n = A.length; int m = B[0].length; int k = B.length; long[][] ret = new long[n][m]; for (int r = 0; r < n; ++r) for (int c = 0; c < m; ++c) { ret[r][c] = NINF; for (int i = 0; i < k; ++i) ret[r][c] = Math.max(ret[r][c], A[r][i] + B[i][c]); } return ret; } public static void main(String[] args) { // read input and set up DFA int n = in.nextInt(); long len = in.nextLong(); int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = in.nextInt(); Map<String, V> mp = new HashMap<String, V>(); String[] pls = new String[n]; for (int i = 0; i < n; ++i) { String s = in.next(); pls[i] = s; for (int j = 0; j <= s.length(); ++j) { String t = s.substring(0, j); if (!mp.containsKey(t)) mp.put(t, new V(t)); } } // add in edges to DFA V[] vs = mp.values().toArray(new V[]{}); for (V curr : vs) for (V next : vs) if (next.s.length() <= 1 || isSuffix(curr.s, next.s.substring(0, next.s.length() - 1))) curr.addChild(next); // set up values of all DFA nodes for (V curr : vs) for (int i = 0; i < n; ++i) if (isSuffix(curr.s, pls[i])) curr.val += a[i]; // set up matrix long[][] A = new long[vs.length][vs.length]; long[][] P = new long[vs.length][vs.length]; for (int i = 0; i < vs.length; ++i) for (int j = 0; j < vs.length; ++j) { if (vs[j].children.contains(vs[i])) A[i][j] = vs[i].val; else { A[i][j] = NINF; P[i][j] = NINF; } } // power matrix to len power boolean init = false; while (len > 0) { if (len%2 == 1) { P = init ? matrixMult(A, P) : A; init = true; } A = matrixMult(A, A); len /= 2; } // get answer int idx = 0; while (vs[idx].s.length() != 0) ++idx; long ans = 0; for (int i = 0; i < vs.length; ++i) ans = Math.max(ans, P[i][idx]); out.println(ans); } } /* 3 2 3 2 1 heart earth art 1 2 1 art */
Java
["3 6\n3 2 1\nheart\nearth\nart", "3 6\n3 2 8\nheart\nearth\nart"]
6 seconds
["6", "16"]
NoteAn optimal answer for the first sample case is hearth containing each pickup line exactly once.An optimal answer for the second sample case is artart.
Java 8
standard input
[ "dp", "data structures", "strings" ]
24a59fe61d996a5fd0a8fa64995f13e4
The first line of input contains two integers n and l (1 ≤ n ≤ 200, 1 ≤ l ≤ 1014) — the number of pickup lines and the maximum length of Barney's text. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100), meaning that Nora's happiness level increases by ai after every time seeing i-th pickup line. The next n lines contain the pickup lines. i-th of them contains a single string si consisting of only English lowercase letter. Summary length of all pickup lines does not exceed 200. All strings are not empty.
2,500
Print the only integer — the maximum possible value of Nora's happiness level after reading Barney's text.
standard output
PASSED
4f0733f40fe8cc9e7a3a0aa0d3d9d6ec
train_002.jsonl
1385479800
Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements.Sereja needs to rush to the gym, so he asked to find all the described positions of q.
256 megabytes
import java.util.*; import java.io.*; public class AlgorithmInfinite { public static void main(String[] args) throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(rd.readLine()); int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()), p = Integer.parseInt(st.nextToken()); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int[] a = new int[n], b = new int[m]; st = new StringTokenizer(rd.readLine()); for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); st = new StringTokenizer(rd.readLine()); for(int i=0; i<m; i++) b[i] = Integer.parseInt(st.nextToken()); int cur = 0; for(int i=0; i<m; i++){ int x = b[i]; if(map.containsKey(x)) continue; else{ map.put(x, cur); cur++; } } int cnt = 0; int[] freq = new int[m+1]; for(int i=0; i<m; i++){ int num = map.get(b[i]); freq[num]++; } int numzeros = 0; int[] fr = new int[m+1]; for(int i=0; i<=m; i++){ if(freq[i]==0) numzeros++; } ArrayList<Integer> ans = new ArrayList<Integer>(); for(int i=0; i<p; i++){ if(i + 1L*(m-1)*p >= n) break; for(int j=0; j<m+1; j++) fr[j] = freq[j]; int zeros = numzeros; for(int j=0; j<m; j++){ int num = a[i+j*p]; if(!map.containsKey(num)){ continue; } else{ num = map.get(num); fr[num]--; if(fr[num]==0) zeros++; } } if(zeros==m+1){ cnt++; ans.add(1+i); } // scan next m-s for(int j=i+m*p; j<n; j+=p){ int old = a[j-m*p]; if(map.containsKey(old)){ int o = map.get(old); fr[o]++; if(fr[o]==1) zeros--; } if(!map.containsKey(a[j])){ continue; } int num = map.get(a[j]); fr[num]--; if(fr[num]==0) zeros++; if(zeros==m+1){ cnt++; ans.add(j-m*p+p+1); } } } pw.println(cnt); Collections.sort(ans); for(int i=0; i<ans.size(); i++){ pw.print(ans.get(i)+" "); } pw.println(); pw.flush(); } static int[] dp = new int[100002]; static String S; }
Java
["5 3 1\n1 2 3 2 1\n1 2 3", "6 3 2\n1 3 2 2 3 1\n1 2 3"]
1 second
["2\n1 3", "2\n1 2"]
null
Java 6
standard input
[ "data structures", "binary search" ]
84cce147e8aadb140afaaa95917fdf0d
The first line contains three integers n, m and p (1 ≤ n, m ≤ 2·105, 1 ≤ p ≤ 2·105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109).
1,900
In the first line print the number of valid qs. In the second line, print the valid values in the increasing order.
standard output
PASSED
bf671727c92c787b0aa114100901ac60
train_002.jsonl
1385479800
Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements.Sereja needs to rush to the gym, so he asked to find all the described positions of q.
256 megabytes
import java.util.List; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.ArrayList; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.HashSet; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { int n, m, p, res; int[] a, b, c, cnt, d; List<Integer> ans; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); m = in.nextInt(); p = in.nextInt(); if (n / p + 1 < m) { out.println("0"); return; } a = new int[n]; b = new int[m]; c = new int[m]; for (int i = 0; i < n; ++i) a[i] = in.nextInt(); for (int i = 0; i < m; ++i) { b[i] = in.nextInt(); c[i] = b[i]; } Arrays.sort(b); d = new int[m]; int mm = 1; d[0] = 1; for (int i = 1; i < m; ++i) if (b[i] != b[i - 1]) { b[mm++] = b[i]; d[mm - 1] = 1; } else d[mm - 1]++; for (int i = 0; i < n; ++i) { int j = Arrays.binarySearch(b, 0, mm, a[i]); a[i] = j; } ans = new ArrayList<Integer>(); cnt = new int[mm + 5]; HashSet<Integer> S = new HashSet<Integer>(); for (int mod = 0; mod < p; ++mod) { Arrays.fill(cnt, 0); S.clear(); for (int i = 0; i < m - 1 && p * i + mod < n; ++i) { if (a[p * i + mod] >= 0) { ++cnt[a[p * i + mod]]; if (cnt[a[p * i + mod]] == d[a[p * i + mod]]) S.add(a[p * i + mod]); } } for (int i = m - 1; p * i + mod < n; ++i) { if (a[p * i + mod] >= 0) { ++cnt[a[p * i + mod]]; if (cnt[a[p * i + mod]] == d[a[p * i + mod]]) S.add(a[p * i + mod]); } if (S.size() == mm) { ++res; ans.add(p * (i - m + 1) + mod); } if (a[p * (i - m + 1) + mod] >= 0) { if (cnt[a[p * (i - m + 1) + mod]] == d[a[p * (i - m + 1) + mod]]) S.remove(a[p * (i - m + 1) + mod]); --cnt[a[p * (i - m + 1) + mod]]; } } } out.println(res); Collections.sort(ans); for (Integer an : ans) out.print((an + 1) + " "); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["5 3 1\n1 2 3 2 1\n1 2 3", "6 3 2\n1 3 2 2 3 1\n1 2 3"]
1 second
["2\n1 3", "2\n1 2"]
null
Java 6
standard input
[ "data structures", "binary search" ]
84cce147e8aadb140afaaa95917fdf0d
The first line contains three integers n, m and p (1 ≤ n, m ≤ 2·105, 1 ≤ p ≤ 2·105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109).
1,900
In the first line print the number of valid qs. In the second line, print the valid values in the increasing order.
standard output
PASSED
8e8788ee635218139f9a96240587b59f
train_002.jsonl
1385479800
Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements.Sereja needs to rush to the gym, so he asked to find all the described positions of q.
256 megabytes
//package round215; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; public class B { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(), p = ni(); int[] a = na(n); int[] b = na(m); int[] all = new int[n+m]; System.arraycopy(a, 0, all, 0, n); System.arraycopy(b, 0, all, n, m); all = shrink(all); System.arraycopy(all, 0, a, 0, n); System.arraycopy(all, n, b, 0, m); long[] hs = new long[n+m+1]; Random gen = new Random(); for(int i = 0;i <= n+m;i++)hs[i] = gen.nextLong(); long ideal = 0; for(int i = 0;i < m;i++){ ideal += hs[b[i]]; } int[] ans = new int[n]; int ap = 0; for(int i = 0;i < p;i++){ long h = 0; for(int j = i;j < n;j+=p){ h += hs[a[j]]; if(j-(long)m*p >= 0){ h -= hs[a[j-m*p]]; } if(h == ideal)ans[ap++] = j-(m-1)*p; } } out.println(ap); int[] ret = radixSort(Arrays.copyOf(ans, ap)); for(int i = 0;i < ret.length;i++){ if(i > 0)out.print(" "); out.print(ret[i]+1); } out.println(); } public static int[] radixSort(int[] f) { int[] to = new int[f.length]; { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i]; int[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i]; int[] d = f; f = to;to = d; } return f; } public static int[] shrink(int[] a) { int n = a.length; long[] b = new long[n]; for(int i = 0;i < n;i++)b[i] = (long)a[i]<<32|i; Arrays.sort(b); int[] ret = new int[n]; int p = 0; for(int i = 0;i < n;i++) { if(i>0 && (b[i]^b[i-1])>>32!=0)p++; ret[(int)b[i]] = p; } return ret; } void run() throws Exception { // int n = 200000; // int m = 100; // Random gen = new Random(); // StringBuilder sb = new StringBuilder(); // sb.append(n + " "); // sb.append(m + " "); // sb.append(m + " "); // for(int i = 0;i < n;i++){ // sb.append(gen.nextInt(3)+1 + " "); // } // for(int i = 0;i < m;i++){ // sb.append(gen.nextInt(3)+1 + " "); // } // INPUT = sb.toString(); is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new B().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5 3 1\n1 2 3 2 1\n1 2 3", "6 3 2\n1 3 2 2 3 1\n1 2 3"]
1 second
["2\n1 3", "2\n1 2"]
null
Java 6
standard input
[ "data structures", "binary search" ]
84cce147e8aadb140afaaa95917fdf0d
The first line contains three integers n, m and p (1 ≤ n, m ≤ 2·105, 1 ≤ p ≤ 2·105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109).
1,900
In the first line print the number of valid qs. In the second line, print the valid values in the increasing order.
standard output
PASSED
5981e200cc2b33eadbbe5ec511518729
train_002.jsonl
1385479800
Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements.Sereja needs to rush to the gym, so he asked to find all the described positions of q.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws IOException { B solver = new B(); solver.solve(); } private void solve() throws IOException { FastScanner sc = new FastScanner(System.in); // sc = new FastScanner("5 3 1\n" + // "1 2 3 2 1\n" + // "1 2 3\n"); // sc = new FastScanner("6 3 2\n" + // "1 3 2 2 3 1\n" + // "1 2 3\n"); int n = sc.nextInt(); int m = sc.nextInt(); int p = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } int[] b = new int[m]; for (int i = 0; i < m; i++) { b[i] = sc.nextInt(); } Map<Integer, Integer> bf = new HashMap<Integer, Integer>(); for (int i = 0; i < m; i++) { if (!bf.containsKey(b[i])) { bf.put(b[i], 1); } else { int v = bf.get(b[i]); bf.put(b[i], v + 1); } } List<Integer> res = new ArrayList<Integer>(); for (int i = 0; i < p; i++) { Map<Integer, Integer> af = new HashMap<Integer, Integer>(); for (int k = 0; i + k * p < n; k++) { if (k >= m) { int key = a[i + (k - m) * p]; int v = af.get(key); if (v > 1) { af.put(key, v - 1); } else { af.remove(key); } } int key = a[i + k * p]; if (!af.containsKey(key)) { af.put(key, 1); } else { int v = af.get(key); af.put(key, v + 1); } if (k >= m - 1) { if (af.equals(bf)) { res.add(i + (k - m + 1) * p + 1); } } } } Collections.sort(res); System.out.println(res.size()); for (int r : res) { System.out.print(r); System.out.print(' '); } System.out.println(); } private static class FastScanner { private BufferedReader br; private StringTokenizer st; public FastScanner(InputStream in) throws IOException { br = new BufferedReader(new InputStreamReader(in)); } public FastScanner(File file) throws IOException { br = new BufferedReader(new FileReader(file)); } public FastScanner(String s) { br = new BufferedReader(new StringReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); return ""; } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5 3 1\n1 2 3 2 1\n1 2 3", "6 3 2\n1 3 2 2 3 1\n1 2 3"]
1 second
["2\n1 3", "2\n1 2"]
null
Java 6
standard input
[ "data structures", "binary search" ]
84cce147e8aadb140afaaa95917fdf0d
The first line contains three integers n, m and p (1 ≤ n, m ≤ 2·105, 1 ≤ p ≤ 2·105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109).
1,900
In the first line print the number of valid qs. In the second line, print the valid values in the increasing order.
standard output
PASSED
259f1ce82d98c6119b58fc9ce489ea4b
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } static long n,pow[]; static int m,arr[]; static HashMap<Long,Integer> map; public static void main(String args[]) throws IOException { Scanner input=new Scanner(System.in); int test=input.nextInt(); pow=new long[32]; pow[0]=1; map=new HashMap<>(); map.put(1L, 0); for(int i=1;i<pow.length;i++) { pow[i]=2*pow[i-1]; map.put(pow[i], i); } StringBuilder ans=new StringBuilder(""); for(int t=1;t<=test;t++) { n=input.nextLong(); m=input.nextInt(); arr=new int[pow.length]; for(int i=0;i<m;i++) { arr[map.get(input.nextLong())]++; } ans.append(solve()+"\n"); } System.out.println(ans); } public static int solve() { int ans=0; if(n%2==1) { if(arr[0]>0) { arr[0]--; n--; } else { for(int i=1;i<pow.length;i++) { if(arr[i]>0) { arr[i]--; long tmp=pow[i]; while(tmp!=1) { // System.out.println(tmp); tmp/=2; arr[map.get(tmp)]++; ans++; } arr[0]--; n--; break; } } } } // System.out.println("III"); arr[1]+=arr[0]/2; arr[0]=0; for(int i=0;i<=62;i++) { // System.out.println("i "+i); if((n&(long)Math.pow(2, i))!=0) { int tmp=check((long)Math.pow(2, i)); if(tmp==-1) { return -1; } ans+=tmp; } } return ans; } public static int check(long tmp) { long tmp1=tmp; int tmp_arr[]=new int[arr.length]; for(int i=0;i<arr.length;i++) { tmp_arr[i]=arr[i]; } for(int i=pow.length-1;i>0;i--) { while(tmp_arr[i]>0 && pow[i]<=tmp1) { tmp1-=pow[i]; tmp_arr[i]--; } } if(tmp1==0) { arr=tmp_arr; return 0; } for(int i=1;i<pow.length;i++) { if(arr[i]>0 && pow[i]>=tmp) { arr[i]--; tmp1=pow[i]; int cnt=0; while(tmp1!=tmp) { tmp1/=2; arr[map.get(tmp1)]++; cnt++; } return cnt; } } return -1; } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
4fb7a3dfe5a672dfc794426724345361
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
/** * ******* Created on 25/2/20 12:44 PM******* */ import java.io.*; import java.util.*; public class ED82D implements Runnable { private static final int MAX = (int) (1E5 + 5); private static final int MOD = (int) (1E9 + 7); private static final long Inf = (long) (1E14 + 10); private void solve() throws IOException { int t =reader.nextInt(); long[] a =new long[MAX]; while(t-- >0){ long n = reader.nextLong(); int m = reader.nextInt(); for(int i=0;i<m;i++) a[i] = reader.nextInt(); long sum =0; int[] c = new int[65]; for(int i=0;i<m;i++) { long temp =a[i]; for(int j=0;j<32;j++){ if(((temp>>j)&1L)==1L){ c[j]++;break; } } sum +=a[i]; } if(sum < n){ writer.println("-1"); continue; } int res =0; for(int i=0;i<60;){ if(((n>>i)&1L)==1L){ if(c[i]>0){ c[i]-=1; }else{ while(i<60 && c[i]==0){ i++; res++; } c[i]-=1; continue; } } c[i+1] += c[i]/2; i++; } writer.println(res); } } public static void main(String[] args) throws IOException { try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) { new ED82D().run(); } } StandardInput reader; PrintWriter writer; @Override public void run() { try { reader = new StandardInput(); writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); } } interface Input extends Closeable { String next() throws IOException; default int nextInt() throws IOException { return Integer.parseInt(next()); } default long nextLong() throws IOException { return Long.parseLong(next()); } default double nextDouble() throws IOException { return Double.parseDouble(next()); } default int[] readIntArray() throws IOException { return readIntArray(nextInt()); } default int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int i = 0; i < array.length; i++) { array[i] = nextInt(); } return array; } default long[] readLongArray(int size) throws IOException { long[] array = new long[size]; for (int i = 0; i < array.length; i++) { array[i] = nextLong(); } return array; } } private static class StandardInput implements Input { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer stringTokenizer; @Override public void close() throws IOException { reader.close(); } @Override public String next() throws IOException { if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
c1a82b876f712543a4b38c1f40691f14
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.util.*; import java.io.*; public class d { public static PrintWriter out; public static FS sc; public static void main(String[] Args) throws Exception { sc = new FS(System.in); out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(System.out))); int t = sc.nextInt(); while (t-->0) { // System.err.println(t); long cap = sc.nextLong(); int n = sc.nextInt(); int[] vals = new int[n]; for (int i = 0; i < n; i++) vals[i] = sc.nextInt(); Arrays.sort(vals); int ans = 0; long curPow = getCurPow(cap); long total = 0; for (int i = 0; i < n; i++) { if ((1l<<curPow) == vals[i]) { cap ^= (1l<<curPow); if (cap == 0) break; curPow = getCurPow(cap); } else if ((1l<<curPow) < vals[i]) { total += vals[i]; while (vals[i] != (1l<<curPow)) { ans++; vals[i] >>= 1; } } else total += vals[i]; while (total >= (1l<<curPow)) { cap ^= (1l<<curPow); total -= (1l<<curPow); if (cap == 0) break; curPow = getCurPow(cap); } if (cap == 0) break; } if (cap != 0) ans = -1; out.println(ans); } out.close(); } public static int getCurPow(long cap) { int curPow = 0; while (((1l<<curPow)&cap) == 0) curPow++; return curPow; } public static class FS { BufferedReader br; StringTokenizer st; FS(InputStream in) throws Exception { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(br.readLine()); } String next() throws Exception { if (st.hasMoreTokens()) return st.nextToken(); st = new StringTokenizer(br.readLine()); return next(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
e901a6201cd61084aebf776fa00d5ff2
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.util.Scanner; public class Main{ public static void main(String args[]) { Scanner sc = new Scanner(System.in); int a[] = new int[105],p[] = new int[105]; long n,m,t; t = sc.nextLong(); while(t-- > 0) { for(int i = 0; i < 105; i++) a[i] = 0; for(int i = 0; i < 105; i++) p[i] = 0; n = sc.nextLong(); m = sc.nextLong(); long sum = 0, ans = 0, temp = n; int cnt = -1; while(temp != 0) { ++cnt; if((temp % 2) == 1) p[cnt] = 1; temp >>= 1; } for(int i = 1, v; i <= m; i++) { v = sc.nextInt(); sum += v; int tep = -1; while(v != 0) { v >>= 1; tep++; } a[tep]++; } if(sum<n) { System.out.println(-1); continue; } for(int i = 0;i <= 64; i++) { if(p[i] != 0) { if(a[i] >= 1) a[i]--; else { int j=i + 1; while(a[j] == 0) { j++; } a[j]--; ans += j - i; while(j != i) { j--; a[j]++; } } } a[i+1] += a[i] / 2; } System.out.println(ans); } sc.close(); } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
6399fa45891affe6b9c02243ec783900
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.*; public class sol { static long mod=(long)Math.pow(10,9)+7; static StringBuilder sb = new StringBuilder(); static ArrayList<Integer> tree[]; static boolean vis[]; static int a[],freq[]; public static void main(String args[])throws Exception { FastReader in = new FastReader(System.in); int t=in.nextInt(),i,j; start:while(t-->0) { long n = in.nextLong(),sum=0; int m = in.nextInt(),res=0; freq = new int[32]; for(i=0;i<m;i++) { int x = in.nextInt(); sum+=x; freq[(int)(Math.log(x)/Math.log(2))]++; } if(sum<n) { sb.append("-1\n"); continue start; } i=0; while(i<31) { if(((1<<i)&n) != 0) { if(freq[i]>0) freq[i]--; else { while(i<31 && freq[i]==0) { i++; res++; } freq[i]--; continue; } } freq[i+1]+=freq[i]/2; i++; } sb.append(res+"\n"); } System.out.print(sb); } static long power(long a, long b) { if(b == 0) return 1L; long val = power(a, b / 2); if(b % 2 == 0) return val * val % mod; else return val * val % mod * a % mod; } static void prt(int a[]) { for(int i=0;i<=a.length;i++) System.out.print(a[i]+" "); System.out.println(); } static void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } static void sort(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort(arr, l, m); sort(arr , m+1, r); merge(arr, l, m, r); } } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static class Pair { int a; int b; Pair(int x, int y) { a = x; b = y; } } } class FastReader { byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } String nextLine() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c != 10 && c != 13; c = scan()) { sb.append((char) c); } return sb.toString(); } char nextChar() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; return (char) c; } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
e357f1a828fbcd86cdd57f30342cabc0
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class d { public static void print(String str,int val){ System.out.println(str+" "+val); } public long gcd(long a, long b) { if (b==0L) return a; return gcd(b,a%b); } public static void debug(long[][] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(Arrays.toString(arr[i])); } } public static void debug(int[][] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(Arrays.toString(arr[i])); } } public static void debug(String[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(arr[i]); } } public static void print(int[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } public static void print(String[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } public static void print(long[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String path) throws FileNotFoundException { br = new BufferedReader(new FileReader(path)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader s=new FastReader(); int t = s.nextInt(); for(int tt=0;tt<t;tt++){ long n = s.nextLong(); int m = s.nextInt(); long[] arr = new long[m]; for(int i=0;i<m;i++){ arr[i] = s.nextInt(); } System.out.println(solve(n,m,arr)); } } static int solve(long n,int m,long[] arr) { int[] count = new int[61]; long sum = 0; for (int i = 0; i < m; i++) { sum += arr[i]; int pow = (int) (Math.log(arr[i]) / Math.log(2)); count[pow]++; } if (sum < n) { return -1; } int ans =0; for(int i=0;i<60;i++){ if((n&(1L<<i))>0){ if(count[i]>=1){ count[i]--; count[i+1]+=((count[i])/2); } else { boolean ischanged =false; for(int j=i+1;j<60;j++){ if(count[j]>0){ ischanged = true; count[j]--; ans+=(j-i); count[i]+=(1<<(j-i)); break; } } if(ischanged){ count[i]--; count[i+1]+= ((count[i])/2); } else { return -1; } } } else { count[i+1]+=(count[i]/2); } } return ans; } // OutputStream out = new BufferedOutputStream( System.out ); // for(int i=1;i<n;i++){ // out.write((arr[i]+" ").getBytes()); // } // out.flush(); // long start_time = System.currentTimeMillis(); // long end_time = System.currentTimeMillis(); // System.out.println((end_time - start_time) + "ms"); }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
ce3334fd4027716ca31a78433541dfa1
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Solve8 { public static void main(String[] args) throws IOException { PrintWriter pw = new PrintWriter(System.out); new Solve8().solve(pw); pw.flush(); pw.close(); } public void solve(PrintWriter pw) throws IOException { FastReader sc = new FastReader(); int t = sc.nextInt(); final int MAX = 64; l: while (t-- > 0) { char[] n = padLeft(Long.toBinaryString(sc.nextLong()).toCharArray(), '0', MAX); int m = sc.nextInt(); long[] a = new long[m]; for (int i = 0; i < m; i++) { a[i] = sc.nextLong(); } int[] freq = getBitsFrequency(a); int ans = 0; for (int i = MAX - 1; i >= 0; i--) { if (n[i] == '1') { if (freq[i] > 0) { --freq[i]; } else { int j = i - 1; while (j >= 0) { if (freq[j] > 0) { break; } j--; } if (j < 0) { pw.println(-1); continue l; } while (j < i) { --freq[j]; freq[j + 1] += 2; ++ans; ++j; } --freq[i]; } } if (i - 1 >= 0) { freq[i - 1] += freq[i] / 2; } } pw.println(ans); } } public int[] getBitsFrequency(long[] arr) { final int BITS_NUMBER = 64; int[] freq = new int[BITS_NUMBER]; for (long x : arr) { for (int i = 0; i < BITS_NUMBER; i++) { if ((x & (1L << i)) != 0) { ++freq[BITS_NUMBER - 1 - i]; } } } return freq; } public char[] padLeft(char[] c, char pad, int newLength) { StringBuilder sb = new StringBuilder(); for (int i = c.length; i < newLength; i++) { sb.append(pad); } return (sb.toString() + new String(c)).toCharArray(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { } } public String next() { if (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { } return null; } public boolean hasNext() throws IOException { if (st != null && st.hasMoreTokens()) { return true; } String s = br.readLine(); if (s == null || s.isEmpty()) { return false; } st = new StringTokenizer(s); return true; } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
e44534dca38d548029b25dcc1218787b
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int tests = sc.nextInt(); while (tests-- > 0) { long n = sc.nextLong(); int m = sc.nextInt(); int[] b = new int[64]; for (int i = 0; i < m; ++i) { int ai = sc.nextInt(); for (int j = 0; j < Integer.SIZE; ++j) { if (((1 << j) & ai) > 0) { b[j]++; break; } } } boolean v = true; int c = 0; for (int i = 0; i < Long.SIZE; ++i) { if (((n >> i) & 1) == 0) continue; if (b[i] == 0) { for (int j = 0; j < i; j++) { b[j + 1] += b[j] / 2; b[j] = b[j] % 2; } } if (b[i] == 0) { for (int j = i + 1; j < Long.SIZE; ++j) { if (b[j] > 0) { for (int k = j; k > i; --k) { b[k]--; b[k - 1] += 2; c++; } break; } } } if (b[i] > 0) { b[i]--; } else { v = false; break; } } System.out.println(v ? c : -1); } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
a8ac842c303c35d57d45cc59a87d20c4
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.*; import java.util.*; public class CF1303D extends PrintWriter { CF1303D() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1303D o = new CF1303D(); o.main(); o.flush(); } static final int B = 60; void main() { int[] kk = new int[B]; int t = sc.nextInt(); while (t-- > 0) { long x = sc.nextLong(); int m = sc.nextInt(); long sum = 0; Arrays.fill(kk, 0); while (m-- > 0) { int a = sc.nextInt(); sum += a; int b = 0; while (a > 1) { a >>= 1; b++; } kk[b]++; } if (sum < x) { println(-1); continue; } int ans = 0; for (int i = 0, j = 0; i < B; i++) { if ((x & 1L << i) == 0) continue; while (j < i) { kk[j + 1] += kk[j] / 2; j++; } while (j < B && kk[j] == 0) j++; kk[j]--; if (i < j) { ans += j - i; i = j - 1; } } println(ans); } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
21ec25764ed8f90be32efc503f80f38d
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int tc=sc.nextInt(); o:while(tc-->0) { long n=sc.nextLong();int m=sc.nextInt(); long[]powersOf2=new long[64]; for(int i=0;i<m;i++) { int power=0; int x=sc.nextInt(); while(x>1) { power++; x/=2; } powersOf2[power]++; } long ans=0; for(int bit=0;bit<63;bit++) { if(((n>>bit)&1)==0)continue; long need=1; for(int b=bit;b>=0;b--) { need=Math.max(0, need-powersOf2[b]); if(need==0)break; need*=2l; } if(need==0) { need=1; for(int b=bit;b>=0;b--) { long dec=Math.min(need, powersOf2[b]); need-=dec; powersOf2[b]-=dec; if(need==0)break; need*=2l; } continue; } int wanted=-1; for(int b=bit+1;b<63;b++) { if(powersOf2[b]>0) { wanted=b;break; } } if(wanted==-1) { pw.println(-1); continue o; } for(int j=wanted;j>bit;j--) { ans++; powersOf2[j]--; powersOf2[j-1]+=2; } powersOf2[bit]--; } pw.println(ans); } pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void addX(int[]in,int x) { for(int i=0;i<in.length;i++)in[i]+=x; } static void addX(long[]in,int x) { for(int i=0;i<in.length;i++)in[i]+=x; } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
aa9714ed01c9af8996c860f76168cf98
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.*; import java.util.*; public class C { static int MAX = 63; static int get(int needed, int[] cnt) { for (int i = needed; i < cnt.length; i++) if (cnt[i] > 0) return i; return -1; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int tc = sc.nextInt(); while (tc-- > 0) { long n = sc.nextLong(); int m = sc.nextInt(); int[] cnt = new int[MAX + 5]; while (m-- > 0) { int x = sc.nextInt(); int bits = 0; for (int i = 0;; i++) if (1 << i == x) { bits = i; break; } cnt[bits]++; } long ans = 0; for (int bit = 0; bit < MAX; bit++) { if ((n & 1L << bit) > 0) { int divide = get(bit, cnt); if (divide == -1) { ans = -1; break; } if (divide > bit) { for (int i = divide - 1; i > bit; i--) cnt[i]++; cnt[bit] += 2; cnt[divide]--; } ans += divide - bit; cnt[bit]--; } cnt[bit + 1] += cnt[bit] / 2; } out.println(ans); } out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
bfd6f38b41ca999d8bcebdb90b784766
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.TreeSet; public class r82p4{ private static InputReader sc; private static PrintWriter pw; static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; InputReader(InputStream stream) { this.stream = stream; } int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } public static void main(String args[]) { sc = new InputReader(System.in); pw = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0) solve(); pw.flush(); pw.close(); } private static void solve(){ long n = sc.nextLong(); int m = sc.nextInt(), arr[] = new int[50], req[] = new int[50]; long sum = 0; for(int i=0; i<m; i++) { long input = sc.nextLong(); sum += input; for(int j=0; j<50; j++){ if((input&(1<<j)) > 0){ arr[j]++; break; } } } //pw.println(Arrays.toString(arr)); if(sum < n){ pw.println(-1); return; } int pow = 0; while(n > 0){ if((n&(1<<pow)) > 0){ n ^= (1<<pow); req[pow]++; } pow++; } //pw.println(Arrays.toString(req)); int ans = 0; for(int i=0; i<49; i++){ if(req[i] > arr[i]){ for (int j = i + 1; j < 50; j++) { if (arr[j] > 0) { int k = j - 1; while (k >= i) { arr[k + 1]--; arr[k] += 2; ans++; k--; } break; } } } arr[i] -= req[i]; arr[i+1] += arr[i]/2; arr[i] %= 2; //System.out.println(Arrays.toString(arr)); } pw.println(+ans); } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
a97b3c874d8f817bcc1e43edcb00906b
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1303d { public static void main(String[] args) throws IOException { int t = ri(); next: while(t --> 0) { long n = rnl(), bit = 1; int m = ni(), cnt[] = new int[63]; r(); for(int i = 0; i < m; ++i) { ++cnt[lg(ni())]; } /* for(int i = 0; bit <= n; bit <<= 1, ++i) { if((n & bit) > 0 && cnt[i] > 0) { --cnt[i]; n &= ~bit; } } */ bit = 1; int ans = 0; for(int i = 0; bit <= n; bit <<= 1, ++i) { if((n & bit) > 0) { long need = 1; int j = i; while(j >= 0 && need > 0) { need = max(0, need - cnt[j]); need <<= 1; if(need > 100000) { break; } --j; } if(need > 0) { j = i + 1; while(j < 63) { if(cnt[j] > 0) { ans += j - i; --cnt[j--]; while(j >= i) { ++cnt[j--]; } break; } ++j; } if(j == 63) { prln(-1); continue next; } } else { j = i; need = 1; while(need > 0) { long sub = min(need, cnt[j]); cnt[j] -= sub; need -= sub; need <<= 1; --j; } } } } prln(ans); } close(); } static int lg(int x) { int ans = 0; while(x > 1) { x >>= 1; ++ans; } return ans; } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random rand = new Random(); // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} // array util static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static <T> void reverse(T[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {T swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(char[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); char swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); Arrays.sort(a);} static void rsort(long[] a) {shuffle(a); Arrays.sort(a);} static void rsort(double[] a) {shuffle(a); Arrays.sort(a);} static void rsort(char[] a) {shuffle(a); Arrays.sort(a);} static <T> void rsort(T[] a) {shuffle(a); Arrays.sort(a);} static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;} // graph util static void connect(List<Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()) - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); __out.println(iter.next());} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
46c2440ec18d10fbfe1db0d0285162a0
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
// package com.codeforces; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class FillTheBag { private static Map<Long, Integer> power = new HashMap<>(); private static long[] result = new long[70]; private long[] has = new long[70]; private long[] size = new long[70]; private long sizeSum = 0; private long hasSum = 0; static { result[0] = 1; power.put(result[0], 0); for(int i = 1; i < 63; i++) { result[i] = result[i-1] * 2; power.put(result[i], i); } } public void setSize(long bag) { this.sizeSum = bag; for(int i = 62; i >= 0 && bag != 0; i--) { while(bag >= result[i]) { bag -= result[i]; size[i]++; } } } public void addBox(long boxSize) { this.hasSum += boxSize; has[power.get(boxSize)]++; } private int borrow(int i) { int ans = 1; if(has[i+1] == 0) ans += borrow(i+1); has[i+1]--; has[i] += 2; return ans; } public int minCut() { if(hasSum < sizeSum) return -1; int ans = 0; for(int i = 0, j = 0; i < 62; i++) { while(true) { if (size[j] <= has[i]) { has[i + 1] += (has[i] - size[j]) / 2; j++; break; } else { ans += borrow(i); } } } return ans; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for( ; t > 0; t--) { FillTheBag fillTheBag = new FillTheBag(); fillTheBag.setSize(in.nextLong()); for(int i = in.nextInt(); i > 0; i--) { fillTheBag.addBox(in.nextLong()); } System.out.println(fillTheBag.minCut()); } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
63d901ed99f131b8c5b14eccecea7c61
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author LUCIANO. */ import java.util.*; public class Solve { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner in = new Scanner(System.in); int t = Integer.parseInt(in.next()); for(int tt = 0; tt < t; tt++) { int[] boxes = new int[64]; long n = in.nextLong(); int m = in.nextInt(); for(int i = 0; i < m; i++) { int log = (int) (Math.log(in.nextLong()) / Math.log(2)); boxes[log] += 1; } int ans = 0; for(int i = 0; i < 64; i++) { if(((n >> i) & 1) == 1) { boolean mk = make(boxes, i); if(mk == false) { int spt = split(boxes, i); if(spt == -1) { ans = -1; break; }else{ ans += spt; } } } } System.out.println(ans); } } public static boolean make(int[] boxes, int pos) { long count = 0; int[] fake = new int[64]; for(int i = pos; i >= 0; i--) { if(count < (long) Math.pow(2, pos) && boxes[i] > 0) { int condition = boxes[i]; for(int j = 0; j < condition; j++) { count += (long) Math.pow(2, i); boxes[i] -= 1; fake[i] += 1; if(count >= (long) Math.pow(2, pos)) { break; } } } } if(count < (long) Math.pow(2, pos)) { for(int i = 0; i < 64; i++) { boxes[i] += fake[i]; } return false; } return true; } public static int split(int[] boxes, int pos) { int cnt = 0; for(int i = pos + 1; i < 64; i++) { if(boxes[i] > 0) { boxes[i] -= 1; for(int j = i; j > pos; j--) { cnt += 1; boxes[j - 1] += 1; } break; } } if(cnt == 0) return -1; else return cnt; } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
13ee79964d89d7b07cf6b62309259ac4
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; /* Hepler Class Methods **only Few Imp Ones** * int[][] getIntMatrix(String s,int r,int c) //Works only for int and long * char getCharacterValue(int i) * int getIntegerValueOfCharacter(char c) * boolean isPerfectSquare(int n) // works only for int and long * int getLargestPrimeFactor(int n) //works only for int and long * boolean isPrime(int n) //works only for int and long * void printArray(int a[]), //works for all * void printMatrix(int a[][]), //works for all * void printNestedList(ArrayList<ArrayList<Integer>> a) //works for all * boolean isPalindrome //works for all except Character * T swap(T) //works only for int[],long[] and String * T getArraySum(T[]) //works only for int[],long[],double[] * T reverse(T) //works only for String,int and long * T[] getReverseArray(T[]) //works for all * HashSet<T> getHashSet(T[]) //works for int[],long[],char[],String[] * T setBit(T,k,side) //works only when n = int or long and k is always int **returns int or long** * String setBitString(T,k,side) //works only when n = int or long and k is always int **returns String** * int getSetBits(long n) //Gives Number of sets bits in a number * String cvtToBinary(T) * int cvtToDecimal(String n) //Always returns Long * boolean isPowerOf2(T) * boolean isSafe(T [][], row,col) //Returns whether current row and col are under bounds * T Log2(T num) //Returns (Math.log(num) / Math.log(2)) * long nCr(long n,long r) // Returns nCr value * long nCrMod(long n,long r) // Returns nCr % MOD value * */ public class A { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); static Helper sc = new Helper(br); static int MOD = 1000000007,INF = Integer.MAX_VALUE,NEG_INF = Integer.MIN_VALUE,SEM_INF = INF / 2; //BigInteger B = new BigInteger("1"); //Scanner scanner = new Scanner(System.in); public static void main(String args[]) { try { int t = sc.getInt(br.readLine()); while (t-- > 0) { testCase(); } out.flush(); }catch (Exception e){ System.out.println("Exception Occured: " + e.getMessage()); e.printStackTrace(); } } private static void testCase() throws Exception { long bagSize = sc.nextLong();int n = sc.nextInt(); long a[] = sc.getLongArray(br.readLine()); int count[] = new int[65]; Arrays.parallelSort(a,0,n); sc.getReverseArray(a); long sum = 0; for(int x = 0;x < n;x++) { long num = a[x]; for(int i = 0;i < 32;i++) { if(((num >> i) & 1) == 1) { count[i]++; break; } } sum += a[x]; } if(sum < bagSize) { writeln(-1); return; } int ans = 0; for(int x = 0;x < 60;) { if(((bagSize >> x) & 1) == 1) { if(count[x] > 0) { count[x]--; }else { while(x < 60 && count[x] == 0) { ans++; x++; } count[x] -=1; continue; } } count[x + 1] += count[x] / 2; x++; } writeln(ans); } public static void writeln() throws Exception { out.write("\n"); } public static void write(Object o) throws Exception { out.write(String.valueOf(o)); } public static void writeln(Object o) throws Exception { out.write(String.valueOf(o) + "\n"); } public static void println() { System.out.println(); } public static void print(Object o) { System.out.print(String.valueOf(o)); } public static void println(Object o) { System.out.println(String.valueOf(o)); } static class Helper { FastReader fr; /*Constructor*/ public Helper(BufferedReader br) { try{ fr = new FastReader(br); }catch (Exception e){ System.out.println("Exception Occured: " + e.getMessage()); e.printStackTrace(); } } /* Inputs*/ public String next() throws Exception { return fr.next(); } public int nextInt() throws Exception { return fr.nextInt(); } public long nextLong() throws Exception { return fr.nextLong(); } public String trimLine() throws Exception { return fr.trimLine(); } public String rawLine() throws Exception { return fr.nextLine(); } public double nextDouble() throws Exception { return fr.nextDouble(); } public float nextFloat() throws Exception { return fr.nextFloat(); } public int [] getIntArray( String s) throws Exception { String input[] = s.split(" "); int res[] = new int[input.length]; for(int x = 0;x < res.length;x++) res[x] = getInt(input[x]); return res; } public long [] getLongArray( String s) throws Exception { String input[] = s.split(" "); long res[] = new long[input.length]; for(int x = 0;x < res.length;x++) res[x] = getLong(input[x]); return res; } public double [] getDoubleArray( String s) throws Exception { String input[] = s.split(" "); double res[] = new double[input.length]; for(int x = 0;x < res.length;x++) res[x] = getDouble(input[x]); return res; } public int[][] getIntMatrix(String s,int r,int c) { int i = 0;int mat[][] = new int[r][c]; String st[] = s.split(" "); for(int x = 0;x < r;x++) for(int y =0 ;y < c;y++) mat[x][y] = Integer.parseInt(st[i++]); return mat; } public long[][] getlongMatrix(String s,int r,int c) { int i = 0;long mat[][] = new long[r][c]; String st[] = s.split(" "); for(int x = 0;x < r;x++) for(int y =0 ;y < c;y++) mat[x][y] = Long.parseLong(st[i++]); return mat; } public int getInt(String s) { return Integer.parseInt(s); } public long getLong(String s) { return Long.parseLong(s); } public float getFloat(String s) { return Float.parseFloat(s); } public double getDouble(String s) { return Double.parseDouble(s); } /*Some basic hepler methods*/ public char getCharacterValue(int i) { return (char)i; } public int getIntegerValueOfCharacter(char c) { return (int)c; } public int Log2(int num) { return (int)(Math.log(num) / Math.log(2)); } public long Log2(long num) { return (long) (Math.log(num) / Math.log(2)); } public double Log2(double num) { return (double) (Math.log(num) / Math.log(2)); } public long nCr(long n,long r) { if(r > n - r) r = n - r; long res = 1; for(long x = 0;x < r;x++) { res *= (n - x); res /= (x + 1); } return res; } public long nCrMod(long n,long r,long md) { if(r > n - r) r = n - r; long res = 1; for(long x = 0;x < r;x++) { res = (res * (n - x)) % md; res /= (x + 1); } return res % md; } public int getGCD(int a,int b) { if(b == 0) return a; return getGCD(b,a % b); } public long getGCD(long a,long b) { if(b == 0) return a; return getGCD(b,a % b); } public double getGCD(double a,double b) { if(b == 0) return a; return getGCD(b,a % b); } public float getGCD(float a,float b) { if(b == 0) return a; return getGCD(b,a % b); } public int getLCM(int a,int b) { return ((a * b) / getGCD(a,b)); } public long getLCM(long a,long b) { return ((a * b) / getGCD(a,b)); } public double getLCM(double a,double b) { return ((a * b) / getGCD(a,b)); } public float getLCM(float a,float b) { return ((a * b) / getGCD(a,b)); } public boolean isSafe(int a[][],int x,int y) { if(x >=0 && y >= 0 && x < a.length && y < a[0].length) return true; return false; } public boolean isSafe(long a[][],int x,int y) { if(x >=0 && y >= 0 && x < a.length && y < a[0].length) return true; return false; } public boolean isSafe(double a[][],int x,int y) { if(x >=0 && y >= 0 && x < a.length && y < a[0].length) return true; return false; } public boolean isSafe(char a[][],int x,int y) { if(x >=0 && y >= 0 && x < a.length && y < a[0].length) return true; return false; } public boolean isPerfectSquare(int n) { if(n == 0 || n == 1) return true; if(n == 2 || n == 3) return false; double d = Math.sqrt(n); return (d - Math.floor(d) == 0); } public boolean isPerfectSquare(long n) { if(n == 0 || n == 1) return true; if(n == 2 || n == 3) return false; double d = Math.sqrt(n); return (d - Math.floor(d) == 0); } public boolean isPowerOf2(long n) { return n != 0 && (n & (n - 1)) == 0; } public long fastPow(long n,long p) { long res = 1; while(p > 0){ if(p % 2 != 0) res = res * n; p = p / 2; n = n * n; } return res; } public long modPow(long n,long p,long md) { long res = 1; n = n % md; if(n == 0) return 0; while(p > 0){ if(p % 2 != 0) res = ((res % md) * (n % md)) % md; p = p / 2; n = ((n % md) * (n % md)) % md; } return (res % md); } public boolean isPalindrome(int n) { StringBuilder sb = new StringBuilder(n + ""); return (Integer.parseInt(sb.reverse().toString()) == n); } public boolean isPalindrome(long n) { StringBuilder sb = new StringBuilder(n + ""); return (Long.parseLong(sb.reverse().toString()) == n); } public boolean isPalindrome(String s) { StringBuilder sb = new StringBuilder(s + ""); return (sb.reverse().toString().equals(s)); } public int getSmallestPrimeFactor(int n) { if(n == 1 || n == 0) return n; if(n % 2 == 0) return 2; else if(n % 3 == 0) return 3; int pf = -1; for(int x = 3;x <= Math.sqrt(n);x += 2) if(n % x == 0) return x; return n; } public int getLargestPrimeFactor(int n) { int pf = -1; if(n == 1 || n == 2 || n == 3 || n == 0) return n; while(n % 2 == 0){ pf = 2; n /= 2; } for(int x = 3;x <= Math.sqrt(n);x += 2) while (n % x == 0){ pf = x; n /= x; } if(n > 2) pf = n; return pf; } public long getSmallestPrimeFactor(long n) { if(n == 1 || n == 0) return n; if(n % 2 == 0) return 2; else if(n % 3 == 0) return 3; for(long x = 3;x <= Math.sqrt(n);x += 2) if(n % x == 0) return x; return n; } public long getLargestPrimeFactor(long n) { long pf = -1; if(n == 1 || n == 2 || n == 3 || n == 0) return n; while(n % 2 == 0){ pf = 2; n /= 2; } for(long x = 3;x <= Math.sqrt(n);x += 2) while (n % x == 0){ pf = x; n /= x; } if(n > 2) pf = n; return pf; } public boolean isPrime(int n) { if(n == 0 || n == 1) return false; if(getLargestPrimeFactor(n) == n) return true; return false; } public boolean isPrime(long n) { if(n == 0 || n == 1) return false; if(getLargestPrimeFactor(n) == n) return true; return false; } public int getSetBits(long n) { int count = 0; while (n > 0){ count += n % 2; n /= 2; } return count; } public int setBit(int n,int k,String side) throws Exception { if(side.equalsIgnoreCase("r") || side.equalsIgnoreCase("right")){ return ((1 << k) | n); }else if(side.equalsIgnoreCase("l") || side.equalsIgnoreCase("left")){ return (int)cvtToDecimal(setBitString(n,k,"l")); }else throw new Exception("Unknown Side of shift! side must be l,left,r,right"); } public long setBit(long n,int k,String side) throws Exception { if(side.equalsIgnoreCase("r") || side.equalsIgnoreCase("right")){ return ((1 << k) | n); }else if(side.equalsIgnoreCase("l") || side.equalsIgnoreCase("left")){ return cvtToDecimal(setBitString(n,k,"l")); }else throw new Exception("Unknown Side of shift! side must be l,left,r,right"); } public String setBitString(int n,int k,String side) throws Exception { StringBuilder sb = new StringBuilder(cvtToBinary(n) + ""); if(side.equalsIgnoreCase("r") || side.equalsIgnoreCase("right")){ sb.setCharAt(sb.length() - 1 - k,'1'); }else if(side.equalsIgnoreCase("l") || side.equalsIgnoreCase("left")){ sb.setCharAt(k,'1'); }else throw new Exception("Unknown Side of shift! side must be l,left,r,right"); return sb.toString(); } public String setBitString(long n, int k,String side) throws Exception { StringBuilder sb = new StringBuilder(cvtToBinary(n) + ""); if(side.equalsIgnoreCase("r") || side.equalsIgnoreCase("right")){ sb.setCharAt(sb.length() - 1 - k,'1'); }else if(side.equalsIgnoreCase("l") || side.equalsIgnoreCase("left")){ sb.setCharAt(k,'1'); }else throw new Exception("Unknown Side of shift! side must be l,left,r,right"); return sb.toString(); } public long cvtToDecimal(String n) { String num = n; long dec_value = 0; // Initializing base value to 1, // i.e 2^0 long base = 1; int len = num.length(); for (int i = len - 1; i >= 0; i--) { if (num.charAt(i) == '1') dec_value += base; base = base * 2; } return dec_value; } public String cvtToBinary(int n) { if(n == 0 || n == 1) return "" + n; StringBuilder sb = new StringBuilder(); while (n > 1){ if(n % 2 == 0) sb.append(0); else sb.append(1); n /= 2; } if(n == 1) sb.append(1); return sb.reverse().toString(); } public String cvtToBinary(long n) { if(n == 0 || n == 1) return "" + n; StringBuilder sb = new StringBuilder(); while (n > 1){ if(n % 2 == 0) sb.append(0); else sb.append(1); n /= 2; } if(n == 1) sb.append(1); return sb.reverse().toString(); } /*Printing Arena*/ public void print(BufferedWriter out,Object s) throws Exception { out.write(String.valueOf(s)); } public void println(BufferedWriter out,Object s) throws Exception { out.write(String.valueOf(s)); } public void printArray(int a[],int s,int e,boolean nextLine) { if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + s + ", " + e + "] Array Size: " + a.length); for(int x = s;x <= e;x++) System.out.print(String.valueOf(a[x]) + " "); if(nextLine) System.out.println(); } public void printArray(long a[],int s,int e,boolean nextLine) { if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + s + ", " + e + "] Array Size: " + a.length); for(int x = s;x <= e;x++) System.out.print(String.valueOf(a[x]) + " "); if(nextLine) System.out.println(); } public void printArray(char a[],int s,int e,boolean nextLine) { if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + s + ", " + e + "] Array Size: " + a.length); for(int x = s;x <= e;x++) System.out.print(String.valueOf(a[x]) + " "); if(nextLine) System.out.println(); } public void printArray(double a[],int s,int e,boolean nextLine) { if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + s + ", " + e + "] Array Size: " + a.length); for(int x = s;x <= e;x++) System.out.print(String.valueOf(a[x]) + " "); if(nextLine) System.out.println(); } public void printArray(String a[],int s,int e,boolean nextLine) { if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + s + ", " + e + "] Array Size: " + a.length); for(int x = s;x <= e;x++) System.out.print(String.valueOf(a[x]) + " "); if(nextLine) System.out.println(); } public void printArray(Object a[],int s,int e,boolean nextLine) { if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + s + ", " + e + "] Array Size: " + a.length); for(int x = s;x <= e;x++) System.out.print(a[x].toString() + " "); if(nextLine) System.out.println(); } public void printMatrix(int a[][]) { for(int x = 0;x < a.length;x++){ for (int y = 0;y < a[0].length;y++) System.out.print(a[x][y] + " "); System.out.println(); } } public void printMatrix(long a[][]) { for(int x = 0;x < a.length;x++){ for (int y = 0;y < a[0].length;y++) System.out.print(String.valueOf(a[x][y]) + " "); System.out.println(); } } public void printMatrix(char a[][]) { for(int x = 0;x < a.length;x++){ for (int y = 0;y < a[0].length;y++) System.out.print(String.valueOf(a[x][y]) + " "); System.out.println(); } } public void printMatrix(double a[][]) { for(int x = 0;x < a.length;x++){ for (int y = 0;y < a[0].length;y++) System.out.print(String.valueOf(a[x][y]) + " "); System.out.println(); } } public void printMatrix(String a[][]) { for(int x = 0;x < a.length;x++){ for (int y = 0;y < a[0].length;y++) System.out.print(String.valueOf(a[x][y]) + " "); System.out.println(); } } public void printMatrix(Object a[][]) { for(int x = 0;x < a.length;x++){ for (int y = 0;y < a[0].length;y++) System.out.print(a[x][y].toString() + " "); System.out.println(); } } public void printIntNestedList(ArrayList<ArrayList<Integer>> a) { for(int x = 0;x < a.size();x++){ ArrayList<Integer> al = a.get(x); for(int y = 0;y < al.size();y++) System.out.print(String.valueOf(al.get(y)) + " "); System.out.println(); } } public void printLongNestedList(ArrayList<ArrayList<Long>> a) { for(int x = 0;x < a.size();x++){ ArrayList<Long> al = a.get(x); for(int y = 0;y < al.size();y++) System.out.print(String.valueOf(al.get(y)) + " "); System.out.println(); } } public void printCharNestedList(ArrayList<ArrayList<Character>> a) { for(int x = 0;x < a.size();x++){ ArrayList<Character> al = a.get(x); for(int y = 0;y < al.size();y++) System.out.print(String.valueOf(al.get(y)) + " "); System.out.println(); } } public void printStringNestedList(ArrayList<ArrayList<String>> a) { for(int x = 0;x < a.size();x++){ ArrayList<String> al = a.get(x); for(int y = 0;y < al.size();y++) System.out.print(String.valueOf(al.get(y)) + " "); System.out.println(); } } public String swap(String st,int i,int j) { StringBuilder sb = new StringBuilder(st); sb.setCharAt(i,st.charAt(j)); sb.setCharAt(j,st.charAt(i)); return sb.toString(); } public int [] swap(int a[],int i,int j) { int t = a[i]; a[i] = a[j]; a[j] = t; return a; } public long[] swap(long a[],int i,int j) { long t = a[i]; a[i] = a[j]; a[j] = t; return a; } public long getArraySum(int a[],int s,int e) { long sum = 0; if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + e + ", " + s + "]"); for(int x = s;x <= e;x++) sum += a[x]; return sum; } public long getArraySum(long a[],int s,int e) { long sum = 0; if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + e + ", " + s + "]"); for(int x = s;x <= e;x++) sum += a[x]; return sum; } public double getArraySum(double a[],int s,int e) { double sum = 0; if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + e + ", " + s + "]"); for(int x = s;x <= e;x++) sum += a[x]; return sum; } public int reverse(int n) { StringBuilder sb = new StringBuilder(n + ""); return Integer.parseInt(sb.reverse().toString()); } public long reverse(long n) { StringBuilder sb = new StringBuilder(n + ""); return Long.parseLong(sb.reverse().toString()); } public String reverse(String s) { StringBuilder sb = new StringBuilder(s + ""); return sb.reverse().toString(); } public Object[] getReverseArray(Object a[]) { int i = 0,j = a.length - 1; while (i <= j) { Object o = a[i]; a[i] = a[j]; a[j] = o; i++;j--; } return a; } public int[] getReverseArray(int a[]) { int i = 0,j = a.length - 1; while (i <= j) { int o = a[i]; a[i] = a[j]; a[j] = o; i++;j--; } return a; } public double[] getReverseArray(double a[]) { int i = 0,j = a.length - 1; while (i <= j) { double o = a[i]; a[i] = a[j]; a[j] = o; i++;j--; } return a; } public char[] getReverseArray(char a[]) { int i = 0,j = a.length - 1; while (i <= j) { char o = a[i]; a[i] = a[j]; a[j] = o; i++;j--; } return a; } public long[] getReverseArray(long a[]) { int i = 0,j = a.length - 1; while (i <= j) { long o = a[i]; a[i] = a[j]; a[j] = o; i++;j--; } return a; } public String[] getReverseArray(String a[]) { int i = 0,j = a.length - 1; while (i <= j) { String o = a[i]; a[i] = a[j]; a[j] = o; i++;j--; } return a; } public HashSet<Integer> getHashSet(int a[]) { HashSet<Integer> set = new HashSet<>(); for(int x = 0;x < a.length;x++) set.add(a[x]); return set; } public HashSet<Long> getHashSet(long a[]) { HashSet<Long> set = new HashSet<>(); for(int x = 0;x < a.length;x++) set.add(a[x]); return set; } public HashSet<Character> getHashSet(char a[]) { HashSet<Character> set = new HashSet<>(); for(int x = 0;x < a.length;x++) set.add(a[x]); return set; } public HashSet<String> getHashSet(String a[]) { HashSet<String> set = new HashSet<>(); for(int x = 0;x < a.length;x++) set.add(a[x]); return set; } public int getMax(int a[]) { int max = Integer.MIN_VALUE; for(int x = 0;x < a.length;x++) max = Math.max(max,a[x]); return max; } public long getMax(long a[]) { long max = Long.MIN_VALUE; for(int x = 0;x < a.length;x++) max = Math.max(max,a[x]); return max; } public double getMax(double a[]) { double max = Double.MIN_VALUE; for(int x = 0;x < a.length;x++) max = Math.max(max,a[x]); return max; } public int getMin(int a[]) { int min = Integer.MAX_VALUE; for(int x = 0;x < a.length;x++) min = Math.min(min,a[x]); return min; } public long getMin(long a[]) { long min = Long.MAX_VALUE; for(int x = 0;x < a.length;x++) min = Math.min(min,a[x]); return min; } public double getMin(double a[]) { double min = Double.MAX_VALUE; for(int x = 0;x < a.length;x++) min = Math.min(min,a[x]); return min; } private class FastReader { BufferedReader br; StringTokenizer st; public FastReader(BufferedReader br) throws Exception { this.br = br; } public String next() throws Exception { if(st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public String trimLine() throws Exception { try{ return br.readLine().trim(); }catch (Exception e){ System.out.println("Exception Occured: " + e.getMessage()); e.printStackTrace(); return null; } } public String nextLine() throws Exception { try{ return br.readLine(); }catch (Exception e){ System.out.println("Exception Occured: " + e.getMessage()); e.printStackTrace(); return null; } } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public float nextFloat() throws Exception { return Float.parseFloat(next()); } } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
880e3e28606bee84723f68f667585a84
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.util.Scanner; import java.util.HashMap; import java.util.Arrays; public class FillTheBag { public static void main(String[] args) { Scanner s = new Scanner(System.in); int c = s.nextInt(); for (int i = 0; i < c; i++) { long n = s.nextLong(); int m = s.nextInt(); int[] cnt = new int[65]; int[] cMap = new int[65]; HashMap<Integer,Integer> hm = new HashMap<>(); for (int j = 0, v = 1; j < 32; j++, v*=2) { cMap[j] = v; hm.put(v, j); } long sum = 0; for (int j = 0; j < m; j++) { int tmp = s.nextInt(); cnt[hm.get(tmp)]++; sum += (long)tmp; } //System.out.println(Long.toBinaryString(n)); //System.out.println(Long.toBinaryString(sum)); if (n > sum) { System.out.println(-1); continue; } int ret = 0; for (int b = 0; b < 64; b++) { boolean isSet = (n & (1L << b)) > 0; //System.out.println(Arrays.toString(cnt)); if (isSet) { //System.out.println(b); if (cnt[b] > 0) { cnt[b]--; cnt[b+1] += cnt[b] / 2; } else { int shift = b + 1; while (shift < 65 && cnt[shift] == 0) shift++; cnt[shift]--; ret += shift - b; while (--shift >= b) cnt[shift]++; } } else { cnt[b+1] += cnt[b] / 2; } } System.out.println(ret); } s.close(); } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
86b17ad5257daf4443d2255bdf3b10ad
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.InputMismatchException; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); Output out = new Output(outputStream); DFillTheBag solver = new DFillTheBag(); int testCount = Integer.parseInt(in.next()); for(int i = 1; i<=testCount; i++) solver.solve(i, in, out); out.close(); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29); thread.start(); thread.join(); } static class DFillTheBag { public DFillTheBag() { } public void solve(int kase, InputReader in, Output pw) { long n = in.nextLong(); int m = in.nextInt(), ans = 0; int[] cnt = new int[64]; for(int i = 0; i<m; i++) { cnt[63-Long.numberOfLeadingZeros(in.nextInt())]++; } for(int i = 0; i<63; i++) { boolean on = (n&1L<<i)>0; if(on) { if(cnt[i]==0) { int j; for(j = i; j<=63&&cnt[j]==0; j++) ; if(j==64) { pw.println("-1"); return; } ans += j-i; cnt[j]--; cnt[i] += 1<<j-i; } cnt[i]--; } cnt[i+1] += cnt[i] >> 1; } pw.println(ans); } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public boolean autoFlush; public String LineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); autoFlush = false; LineSeparator = System.lineSeparator(); } public void println(int i) { println(String.valueOf(i)); } public void println(String s) { sb.append(s); println(); if(autoFlush) { flush(); }else if(sb.length()>BUFFER_SIZE >> 1) { flushToBuffer(); } } public void println() { sb.append(LineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static interface InputReader { int nextInt(); long nextLong(); } static class FastReader implements InputReader { final private int BUFFER_SIZE = 1<<16; private DataInputStream din; private byte[] buffer; private int bufferPointer; private int bytesRead; public FastReader(InputStream is) { din = new DataInputStream(is); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String next() { StringBuilder ret = new StringBuilder(64); byte c = skip(); while(c!=-1&&!isSpaceChar(c)) { ret.appendCodePoint(c); c = read(); } return ret.toString(); } public int nextInt() { int ret = 0; byte c = skipToDigit(); boolean neg = (c=='-'); if(neg) { c = read(); } do { ret = ret*10+c-'0'; } while((c = read())>='0'&&c<='9'); if(neg) { return -ret; } return ret; } public long nextLong() { long ret = 0; byte c = skipToDigit(); boolean neg = (c=='-'); if(neg) { c = read(); } do { ret = ret*10+c-'0'; } while((c = read())>='0'&&c<='9'); if(neg) { return -ret; } return ret; } private boolean isSpaceChar(byte b) { return b==' '||b=='\r'||b=='\n'||b=='\t'||b=='\f'; } private byte skip() { byte ret; while(isSpaceChar((ret = read()))) ; return ret; } private boolean isDigit(byte b) { return b>='0'&&b<='9'; } private byte skipToDigit() { byte ret; while(!isDigit(ret = read())&&ret!='-') ; return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); }catch(IOException e) { e.printStackTrace(); throw new InputMismatchException(); } if(bytesRead==-1) { buffer[0] = -1; } } private byte read() { if(bytesRead==-1) { throw new InputMismatchException(); }else if(bufferPointer==bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
8352382cbd5621c810433a4478c5adf7
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.*; import java.util.*; public class D { void solve(FastIO io) { long n = io.nextLong(); int m = io.nextInt(); long all = 0; Long[] sort = new Long[m]; for (int i = 0; i < m; i++) all += sort[i] = io.nextLong(); if (all < n) { io.println(-1); return; } Arrays.sort(sort); long[] a = new long[m]; for (int i = 0; i < m; i++) a[i] = sort[i]; long sum = 0; ArrayList<Long> bits = new ArrayList<>(); for (int i = 0; i < 64; i++) if ((n & (1L << i)) != 0) bits.add(1L << i); int i = 0, j = 0; long ans = 0; while (j < bits.size()) { long b = bits.get(j); if (sum >= b) { j++; sum -= b; continue; } if (i >= n) break; if (a[i] > b) { long k = 0; while (a[i] >> k > b) k++; sum += a[i] - b; ans += k; i++; } else { sum += a[i]; i++; } } io.println(ans); } public static void main(String[] args) { FastIO io = new FastIO(); int t = io.nextInt(); for (int i = 0; i < t; i++) new D().solve(io); io.close(); } static class FastIO extends PrintWriter { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); FastIO() { super(System.out); } public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(r.readLine()); } catch (Exception e) { //TODO: handle exception } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
2dcfa3b28bed9645d0fc5a52afb282ff
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jenish */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DFillTheBag solver = new DFillTheBag(); solver.solve(1, in, out); out.close(); } static class DFillTheBag { int find(int n) { int c = 0; while (n > 1) { c++; n /= 2; } return c; } public void solve(int testNumber, ScanReader in, PrintWriter out) { int t = in.scanInt(); while (t-- > 0) { long n = in.scanLong(); int m = in.scanInt(); int arr[] = new int[m]; in.scanInt(arr); long sum = 0; for (int k : arr) sum += k + 0l; int hash[] = new int[64]; int bitres[] = new int[64]; for (int i = 0; i < 60; i++) if ((n & (1l << i)) != 0) bitres[i]++; for (int i : arr) hash[find(i)]++; if (sum < n) { out.println(-1); } else { long ans = 0; for (int i = 0; i < 60; ++i) { if (bitres[i] > 0) { if (hash[i] == 0) { int j = i + 1; while (hash[j] == 0) ++j; hash[j]--; while (--j >= i) { hash[j]++; ans++; } hash[i]++; } hash[i]--; } hash[i + 1] += hash[i] / 2; } out.println(ans); } } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int INDEX; private BufferedInputStream in; private int TOTAL; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (INDEX >= TOTAL) { INDEX = 0; try { TOTAL = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (TOTAL <= 0) return -1; } return buf[INDEX++]; } public int scanInt() { int I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } public long scanLong() { long I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } public void scanInt(int[] A) { for (int i = 0; i < A.length; i++) A[i] = scanInt(); } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
e3b78a605d82f3e9c56c922035c55dc3
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static int get(int needed, int[] cnt) { for (int i = needed; i < cnt.length; i++) if (cnt[i] > 0) return i; return -1; } public static void main (String[]args) throws IOException { Scanner in = new Scanner(System.in); try (PrintWriter or = new PrintWriter(System.out)) { int t=in.nextInt(); while (t-->0) { long n = in.nextLong(); int m=in.nextInt(); int[] cnt = new int[68]; while (m-- > 0) { int x = in.nextInt(); int bits = 0; for (int i = 0;; i++) if (1 << i == x) { bits = i; break; } cnt[bits]++; } long ans = 0; for (int bit = 0; bit < 63; bit++) { if ((n & (1L << bit)) > 0) { int divide = get(bit, cnt); if (divide == -1) { ans = -1; break; } if (divide > bit) { for (int i = divide - 1; i > bit; i--) cnt[i]++; cnt[bit] += 2; cnt[divide]--; } ans += divide - bit; cnt[bit]--; } cnt[bit + 1] += cnt[bit] / 2; } or.println(ans); } } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static int getlen(int r,int l,int a){ return (r-l+1+1)/(a+1); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) { if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) { f *= 10; } } } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } } class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } @Override public int compareTo(Pair o) { if (first!=o.first)return first-o.first; return second-o.second; } } class Tempo { int first,second,third; public Tempo(int first, int second, int third) { this.first = first; this.second = second; this.third = third; } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
82fd944ecafd709aa33124d84b465492
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.*; import java.util.*; //import javafx.util.*; import java.math.*; //import java.lang.*; public class Main { // static int n; static HashSet<Integer> adj[]; static boolean vis[]; // static long ans[]; static int arr[]; static long mod=1000000007; static final long oo=(long)1e18; // static int n; public static void main(String[] args) throws IOException { // Scanner sc=new Scanner(System.in); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); br = new BufferedReader(new InputStreamReader(System.in)); int test=nextInt(); // int test=1; outer: while(test--!=0){ int a[]=new int[64]; long n=nextLong(); int m=nextInt(); Long arr[]=new Long[m]; for(int i=0;i<m;i++){ arr[i]=nextLong(); a[(int)(Math.log(arr[i])/Math.log(2))]++; } int ans=0; for(int i=0;i<62;i++){ if((n&(1l<<i))!=0){ // pw.println(i); boolean yes=false; int j=i; for(j=i;j<62;j++){ if(a[j]>0){ yes=true; break; } } if(yes){ while(j!=i){ a[j]--; a[j-1]+=2; ans++; j--; } a[j]--; } else{ pw.println("-1"); continue outer; } } a[i+1]+=a[i]/2; } pw.println(ans); // Arrays.sort(arr,Collections.reverseOrder()); } pw.close(); } static boolean dfs(int v,int parent){ // System.out.println(v); vis[v]=true; for(int a:adj[v]){ if(!vis[a]){ if(dfs(a,v)){ return true; } } else if(a!=parent){ return true; } } return false; } static ArrayList<ArrayList<Integer>> permutation2(int[] a, int n) { ArrayList<ArrayList<Integer>> gen = new ArrayList<>(); if(n == 1) { ArrayList<Integer> new_permutation = new ArrayList<>(); new_permutation.add(a[n-1]); gen.add(new_permutation); } else { Iterator<ArrayList<Integer>> itr = permutation2(a, n-1).iterator(); while(itr.hasNext()) { ArrayList<Integer> permutation = itr.next(); // (create new permutation with this element in every position) for(int i = 0;i <= permutation.size();i++) { ArrayList<Integer> new_permutation = new ArrayList<>(permutation); new_permutation.add(i, a[n-1]); gen.add(new_permutation); } } } return gen; } static void decToBinary(int n) { // array to store binary number int[] binaryNum = new int[1000]; // counter for binary array int i = 0; while (n > 0) { // storing remainder in binary array binaryNum[i] = n % 2; n = n / 2; i++; } // printing binary array in reverse order for (int j = i - 1; j >= 0; j--) System.out.print(binaryNum[j]); System.out.println(); } static long ncr(long n,long r){ if(r==0) return 1; long val=ncr(n-1,r-1); val=(n*val)%mod; val=(val*modInverse(r,mod))%mod; return val; } static int find(ArrayList<Integer> a,int i){ if(a.size()==0||i<0)return 0; ArrayList<Integer> l=new ArrayList<Integer>(); ArrayList<Integer> r=new ArrayList<Integer>(); for(int v:a){ if((v&(1<<i))!=0)l.add(v); else r.add(v); } if(l.size()==0)return find(r,i-1); if(r.size()==0)return find(l,i-1); return Math.min(find(l,i-1),find(r,i-1))+(1<<i); } public static BufferedReader br; public static StringTokenizer st; public static String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return st.nextToken(); } public static Integer nextInt() { return Integer.parseInt(next()); } public static Long nextLong() { return Long.parseLong(next()); } public static Double nextDouble() { return Double.parseDouble(next()); } // static class Pair{ // int x;int y; // Pair(int x,int y,int z){ // this.x=x; // this.y=y; // // this.z=z; // // this.z=z; // // this.i=i; // } // } // static class sorting implements Comparator<Pair>{ // public int compare(Pair a,Pair b){ // //return (a.y)-(b.y); // if(a.y==b.y){ // return -1*(a.z-b.z); // } // return (a.y-b.y); // } // } public static int[] na(int n)throws IOException{ int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = nextInt(); return a; } static class query implements Comparable<query>{ int l,r,idx,block; static int len; query(int l,int r,int i){ this.l=l; this.r=r; this.idx=i; this.block=l/len; } public int compareTo(query a){ return block==a.block?r-a.r:block-a.block; } } static class Pair implements Comparable<Pair>{ int x;int y; Pair(int x,int y){ this.x=x; this.y=y; //this.z=z; } public int compareTo(Pair p){ //return (x-p.x); if(x>p.x) return 1; if(x<p.x) return -1; return y-p.y; //return (x-a.x)>0?1:-1; } } // static class sorting implements Comparator<Pair>{ // public int compare(Pair a1,Pair a2){ // if(o1.a==o2.a) // return (o1.b>o2.b)?1:-1; // else if(o1.a>o2.a) // return 1; // else // return -1; // } // } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } // To compute x^y under modulo m static long power(long x, long y, long m){ if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } static long fast_pow(long base,long n,long M){ if(n==0) return 1; if(n==1) return base; long halfn=fast_pow(base,n/2,M); if(n%2==0) return ( halfn * halfn ) % M; else return ( ( ( halfn * halfn ) % M ) * base ) % M; } static long modInverse(long n,long M){ return fast_pow(n,M-2,M); } // (1,1) // (3,2) (3,5) }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
4b4913e1d1bc156f742c202391da2b20
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
//package educational.round82; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class D { InputStream is; PrintWriter out; String INPUT = ""; void solve() { for(int T = ni();T > 0;T--) { long n = nl(); int m = ni(); int[] a = na(m); int[] f = new int[60]; for(int v : a) { f[Integer.numberOfTrailingZeros(v)]++; } long s = 0; for(int v : a)s += v; if(n > s) { out.println(-1); continue; } int cost = 0; for(int d = 0;d < 60;d++) { if(n<<~d<0) { f[d]--; if(f[d] < 0) { for(int e = d+1;e < 60;e++) { cost++; if(f[e] > 0) { f[e]--; for(int k = e-1;k >= d;k--)f[k]++; break; } } } } if(d+1 < 60) { f[d+1] += f[d]/2; f[d] %= 2; } } out.println(cost); } } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
16ad632c87c6ff1addb915ee62e88ce8
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(); int q = in.nextInt(); while (q-- > 0) { long n = in.nextLong(); int m = in.nextInt(); int k = 60; int[] a = new int[m]; long dfsdf = 0; for (int i = 0; i < m; i++) { a[i] = in.nextInt(); dfsdf += a[i]; } if(dfsdf < n){ in.out.println(-1); continue; } int[] cnt = new int[k]; for (int i = 0; i < m; i++) { int l = 0; int r = k; while (l + 1 < r) { int mid = (l + r) >> 1; if ((1L << mid) <= a[i]) l = mid; else r = mid; } cnt[l]++; } int ans = 0; long sum = 0; for (int i = 0; i < k; i++) { long jopi = (1L << i); sum += jopi * cnt[i]; if ((jopi & n) != 0) { if (sum >= jopi) sum -= jopi; else { for (int j = i + 1; j < k; j++) { if (cnt[j] != 0) { sum += (1L << j) - jopi; cnt[j]--; ans += j - i; break; } } } } } in.out.println(ans); } in.out.close(); } } class FastScanner { BufferedReader br; StringTokenizer st = new StringTokenizer(""); PrintWriter out; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } FastScanner(String in, String out_) throws FileNotFoundException { br = new BufferedReader(new FileReader(in)); out = new PrintWriter(out_); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
7e54fd4828b7c69ad1a439e3248d2985
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) { Problem problem = new Problem(); problem.solve(); } } class Problem { private final Parser parser = new Parser(); void solve() { int t = parser.parseInt(); for (int i = 0; i < t; i++) { solve(i); } } void solve(int testCase) { long n = parser.parseLong(); int m = parser.parseInt(); long sum = 0; Map<Long, Integer> map = new HashMap<>(); for(int i = 0; i < m; i++) { long v = parser.parseInt(); map.put(v, map.getOrDefault(v, 0) + 1); sum += v; } if(n > sum) { System.out.println(-1); return; } long current = 0; int rightIndex = -1; int ans = 0; for(int i = 0; i <= 60; i++) { long v = (1L << i); if(rightIndex != -1 && map.getOrDefault(v, 0) != 0) { ans += (i - rightIndex); map.put(v, map.get(v) - 1); rightIndex = -1; } current += v * map.getOrDefault(v, 0); if((v & n) != 0) { if (current >= v) { current -= v; } else if (rightIndex == -1) { rightIndex = i; } } } System.out.println(ans); } } class Parser { private final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private final Iterator<String> stringIterator = br.lines().iterator(); private final Deque<String> inputs = new ArrayDeque<>(); void fill() { if (inputs.isEmpty()) { if (!stringIterator.hasNext()) throw new NoSuchElementException(); inputs.addAll(Arrays.asList(stringIterator.next().split(" "))); } } Integer parseInt() { fill(); if (!inputs.isEmpty()) { return Integer.parseInt(inputs.pollFirst()); } throw new NoSuchElementException(); } Long parseLong() { fill(); if (!inputs.isEmpty()) { return Long.parseLong(inputs.pollFirst()); } throw new NoSuchElementException(); } Double parseDouble() { fill(); if (!inputs.isEmpty()) { return Double.parseDouble(inputs.pollFirst()); } throw new NoSuchElementException(); } String parseString() { fill(); return inputs.removeFirst(); } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
f5424b46091f7c585c768bfa0dc64214
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.util.*; import java.io.*; public class D { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while(t-->0) { String[] inp = br.readLine().split(" "); long n = Long.parseLong(inp[0]); int m = Integer.parseInt(inp[1]); int[] boxes = new int [63]; int[] number = new int[63]; inp = br.readLine().split(" "); long sum=0; for(int i=0;i<m;i++) { long temp = Long.parseLong(inp[i]); sum+=temp; for(int j=0;j<63;j++) { if((temp>>j&1)!=0) { boxes[j]++; continue; } } } if(sum<n) { pw.println(-1); continue; } for(int i=0;i<63;i++) { if((n>>i&1)!=0) { number[i]=1; } } long c=0; for(int i=0;i<62;i++) { if(number[i]==1) { if(boxes[i]>0)boxes[i]--; else { int ind=0; for(int j=i+1;j<63;j++) { if(boxes[j]>0) { ind = j; break; } } // pw.println(ind); for(int j=ind;j>i;j--) { boxes[j-1]+=2; boxes[j]--; c++; } boxes[i]--; } } boxes[i+1] += boxes[i]>>1; } pw.println(c); } pw.flush(); } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
18c28ae9a85cf6d9d659c4a328789418
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { static FastReader in=new FastReader(); public static void main(String [] args) { int t=in.nextInt(); while(t-->0){ long nn=in.nextLong(),n=nn,sum=0L; int m=in.nextInt(); int x[]=new int [61],c[]=new int[61],ll=0; while(n>0){ c[ll]=(int) (n%2); n/=2;ll++; } for(int i=0;i<m;i++){ int xx=in.nextInt(),l=0; sum+=(long)xx; while(xx>0){ if(xx==1){x[l]++;break;} l++; xx/=2; } } if(nn>sum){System.out.println("-1");} else{ int ans=0; for(int i=0;i<60;i++){ if(c[i]>0){ int l=0,u=i; while(u<60){ if(x[u]>0){x[u]--; ans+=l; break; } else x[u]++; u++;l++; } } if(x[i]>1){x[i+1]+=x[i]/2;} } System.out.println(ans);} }} static long gcd(long g,long x){ if(x<1)return g; else return gcd(x,g%x); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } class Sorting{ public static int[] bucketSort(int[] array, int bucketCount) { if (bucketCount <= 0) throw new IllegalArgumentException("Invalid bucket count"); if (array.length <= 1) return array; //trivially sorted int high = array[0]; int low = array[0]; for (int i = 1; i < array.length; i++) { //find the range of input elements if (array[i] > high) high = array[i]; if (array[i] < low) low = array[i]; } double interval = ((double)(high - low + 1))/bucketCount; //range of one bucket ArrayList<Integer> buckets[] = new ArrayList[bucketCount]; for (int i = 0; i < bucketCount; i++) { //initialize buckets buckets[i] = new ArrayList(); } for (int i = 0; i < array.length; i++) { //partition the input array buckets[(int)((array[i] - low)/interval)].add(array[i]); } int pointer = 0; for (int i = 0; i < buckets.length; i++) { Collections.sort(buckets[i]); //mergeSort for (int j = 0; j < buckets[i].size(); j++) { //merge the buckets array[pointer] = buckets[i].get(j); pointer++; } } return array; } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
ef17aec0091d2c1830864e15a82b28bf
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { static ArrayList<Character> adj[]; static PrintWriter out = new PrintWriter(System.out); public static int mod = 1000000007; static int notmemo[][][][]; static int k; static long a[]; static int b[]; static int m; static char c[]; static int trace[]; static int h; static int x; static int ans1; static int ans2; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int t=sc.nextInt(); label:while(t-->0) { req=new boolean[61]; long n=sc.nextLong(); int m=sc.nextInt(); long a[]=new long[m]; long count[]=new long[61]; boolean vis[]=new boolean[61]; long sum=0; for (int i = 0; i < a.length; i++) { a[i]=sc.nextLong(); sum+=a[i]; for (int j = 0; j <61; j++) { if((a[i]&((long)(1*1l<<j)))!=0) { count[j]++; break; } } } if(sum<n) { System.out.println(-1); continue label; } block(n); long total=0; for (int i = 0; i < vis.length; i++) { if(!req[i]&&count[i]>=2) { long c=count[i]/2; if(i<60) count[i+1]+=c; count[i]=0; } else if(req[i]&&count[i]>=3) { count[i]--; long c=count[i]/2; if(i<60) count[i+1]+=c; count[i]=0; vis[i]=true; } else if(req[i]&&count[i]>0) { vis[i]=true; count[i]--; } long first=-1; while(req[i]&&!vis[i]) { int idx=i; while(idx<60&&count[idx]==0) { idx++; } if(first==-1) { first=idx; } long c=2; if(idx>0) count[idx-1]+=c; count[idx]--; if(count[i]>0) { vis[i]=true; total+=(first-i); //System.out.println(idx+" "+i); } } } //System.out.println(Arrays.toString(count)); System.out.println(total); //System.out.println(Arrays.toString(vis)); // System.out.println(Arrays.toString(count)); } } static boolean req[]; static void block(long x) { ArrayList<Long> v = new ArrayList<Long>(); // Convert decimal number to // its binary equivalent // System.out.print("Blocks for "+x+" : "); while (x > 0) { v.add((long)x % 2); x = x / 2; } // Displaying the output when // the bit is '1' in binary // equivalent of number. for (int i = 0; i < v.size(); i++) { if (v.get(i) == 1) { req[i]=true; // System.out.print(i); // if (i != v.size() - 1) // System.out.print( ", "); } } //System.out.println(); } static void dfs(char c) { if(vis[c-'a']) { return; } vis[c-'a']=true; for(char c2:adj[c-'a']) { if(!vis[c2-'a']) { dfs(c2); } } System.out.print(c); } static class book implements Comparable<book> { int idx; long score; public book(int i, long s) { idx = i; score = s; } public int compareTo(book o) { return (int) (o.score - score); } } static class library implements Comparable<library> { int numofbooks; int signup; int shiprate; int idx; public library(int a, int b, int c, int idx) { numofbooks = a; signup = b; shiprate = c; this.idx = idx; } @Override public int compareTo(library o) { if(signup==o.signup) { return o.numofbooks-numofbooks; } return signup - o.signup; } } static long dp(int i, int state) { if (i < 0) { return state; } if (memo[i][state] != -1) return memo[i][state]; int x = Integer.parseInt(c[i] + ""); x += state; int newc = x / 10; x = x % 10; return memo[i][state] = Math.min(dp(i - 1, newc) + x, x == 0 ? (long) 1e15 : dp(i - 1, newc + 1) + 10 - x); } static boolean isPal(String s) { int j = s.length() - 1; c = s.toCharArray(); Arrays.sort(c); for (int i = 0; i < c.length; i++) { } return true; } static String s; static boolean isOn(int S, int j) { return (S & 1 << j) != 0; } static int y, d; static void extendedEuclid(int a, int b) { if (b == 0) { x = 1; y = 0; d = a; return; } extendedEuclid(b, a % b); int x1 = y; int y1 = x - a / b * y; x = x1; y = y1; } static boolean f = true; static class SegmentTree { // 1-based DS, OOP int N; // the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N << 1]; build(1, 1, N); } void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] += val; while (index > 1) { index >>= 1; sTree[index] = Math.max(sTree[index << 1], sTree[index << 1 | 1]); } } void update_range(int i, int j, int val) // O(log n) { update_range(1, 1, N, i, j, val); } void update_range(int node, int b, int e, int i, int j, int val) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] += (e - b + 1) * val; lazy[node] += val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node << 1, b, mid, i, j, val); update_range(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void propagate(int node, int b, int mid, int e) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; sTree[node << 1] += (mid - b + 1) * lazy[node]; sTree[node << 1 | 1] += (e - mid) * lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return 0; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; // propagate(node, b, mid, e); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return Math.max(q1, q2); } } static long memo[][]; static long nCr1(int n, int k) { if (n < k) return 0; if (k == 0 || k == n) return 1; if (comb[n][k] != -1) return comb[n][k]; if (n - k < k) return comb[n][k] = nCr1(n, n - k); return comb[n][k] = ((nCr1(n - 1, k - 1) % mod) + (nCr1(n - 1, k) % mod)) % mod; } static class UnionFind { int[] p, rank, setSize; int numSets; int max[]; public UnionFind(int N) { max = new int[N]; p = new int[numSets = N]; rank = new int[N]; setSize = new int[N]; for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; max[i] = i; } } public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); } public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } public void unionSet(int i, int j) { if (isSameSet(i, j)) return; numSets--; int x = findSet(i), y = findSet(j); if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; max[x] = Math.max(max[x], max[y]); } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; max[y] = Math.max(max[x], max[y]); } } private int getmax(int j) { return max[findSet(j)]; } public int numDisjointSets() { return numSets; } public int sizeOfSet(int i) { return setSize[findSet(i)]; } } /** * private static void trace(int i, int time) { if(i==n) return; * * * long ans=dp(i,time); * if(time+a[i].t<a[i].burn&&(ans==dp(i+1,time+a[i].t)+a[i].cost)) { * * trace(i+1, time+a[i].t); * * l1.add(a[i].idx); return; } trace(i+1,time); * * } **/ static class incpair implements Comparable<incpair> { int a; long b; int idx; incpair(int a, long dirg, int i) { this.a = a; b = dirg; idx = i; } public int compareTo(incpair e) { return (int) (b - e.b); } } static class decpair implements Comparable<decpair> { int a; long b; int idx; decpair(int a, long dirg, int i) { this.a = a; b = dirg; idx = i; } public int compareTo(decpair e) { return (int) (e.b - b); } } static long allpowers[]; static class Quad implements Comparable<Quad> { int u; int v; char state; int turns; public Quad(int i, int j, char c, int k) { u = i; v = j; state = c; turns = k; } public int compareTo(Quad e) { return (int) (turns - e.turns); } } static long dirg[][]; static Edge[] driver; static int n; static class Edge implements Comparable<Edge> { int node; long cost; Edge(int a, long dirg) { node = a; cost = dirg; } public int compareTo(Edge e) { return (int) (cost - e.cost); } } static long manhatandistance(long x, long x2, long y, long y2) { return Math.abs(x - x2) + Math.abs(y - y2); } static long fib[]; static long fib(int n) { if (n == 1 || n == 0) { return 1; } if (fib[n] != -1) { return fib[n]; } else return fib[n] = ((fib(n - 2) % mod + fib(n - 1) % mod) % mod); } static class Pair { int a, b; Pair(int x, int y) { a = x; b = y; } } static long[][] comb; static class Triple implements Comparable<Triple> { int l; int r; long cost; int idx; public Triple(int a, int b, long l1, int l2) { l = a; r = b; cost = l1; idx = l2; } public int compareTo(Triple x) { if (l != x.l || idx == x.idx) return l - x.l; return -idx; } } static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N)) { TreeSet<Long> factors = new TreeSet<Long>(); // take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while (p * p <= N) { while (N % p == 0) { factors.add((long) p); N /= p; } if (primes.size() > idx + 1) p = primes.get(++idx); else break; } if (N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static boolean visited[]; /** * static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>(); * q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0; * while(!q.isEmpty()) { * * int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) { * maxcost=Math.max(maxcost, v.cost); * * * * if(!visited[v.v]) { * * visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost, * v.cost); } } * * } return maxcost; } **/ public static boolean FindAllElements(int n, int k) { int sum = k; int[] A = new int[k]; Arrays.fill(A, 0, k, 1); for (int i = k - 1; i >= 0; --i) { while (sum + A[i] <= n) { sum += A[i]; A[i] *= 2; } } if (sum == n) { return true; } else return false; } static boolean vis2[][]; static boolean f2 = false; static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x // r) { long[][] C = new long[p][r]; for (int i = 0; i < p; ++i) { for (int j = 0; j < r; ++j) { for (int k = 0; k < q; ++k) { C[i][j] = (C[i][j] + (a2[i][k] % mod * b[k][j] % mod)) % mod; C[i][j] %= mod; } } } return C; } static ArrayList<Pair> a1[]; static int memo1[]; static boolean vis[]; static TreeSet<Integer> set = new TreeSet<Integer>(); static long modPow(long ways, long count, long mod) // O(log e) { ways %= mod; long res = 1; while (count > 0) { if ((count & 1) == 1) res = (res * ways) % mod; ways = (ways * ways) % mod; count >>= 1; } return res % mod; } static long gcd(long ans, long b) { if (b == 0) { return ans; } return gcd(b, ans % b); } static int[] isComposite; static int[] valid; static ArrayList<Integer> primes; static ArrayList<Integer> l; static void sieve(int N) // O(N log log N) { isComposite = new int[N + 1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); l = new ArrayList<>(); valid = new int[N + 1]; for (int i = 2; i <= N; ++i) // can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) // can loop in 2 and odd integers for slightly better performance { primes.add(i); l.add(i); valid[i] = 1; for (int j = i * 2; j <= N; j += i) { // j = i * 2 will not affect performance too much, may alter in // modified sieve isComposite[j] = 1; } } for (int i = 0; i < primes.size(); i++) { for (int j : primes) { if (primes.get(i) * j > N) { break; } valid[primes.get(i) * j] = 1; } } } public static int[] schuffle(int[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); int temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } static int V; static long INF = (long) 1E16; static class Edge2 { int node; long cost; long next; Edge2(int a, int c, Long long1) { node = a; cost = long1; next = c; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
c8bef944bd5dd1b2efe193282f527725
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { static ArrayList<Character> adj[]; static PrintWriter out = new PrintWriter(System.out); public static int mod = 1000000007; static int notmemo[][][][]; static int k; static long a[]; static int b[]; static int m; static char c[]; static int trace[]; static int h; static int x; static int ans1; static int ans2; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int t=sc.nextInt(); int x=0; boolean luck=false; label:while(t-->0) { x++; req=new boolean[62]; long n=sc.nextLong(); int m=sc.nextInt(); long a[]=new long[m]; long count[]=new long[62]; boolean vis[]=new boolean[62]; long sum=0; for (int i = 0; i < a.length; i++) { a[i]=sc.nextLong(); sum+=a[i]; for (int j = 0; j <62; j++) { if((a[i]&((long)(1*1l<<j)))!=0) { count[j]++; break; } } } if(sum<n) { System.out.println(-1); continue label; } block(n); long total=0; for (int i = 0; i < vis.length-1; i++) { while(req[i]&&!vis[i]&&count[i]==0) { int idx=i+1; while(idx<61&&count[idx]==0) { idx++; } long c=2; while(idx>i&&idx>0) { count[idx-1]+=c; count[idx]--; total++; idx--; } if(count[i]>0) { vis[i]=true; } } if(req[i]) { count[i]--; } count[i+1]+=(count[i]/2); } //System.out.println(Arrays.toString(count)); System.out.println(total); //System.out.println(Arrays.toString(vis)); // System.out.println(Arrays.toString(count)); //'392349085599 } } static boolean req[]; static void block(long x) { ArrayList<Long> v = new ArrayList<Long>(); // Convert decimal number to // its binary equivalent // System.out.print("Blocks for "+x+" : "); while (x > 0) { v.add(x % 2); x = x / 2; } // Displaying the output when // the bit is '1' in binary // equivalent of number. for (int i = 0; i < v.size(); i++) { if (v.get(i) == 1) { req[i]=true; // System.out.print(i); // if (i != v.size() - 1) // System.out.print( ", "); } } //System.out.println(); } static void dfs(char c) { if(vis[c-'a']) { return; } vis[c-'a']=true; for(char c2:adj[c-'a']) { if(!vis[c2-'a']) { dfs(c2); } } System.out.print(c); } static class book implements Comparable<book> { int idx; long score; public book(int i, long s) { idx = i; score = s; } public int compareTo(book o) { return (int) (o.score - score); } } static class library implements Comparable<library> { int numofbooks; int signup; int shiprate; int idx; public library(int a, int b, int c, int idx) { numofbooks = a; signup = b; shiprate = c; this.idx = idx; } @Override public int compareTo(library o) { if(signup==o.signup) { return o.numofbooks-numofbooks; } return signup - o.signup; } } static long dp(int i, int state) { if (i < 0) { return state; } if (memo[i][state] != -1) return memo[i][state]; int x = Integer.parseInt(c[i] + ""); x += state; int newc = x / 10; x = x % 10; return memo[i][state] = Math.min(dp(i - 1, newc) + x, x == 0 ? (long) 1e15 : dp(i - 1, newc + 1) + 10 - x); } static boolean isPal(String s) { int j = s.length() - 1; c = s.toCharArray(); Arrays.sort(c); for (int i = 0; i < c.length; i++) { } return true; } static String s; static boolean isOn(int S, int j) { return (S & 1 << j) != 0; } static int y, d; static void extendedEuclid(int a, int b) { if (b == 0) { x = 1; y = 0; d = a; return; } extendedEuclid(b, a % b); int x1 = y; int y1 = x - a / b * y; x = x1; y = y1; } static boolean f = true; static class SegmentTree { // 1-based DS, OOP int N; // the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N << 1]; build(1, 1, N); } void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] += val; while (index > 1) { index >>= 1; sTree[index] = Math.max(sTree[index << 1], sTree[index << 1 | 1]); } } void update_range(int i, int j, int val) // O(log n) { update_range(1, 1, N, i, j, val); } void update_range(int node, int b, int e, int i, int j, int val) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] += (e - b + 1) * val; lazy[node] += val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node << 1, b, mid, i, j, val); update_range(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void propagate(int node, int b, int mid, int e) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; sTree[node << 1] += (mid - b + 1) * lazy[node]; sTree[node << 1 | 1] += (e - mid) * lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return 0; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; // propagate(node, b, mid, e); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return Math.max(q1, q2); } } static long memo[][]; static long nCr1(int n, int k) { if (n < k) return 0; if (k == 0 || k == n) return 1; if (comb[n][k] != -1) return comb[n][k]; if (n - k < k) return comb[n][k] = nCr1(n, n - k); return comb[n][k] = ((nCr1(n - 1, k - 1) % mod) + (nCr1(n - 1, k) % mod)) % mod; } static class UnionFind { int[] p, rank, setSize; int numSets; int max[]; public UnionFind(int N) { max = new int[N]; p = new int[numSets = N]; rank = new int[N]; setSize = new int[N]; for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; max[i] = i; } } public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); } public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } public void unionSet(int i, int j) { if (isSameSet(i, j)) return; numSets--; int x = findSet(i), y = findSet(j); if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; max[x] = Math.max(max[x], max[y]); } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; max[y] = Math.max(max[x], max[y]); } } private int getmax(int j) { return max[findSet(j)]; } public int numDisjointSets() { return numSets; } public int sizeOfSet(int i) { return setSize[findSet(i)]; } } /** * private static void trace(int i, int time) { if(i==n) return; * * * long ans=dp(i,time); * if(time+a[i].t<a[i].burn&&(ans==dp(i+1,time+a[i].t)+a[i].cost)) { * * trace(i+1, time+a[i].t); * * l1.add(a[i].idx); return; } trace(i+1,time); * * } **/ static class incpair implements Comparable<incpair> { int a; long b; int idx; incpair(int a, long dirg, int i) { this.a = a; b = dirg; idx = i; } public int compareTo(incpair e) { return (int) (b - e.b); } } static class decpair implements Comparable<decpair> { int a; long b; int idx; decpair(int a, long dirg, int i) { this.a = a; b = dirg; idx = i; } public int compareTo(decpair e) { return (int) (e.b - b); } } static long allpowers[]; static class Quad implements Comparable<Quad> { int u; int v; char state; int turns; public Quad(int i, int j, char c, int k) { u = i; v = j; state = c; turns = k; } public int compareTo(Quad e) { return (int) (turns - e.turns); } } static long dirg[][]; static Edge[] driver; static int n; static class Edge implements Comparable<Edge> { int node; long cost; Edge(int a, long dirg) { node = a; cost = dirg; } public int compareTo(Edge e) { return (int) (cost - e.cost); } } static long manhatandistance(long x, long x2, long y, long y2) { return Math.abs(x - x2) + Math.abs(y - y2); } static long fib[]; static long fib(int n) { if (n == 1 || n == 0) { return 1; } if (fib[n] != -1) { return fib[n]; } else return fib[n] = ((fib(n - 2) % mod + fib(n - 1) % mod) % mod); } static class Pair { int a, b; Pair(int x, int y) { a = x; b = y; } } static long[][] comb; static class Triple implements Comparable<Triple> { int l; int r; long cost; int idx; public Triple(int a, int b, long l1, int l2) { l = a; r = b; cost = l1; idx = l2; } public int compareTo(Triple x) { if (l != x.l || idx == x.idx) return l - x.l; return -idx; } } static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N)) { TreeSet<Long> factors = new TreeSet<Long>(); // take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while (p * p <= N) { while (N % p == 0) { factors.add((long) p); N /= p; } if (primes.size() > idx + 1) p = primes.get(++idx); else break; } if (N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static boolean visited[]; /** * static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>(); * q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0; * while(!q.isEmpty()) { * * int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) { * maxcost=Math.max(maxcost, v.cost); * * * * if(!visited[v.v]) { * * visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost, * v.cost); } } * * } return maxcost; } **/ public static boolean FindAllElements(int n, int k) { int sum = k; int[] A = new int[k]; Arrays.fill(A, 0, k, 1); for (int i = k - 1; i >= 0; --i) { while (sum + A[i] <= n) { sum += A[i]; A[i] *= 2; } } if (sum == n) { return true; } else return false; } static boolean vis2[][]; static boolean f2 = false; static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x // r) { long[][] C = new long[p][r]; for (int i = 0; i < p; ++i) { for (int j = 0; j < r; ++j) { for (int k = 0; k < q; ++k) { C[i][j] = (C[i][j] + (a2[i][k] % mod * b[k][j] % mod)) % mod; C[i][j] %= mod; } } } return C; } static ArrayList<Pair> a1[]; static int memo1[]; static boolean vis[]; static TreeSet<Integer> set = new TreeSet<Integer>(); static long modPow(long ways, long count, long mod) // O(log e) { ways %= mod; long res = 1; while (count > 0) { if ((count & 1) == 1) res = (res * ways) % mod; ways = (ways * ways) % mod; count >>= 1; } return res % mod; } static long gcd(long ans, long b) { if (b == 0) { return ans; } return gcd(b, ans % b); } static int[] isComposite; static int[] valid; static ArrayList<Integer> primes; static ArrayList<Integer> l; static void sieve(int N) // O(N log log N) { isComposite = new int[N + 1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); l = new ArrayList<>(); valid = new int[N + 1]; for (int i = 2; i <= N; ++i) // can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) // can loop in 2 and odd integers for slightly better performance { primes.add(i); l.add(i); valid[i] = 1; for (int j = i * 2; j <= N; j += i) { // j = i * 2 will not affect performance too much, may alter in // modified sieve isComposite[j] = 1; } } for (int i = 0; i < primes.size(); i++) { for (int j : primes) { if (primes.get(i) * j > N) { break; } valid[primes.get(i) * j] = 1; } } } public static int[] schuffle(int[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); int temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } static int V; static long INF = (long) 1E16; static class Edge2 { int node; long cost; long next; Edge2(int a, int c, Long long1) { node = a; cost = long1; next = c; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
6330dde093a9ef6e6a53ad37a9557bc7
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import javafx.util.Pair; import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main implements Runnable { boolean multiple = true; long MOD = 1000000007; @SuppressWarnings("Duplicates") void solve() throws Exception { long n = sc.nextLong(); long m = sc.nextLong(); int[] count = new int[67]; for (int i = 0; i < m; i++) count[(int) (0.00001 + log(sc.nextLong()) / log(2))]++; long ans = 0; for (int ptr = 0; ptr < 64; ptr++) { // System.out.print(ptr + ": "); // for (int i = 0; i < 7; i++) // System.out.print(count[i]); // System.out.println(); if (n % 2 == 1) //i need 2^ptr { // System.out.println("what"); if (count[ptr] == 0) { int i; for (i = ptr + 1; i < 67 && count[i] == 0; i++); if (i == 67) { System.out.println(-1); return; } ans += i - ptr; count[i]--; for (int j = ptr; j < i; j++) count[j]++; count[ptr]++; } count[ptr]--; } count[ptr + 1] += count[ptr] / 2; n /= 2; } System.out.println(ans); } int nck(int n, int k) { return factorial(n) / (factorial(n - k) * factorial(k)); } int factorial(int n) { return (n <= 1) ? 1 : n * factorial(n - 1); } long[][] pow(long[][] a, long pow) { if (pow == 0) { long[][] identity = new long[a.length][a.length]; for (int i = 0; i < a.length; i++) identity[i][i] = 1; return identity; } if (pow == 1) return a; long[][] temp = pow(a, pow / 2); temp = mult(temp, temp); if (pow % 2 == 0) return temp; return mult(a, temp); } long[][] mult(long[][] a, long[][] b) { if (a[0].length != b.length) a[0][0] /= 0; long[][] c = new long[a.length][b[0].length]; for (int i = 0; i < a.length; i++) for (int j = 0; j < b[0].length; j++) for (int k = 0; k < a[0].length; k++) c[i][j] = (c[i][j] + ((a[i][k] * b[k][j]) % MOD)) % MOD; return c; } long totient(long m) { long result = m; for (long i = 2; i * i <= m; i++) if (m % i == 0) { while (m % i == 0) m /= i; result -= result / i; } if (m > 1) result -= result / m; return result; } long inv(long a, long b) { return 1 < a ? b - inv(b % a, a) * b / a : 1; } long gcd(long a, long b) { return a == 0 ? b : gcd(b % a, a); } long lcm(long a, long b) { return (a * b) / gcd(a, b); } class SegTree { long[][] ans; SegTree() { } } class SegNode { int max; int L, R; SegNode left = null, right = null; int query(int queryL, int queryR) { if (queryL == L && queryR == R) return max; int leftAns = Integer.MIN_VALUE, rightAns = Integer.MIN_VALUE; if (left != null && queryL <= left.R) leftAns = left.query(queryL, min(queryR, left.R)); if (right != null && queryR >= right.L) rightAns = right.query(max(queryL, right.L), queryR); return max(leftAns, rightAns); } SegNode(int[] arr, int l, int r) { L = l; R = r; max = arr[l]; if (l == r) return; int mid = (l + r) / 2; left = new SegNode(arr, l, mid); right = new SegNode(arr, mid + 1, r); max = max(left.max, right.max); } } void print(long[] arr) { for (int i = 0; i < arr.length; i++) System.out.print(arr[i] + " "); System.out.println(); } @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); if (multiple) { int q = sc.nextInt(); for (int i = 0; i < q; i++) solve(); } else solve(); } catch (Throwable uncaught) { Main.uncaught = uncaught; } finally { out.close(); } } public static void main(String[] args) throws Throwable { Thread thread = new Thread(null, new Main(), "", (1 << 26)); thread.start(); thread.join(); if (Main.uncaught != null) { throw Main.uncaught; } } static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out; } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
0827b72c1f8fff9eca785505addb7794
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.util.regex.*; public class Solution { static class Pair<E, V> implements Comparable<Pair<E, V>>{ E a; V b; public Pair(E x, V y) {a = x;b=y;} public int compareTo(Pair<E, V> p){ return Integer.compare((Integer)a, (Integer)p.a); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (Integer)a; result = prime * result + (Integer)b; return result; } @Override public boolean equals(Object obj) { Pair<E, V> cur = (Pair<E, V>)obj; if((Integer)a == (Integer)cur.a && (Integer)b == (Integer)cur.b)return true; if((Integer)b == (Integer)cur.a && (Integer)a == (Integer)cur.b)return true; return false; } } public static void main(String[] args) throws Exception { new Thread(null, null, "Anshum Gupta", 99999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } public static long gcd(long a,long b) { if(a<b) return gcd(b,a); if(b==0) return a; return gcd(b,a%b); } static long lcm(int a,int b) { return a*b / gcd(a,b); } static int[] z(char[]arr) { int l = 0, r = 0; int[]z = new int[n]; for(int i=1; i<n; i++) { if(i > r) { l = r = i; while(r < n && arr[r-l] == arr[r])r++; z[i] = r-- - l; }else { int k = i - l; if(z[k] < r - i + l)z[i] = z[k]; else { l = i; while(r < n && arr[r-l] == arr[r])r++; z[i] = r-- - l; } } } return z; } static long pow(long x,long y){ if(y == 0)return 1; if(y==1)return x; long a = pow(x,y/2); a = (a*a)%mod; if(y%2==0){ return a; } return (a*x)%mod; } static long my_inv(long a) { return pow(a,mod-2); } static long bin(int a,int b) { if(a < b || a<0 || b<0)return 0; return ((fact[a]*inv_fact[a-b])%mod * inv_fact[b])%mod; } static void make_facts() { fact=new long[mxN]; inv_fact = new long[mxN]; fact[0]=inv_fact[0]=1L; for(int i=1;i<mxN;i++) { fact[i] = (i*fact[i-1])%mod; inv_fact[i] = my_inv(fact[i]); } } static final long mxx = (long)(1e18+5); static final int mxN = (int)(1e5); static final int mxV = (int)(1e5+5), log = 18; static long mod = (long)(1e9+7); //998244353;// static long[]fact, inv_fact; static final int INF = (int)1e9+5; static boolean[]vis; static ArrayList<ArrayList<Integer>> adj; static int n, m, k, x, y, z, q; static long ans; static char[]arr, str; static boolean makeInExisting(int[]cnt, int i) { long cur = 0, need = (1L<<i); int[]temp = Arrays.copyOf(cnt, 32); for(int j=Math.min(31, i); j>=0; j--) { if(cur + (1L<<j) * cnt[j] >= need) { temp[j] -= (need - cur) / ((1L<<j)); for(int k=31; k>=0; k--)cnt[k] = temp[k]; // out.println("i = " + i + " " + "j = " + j); return true; } else { cur += (1L<<j) * cnt[j]; temp[j] = 0; } } return false; } static boolean breakNearest(int[]cnt, int i) { for(int j=i+1; j<=31; j++) { if(cnt[j] > 0) { ans += (j - i); cnt[j]--; for(int k=j-1; k>=i; k--) { assert(cnt[k] == 0); cnt[k]++; } return true; } } return false; } public static void solve() throws Exception { // solve the problem here s = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out), true); // out = new PrintWriter("output.txt"); int tc = s.nextInt(); while(tc-->0){ long n = s.nextLong(); int m = s.nextInt(); int[]a = s.nextIntArray(m); int[]cnt = new int[32]; for(int i=0; i<m; i++) { for(int j=0; j<32; j++) { if(((1<<j) & a[i]) > 0) cnt[j]++; } } // DebugUtills.printIntArray(cnt); ans = 0; boolean ok = true; for(int i=0; i<60; i++) { if(((1L << i) & n) > 0) { if(!makeInExisting(cnt, i)) { if(!breakNearest(cnt, i)) { ok = false; break; } } // DebugUtills.printIntArray(cnt); // out.println("i = " + i + " cur ans = " + ans); } } out.println(ok ? ans : "-1"); } out.flush(); out.close(); } public static PrintWriter out; public static MyScanner s; static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public MyScanner(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] nextIntArray(int n){ int[]a = new int[n]; for(int i=0; i<n; i++) { a[i] = this.nextInt(); } return a; } long[] nextLongArray(int n) { long[]a = new long[n]; for(int i=0; i<n; i++) { a[i] = this.nextLong(); } return a; } char[][] next2DCharArray(int n, int m){ char[][]arr = new char[n][m]; for(int i=0; i<n; i++) { arr[i] = this.next().toCharArray(); } return arr; } ArrayList<ArrayList<Integer>> readUndirectedUnweightedGraph(int n, int m) { ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>()); for(int i=0; i<m; i++) { int u = s.nextInt(); int v = s.nextInt(); adj.get(u).add(v); adj.get(v).add(u); } return adj; } ArrayList<ArrayList<Integer>> readDirectedUnweightedGraph(int n, int m) { ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>()); for(int i=0; i<m; i++) { int u = s.nextInt(); int v = s.nextInt(); adj.get(u).add(v); } return adj; } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
a9eb68a0aab91044b1ffb46545e3befe
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Main { public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new FileReader("penguins.in")); pw = new PrintWriter(System.out); //pw = new PrintWriter("penguins.out"); new Main().run(); } void run() throws IOException { int t = nextInt(); while (t-- > 0) { long n = nextLong(); int m = nextInt(); int[] a = new int[m]; long sum = 0; int[] steps = new int[67]; for (int i = 0; i < a.length; i++) { a[i] = nextInt(); int x = a[i]; int cnt = 0; while (x > 0) { x /= 2; cnt++; } steps[cnt - 1]++; } ArrayList<Integer> al = new ArrayList<>(); long k = n; while (k > 0) { al.add((int) (k % 2)); k /= 2; } while (al.size() < 67) al.add(0); int[] q = new int[al.size()]; for (int i = 0; i < q.length; i++) { q[i] = al.get(i); } int ans = 0; boolean flag = false; for (int i = 0; i < q.length - 1; i++) { if (q[i] == 1) { if (steps[i] == 0) { boolean find = false; int pos = 0; for (int j = i + 1; j < steps.length; j++) { if (steps[j] > 0) { pos = j; find = true; break; } } if (!find) { flag = true; pw.println(-1); break; } for (int j = pos; j > i; j--) { steps[j]--; steps[j - 1] += 2; ans++; } } } if(q[i] == 1)steps[i]--; steps[i + 1] += steps[i] / 2; } if (flag) continue; pw.println(ans); } pw.close(); } class pair implements Comparable<pair> { char l, r; public pair(char l, char r) { this.l = l; this.r = r; } @Override public int compareTo(pair o) { if (o.l == this.l) return Integer.compare(o.r, this.r); return Integer.compare(o.l, this.l); } } static BufferedReader br; static StringTokenizer st = new StringTokenizer(""); static PrintWriter pw = new PrintWriter(System.out); public static int nextInt() throws IOException { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return Integer.parseInt(st.nextToken()); } public static String next() throws IOException { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public static long nextLong() throws IOException { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return Long.parseLong(st.nextToken()); } public static double nextDouble() throws IOException { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return Double.parseDouble(st.nextToken()); } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
cf01aff961270f6677d6b913a00190bc
train_002.jsonl
1581518100
You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.TreeMap; import java.util.Map; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Ribhav */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DFillTheBag solver = new DFillTheBag(); solver.solve(1, in, out); out.close(); } static class DFillTheBag { public void solve(int testNumber, FastReader s, PrintWriter out) { int t = s.nextInt(); while (t-- > 0) { long n = s.nextLong(); int m = s.nextInt(); long[] arr = s.nextLongArray(m); TreeMap<Long, Integer> map = new TreeMap<>(); for (int i = 0; i < arr.length; i++) { map.put(arr[i], map.getOrDefault(arr[i], 0) + 1); } int maxBits = Long.toBinaryString(n).length(); int count = 0; boolean canBeFound = true; for (int i = 0; i < maxBits; i++) { if (((1L << i) & n) != 0) { if (map.containsKey(1L << i)) { int freq = map.get(1L << i); map.put(1L << i, freq - 1); if (freq - 1 >= 2) { map.put(1L << (i + 1), map.getOrDefault(1L << (i + 1), 0) + (freq - 1) / 2); } } else { Long next = map.ceilingKey(1L << i); if (next == null) { canBeFound = false; break; } long curr = next; while (curr != (1L << i)) { int freq1 = map.get(curr); if (freq1 == 1) { map.remove(curr); } else { map.put(curr, freq1 - 1); } curr /= 2; map.put(curr, map.getOrDefault(curr, 0) + 2); count++; } int freq = map.get(1L << i); map.put(1L << i, freq - 1); if (freq - 1 >= 2) { map.put(1L << (i + 1), map.getOrDefault(1L << (i + 1), 0) + (freq - 1) / 2); } } } else { int freq = map.getOrDefault(1L << i, 0); if (freq >= 2) { map.put((1L << (i + 1)), map.getOrDefault(1L << (i + 1), 0) + freq / 2); } } } if (canBeFound) { out.println(count); } else { out.println(-1); } } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; ++i) array[i] = nextLong(); return array; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8"]
2 seconds
["2\n-1\n0"]
null
Java 11
standard input
[ "bitmasks", "greedy" ]
79440d6707a1d7553493130ebced47e3
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.
1,900
For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).
standard output
PASSED
2061dc85871d1f9814884e33cabb1516
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.util.*; import java.io.*; public class Task{ // taking inputs static BufferedReader s1; static BufferedWriter out; static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;} static int int_v (String s1){return Integer.parseInt(s1);} static long long_v(String s1){return Long.parseLong(s1);} static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;} static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;} static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));} static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res;} static long Modmul(long a,long b,long m){return ((a%m)*(b%m))%m;} static long ModInv(long a,long m){return Modpow(a,m-2,m);} static int mod=(int)1e9+47; //......................................@uthor_Alx.............................................. //if op<k l=m+1 else r=m static class pair{ long c;int idx; pair(long c1,int i){c=c1;idx=i;} } static int f(int[] x,int[] y){ if(y[1]==x[1]){ return x[0]-y[0]; } return y[1]-x[1]; } public static void main(String[] args) throws IOException{ assign(); int t=1;//int_v(read()),cn=1; while(t--!=0){ int n=int_v(read()); int[] fc=new int[100001]; int[] a=int_arr(); int q=int_v(read()); TreeSet<int[]> pq=new TreeSet<>((a1,b1)->f(a1,b1)); for(int z:a){ fc[z]++; } for(int i=1;i<=100000;i++){if(fc[i]>0) pq.add(new int[]{i,fc[i]});} while(q--!=0){ String[] s=read().split(" "); char c=s[0].charAt(0);int x=int_v(s[1]); int zz=1; if(c=='-') zz=-1; pq.remove(new int[]{x,fc[x]}); fc[x]+=zz; pq.add(new int[]{x,fc[x]}); boolean bb=false; int[] v=new int[3]; int i=1; for(int[] vv:pq){ v[i-1]=vv[1]; i++; if(i>3) break; } if(v[0]>=8) bb=true; if(v[0]>=4){ if((v[0]-4>=2&&v[1]>=2)||v[1]>=4||(v[1]>=2&&v[2]>=2)){bb=true;} } if(bb){ out.write("YES\n"); } else{out.write("NO\n");} } //out.write((k/2+1)+"\n"); } out.flush(); } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
1bbe54ada73edaac3de5f42772a6e595
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.util.*; public class Codeforces1 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] arr = new int[n]; HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); map.put(arr[i], map.getOrDefault(arr[i], 0) + 1); } String last = "NO"; int q = s.nextInt(); int c = 0, f = 0; int w = 0; if (w == 0) { HashMap<Integer, Integer> newm = new HashMap<>(); // System.out.print(map); // System.out.print(" "); newm.putAll(map); for (Integer key : newm.keySet()) { // System.out.println(newm.get(key)); if (newm.get(key) >= 4) { int val = newm.get(key); int mult = val / 4; newm.put(key, newm.get(key) - 4 * mult); c += mult; } if (newm.get(key) >= 2) { int val = newm.get(key); int mult = val / 2; newm.put(key, newm.get(key) - 2 * mult); f += mult; } } w++; } while (q-- > 0) { char ch = s.next().charAt(0); int a = s.nextInt(); if (ch == '+') { int val = map.getOrDefault(a, 0); if (val % 4 == 1) { f++; } if (val % 4 == 3) { f--; c++; } map.put(a, map.getOrDefault(a, 0) + 1); } else { int val = map.get(a); if (val % 4 == 2) f--; if (val % 4 == 0) { c--; f++; } map.put(a, map.getOrDefault(a, 0) - 1); } // System.out.println(c + " " + f); // System.out.println(c+" "+f); if (c > 1 || (c == 1 && f > 1)) { System.out.println("YES"); last = "YES"; } else { System.out.println("NO"); last = "NO"; } } } // } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
1cdc795464de8f1589567d43dc521d14
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.util.*; public class Main { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] a = new int[100001]; List<Integer> p2 = new ArrayList<Integer>(); List<Integer> p4 = new ArrayList<Integer>(); List<Integer> p6 = new ArrayList<Integer>(); List<Integer> p8 = new ArrayList<Integer>(); for (int i=0; i<n ; i++) { int temp = scanner.nextInt(); a[temp]++; if (a[temp] == 8) { p8.add(temp); p6.remove(Integer.valueOf(temp)); } else if (a[temp] == 6) { p6.add(temp); p4.remove(Integer.valueOf(temp)); } else if (a[temp] == 4) { p4.add(temp); p2.remove(Integer.valueOf(temp)); } else if (a[temp] == 2) { p2.add(temp); } } int q = scanner.nextInt(); for (int i=0; i<q; i++) { String signs = scanner.next(); char sign = signs.charAt(0); int planksChanged = scanner.nextInt(); if (sign == '+') { a[planksChanged]++; if (a[planksChanged] == 8) { p8.add(planksChanged); p6.remove(Integer.valueOf(planksChanged)); } else if (a[planksChanged] == 6) { p6.add(planksChanged); p4.remove(Integer.valueOf(planksChanged)); } else if (a[planksChanged] == 4) { p4.add(planksChanged); p2.remove(Integer.valueOf(planksChanged)); } else if (a[planksChanged] == 2) { p2.add(planksChanged); } } else if (sign == '-') { a[planksChanged]--; if (a[planksChanged] == 7) { p8.remove(Integer.valueOf(planksChanged)); p6.add(planksChanged); } else if (a[planksChanged] == 5) { p6.remove(Integer.valueOf(planksChanged)); p4.add(planksChanged); } else if (a[planksChanged] == 3) { p4.remove(Integer.valueOf(planksChanged)); p2.add(planksChanged); } else if (a[planksChanged] == 1) { p2.remove(Integer.valueOf(planksChanged)); } } if (p8.size() >= 1 || p6.size() > 1 || p4.size() > 1) { System.out.println("YES"); } else if (p6.size() == 1 && p4.size() == 1) { System.out.println("YES"); } else if (p6.size() == 1 && p2.size() >= 1) { System.out.println("YES"); } else if (p4.size() == 1 && p2.size() >= 2) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
7ed0ef2715e5868598ace9676d80457d
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.util.*; public class Main { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] a = new int[100001]; Set<Integer> p2 = new HashSet<Integer>(); Set<Integer> p4 = new HashSet<Integer>(); Set<Integer> p6 = new HashSet<Integer>(); Set<Integer> p8 = new HashSet<Integer>(); for (int i=0; i<n ; i++) { int temp = scanner.nextInt(); a[temp]++; if (a[temp] == 8) { p8.add(temp); p6.remove(temp); } else if (a[temp] == 6) { p6.add(temp); p4.remove(temp); } else if (a[temp] == 4) { p4.add(temp); p2.remove(temp); } else if (a[temp] == 2) { p2.add(temp); } } int q = scanner.nextInt(); for (int i=0; i<q; i++) { String signs = scanner.next(); char sign = signs.charAt(0); int planksChanged = scanner.nextInt(); if (sign == '+') { a[planksChanged]++; if (a[planksChanged] == 8) { p8.add(planksChanged); p6.remove(planksChanged); } else if (a[planksChanged] == 6) { p6.add(planksChanged); p4.remove(planksChanged); } else if (a[planksChanged] == 4) { p4.add(planksChanged); p2.remove(planksChanged); } else if (a[planksChanged] == 2) { p2.add(planksChanged); } } else if (sign == '-') { a[planksChanged]--; if (a[planksChanged] == 7) { p8.remove(planksChanged); p6.add(planksChanged); } else if (a[planksChanged] == 5) { p6.remove(planksChanged); p4.add(planksChanged); } else if (a[planksChanged] == 3) { p4.remove(planksChanged); p2.add(planksChanged); } else if (a[planksChanged] == 1) { p2.remove(planksChanged); } } if (p8.size() >= 1 || p6.size() > 1 || p4.size() > 1) { System.out.println("YES"); } else if (p6.size() == 1 && p4.size() == 1) { System.out.println("YES"); } else if (p6.size() == 1 && p2.size() >= 1) { System.out.println("YES"); } else if (p4.size() == 1 && p2.size() >= 2) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
8544228e9b896ff169d9d3117738f658
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.util.*; public class MyClass { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; for(int i=0;i<n;i++) { a[i] = sc.nextInt(); } int k = sc.nextInt(); HashMap<Integer,Integer> hs = new HashMap<Integer,Integer>(); int twocount = 0; int samecount = 0; for(int i=0;i<n;i++) { if(hs.containsKey(a[i])) { hs.put(a[i],hs.get(a[i])+1); } else { hs.put(a[i],1); } if(hs.get(a[i])%2==0) { twocount++; } if(hs.get(a[i])%4==0) { samecount++; } } for(int i=0;i<k;i++) { char ch = sc.next().charAt(0); int num = sc.nextInt(); if(ch=='+') { if(hs.containsKey(num)) { hs.put(num,hs.get(num)+1); } else { hs.put(num,1); } if(hs.get(num)%2==0) { twocount++; } if(hs.get(num)%4==0) { samecount++; } } if(ch=='-') { if(hs.containsKey(num)) { if(hs.get(num)%4==0) { samecount--; } if(hs.get(num)%2==0) { twocount--; } hs.put(num,hs.get(num)-1); if(hs.get(num)==0) { hs.remove(num); } } } if(twocount>=4&&samecount>=1) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
47464c80ea572ddca351fecc15fc238e
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.util.*; import java.io.*; public class tr0 { static PrintWriter out; static StringBuilder sb; static int mod = 1000000007; static long inf = (long) 1e16; static int[] l, r; static int n, m, k; static long all, ans; static ArrayList<Integer>[] ad; static long[][] memo; static boolean f; static boolean vis[]; static int[] c; static long sum, a[]; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int n = sc.nextInt(); TreeSet<pair> ts = new TreeSet<>(); c = new int[100001]; HashSet<Integer> j = new HashSet<>(); for (int i = 0; i < n; i++) { int x = sc.nextInt(); j.add(x); c[x]++; } for (int h : j) ts.add(new pair(h, c[h])); int q = sc.nextInt(); while (q-- > 0) { if (sc.nextChar() == '+') { int x = sc.nextInt(); ts.remove(new pair(x, c[x])); c[x]++; ts.add(new pair(x, c[x])); } else { int x = sc.nextInt(); ts.remove(new pair(x, c[x])); c[x]--; if (c[x] != 0) ts.add(new pair(x, c[x])); } if (ts.size() == 0) out.println("NO"); else if (ts.size() == 1) { if (ts.first().y >= 8) out.println("YES"); else out.println("NO"); } else if (ts.size() == 2) { if (ts.first().y >= 8) out.println("YES"); else if (ts.first().y >= 6) { pair cur = ts.pollFirst(); if (ts.first().y >= 2) out.println("YES"); else out.println("NO"); ts.add(new pair(cur.x, cur.y)); } else if (ts.first().y < 4) { out.println("NO"); } else { pair cur = ts.pollFirst(); if (ts.first().y >= 4) out.println("YES"); else out.println("NO"); ts.add(new pair(cur.x, cur.y)); } } else { pair cur1 = ts.pollFirst(); pair cur2 = ts.pollFirst(); pair cur3 = ts.pollFirst(); if (cur1.y >= 8) out.println("YES"); else if (cur1.y >= 6 && cur2.y >= 2) out.println("YES"); else if (cur1.y >= 4 && cur2.y >= 4) out.println("YES"); else if (cur1.y >= 4 && cur2.y >= 2 && cur3.y >= 2) out.println("YES"); else out.println("NO"); ts.add(new pair(cur1.x, cur1.y)); ts.add(new pair(cur2.x, cur2.y)); ts.add(new pair(cur3.x, cur3.y)); } } out.flush(); } static class pair implements Comparable<pair> { int x; int y; pair(int x, int y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } @Override public int compareTo(pair o) { if (y == o.y) return x - o.x; return o.y - y; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
0c6aa75b56d4e761e504cef900dfed26
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.io.*; import java.text.DecimalFormat; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); HashSet<Integer>g8=new HashSet<Integer>(); HashSet <Integer> g6=new HashSet<Integer>(); HashSet<Integer> g4=new HashSet <Integer>(); HashSet<Integer> g2=new HashSet<Integer>(); int []freq1=new int[(int)1e5+1]; for (int i=0;i<n;i++){ int u=sc.nextInt(); freq1[u]++; if(freq1[u]==8){ g8.add(u); g6.remove(u); } else if(freq1[u]==6){ g6.add(u); g4.remove(u); } else if(freq1[u]==4){ g4.add(u); g2.remove(u); } else if(freq1[u]==2){ g2.add(u); } } int q=sc.nextInt(); while(q-->0){ if(sc.next().charAt(0)=='+'){ int u=sc.nextInt(); freq1[u]++; if(freq1[u]==8){ g8.add(u); g6.remove(u); } else if(freq1[u]==6){ g6.add(u); g4.remove(u); } else if(freq1[u]==4){ g4.add(u); g2.remove(u); } else if(freq1[u]==2){ g2.add(u); } } else{ int u=sc.nextInt(); freq1[u]--; if(freq1[u]>=6&&freq1[u]<8){ g6.add(u); g8.remove(u); } else if(freq1[u]>=4&&freq1[u]<6){ g4.add(u); g6.remove(u); } else if(freq1[u]>=2&&freq1[u]<4){ g2.add(u); g4.remove(u); } else if(freq1[u]<2){ g2.remove(u); } } if (g8.size()>=1){ System.out.println("YES"); } else if(g6.size()>=2||(g6.size()==1&&(g4.size()>=1||g2.size()>=1))){ System.out.println("YES"); } else if(g4.size()>=2||(g4.size()==1&&g2.size()>=2)){ System.out.println("YES"); } else{ System.out.println("NO"); } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public boolean hasNext() { // TODO Auto-generated method stub return false; } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } }}
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
290f1edfb3f5ba8b3f25a7ddb40baf37
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
//created by Whiplash99 import java.io.*; import java.util.*; public class B { static class Pair implements Comparable<Pair> { int f, s; Pair(int f, int s){this.f = f;this.s = s;} public int compareTo(Pair b){return Integer.compare(b.s,this.s);} } public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,N; N=Integer.parseInt(br.readLine().trim()); String[] s=br.readLine().trim().split(" "); int a[]=new int[N]; for(i=0;i<N;i++) a[i]=Integer.parseInt(s[i]); int Q=Integer.parseInt(br.readLine().trim()); StringBuilder sb=new StringBuilder(); PriorityQueue<Pair> PQ=new PriorityQueue<>(); int[] val=new int[(int)1e5+5]; for(i=0;i<N;i++) val[a[i]]++; for(i=0;i<=(int)1e5;i++) if(val[i]>0) PQ.add(new Pair(i,val[i])); while (Q-->0) { s=br.readLine().trim().split(" "); int num=Integer.parseInt(s[1]); if(s[0].charAt(0)=='+') val[num]++; else val[num]--; if(val[num]>0) PQ.add(new Pair(num,val[num])); boolean flag=false; while (true) { if(PQ.isEmpty()) break; Pair f=PQ.poll(); int first=f.f; int count=f.s; if(count!= val[first]) continue; if(count>=8) flag=true; else if(count>=4) { while (true) { if(PQ.isEmpty()) break; Pair sec=PQ.poll(); int second= sec.f; int count2=sec.s; if(count2!= val[second]||second==first) continue; if(count2>=4||(count>=6&&count2>=2)) flag=true; else if(count2>=2) { while (true) { if(PQ.isEmpty()) break; Pair t=PQ.poll(); int third= t.f; int count3=t.s; if(count3!= val[third]||third==first||third==second) continue; if(count3>=2) flag=true; PQ.add(t); break; } } PQ.add(sec); break; } } PQ.add(f); break; } sb.append(flag?"YES\n":"NO\n"); } System.out.println(sb); } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
bae3a3ea4c8ccbf5bdce32f77f03e7eb
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ public static Scanner scn=new Scanner(new InputStreamReader(System.in)); public static void main(String[]args){ int n=scn.nextInt(); ArrayList<Integer>arr=new ArrayList<>(); HashMap<Integer,Integer>map=new HashMap<>(); HashSet<Integer>map1=new HashSet<>(); HashSet<Integer>map2=new HashSet<>(); while(n-->0){ int b=0; int a=scn.nextInt(); if(!map.containsKey(a)){ arr.add(a); map.put(a,1); b=1; }else{ b=map.get(a)+1; map.put(a,b); } if(b==4){ map1.remove(a); map2.add(a); } else if(b==2) map1.add(a); } int q=scn.nextInt(); while(q-->0){ char ch=scn.next().charAt(0); int a=scn.nextInt(); int b=0; if(ch=='+'){ if(map.containsKey(a)){ b=map.get(a)+1; map.put(a,b); if(b==4){ map1.remove(a); map2.add(a); } else if(b==2){ map1.add(a); } } else{ map.put(a,1); arr.add(a); b=1; } // // System.out.println(map); // System.out.println("map1: "+map1); // System.out.println("map2: "+map2); } else{ b=map.get(a)-1; map.put(a,b); // // System.out.println(map); // System.out.println("map1: "+map1); // System.out.println("map2: "+map2); if(b==3){ map2.remove(a); map1.add(a); } else if(b==1){ map1.remove(a); } else if(b==0){ map.remove(a); // for(int i=0;i<arr.size();i++){ // if(arr.get(i)==a){ // arr.remove(i); // break; // } // } } } if(map2.size()>=2){ System.out.println("YES"); } else if(map2.size()==1){ int c=map2.iterator().next(); // map2.add(c); int size=map.get(c); if(size>=8) System.out.println("YES"); else if(size>=6){ if(map1.size()>=1) System.out.println("YES"); else System.out.println("NO"); } else{//4 or 5 if(map1.size()>=2) System.out.println("YES"); else System.out.println("NO"); } } else System.out.println("NO"); } } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
b4e029846502edd81657da275cf650ca
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.util.*; import java.io.*; public class bitch{ public static Scanner scn=new Scanner(new InputStreamReader(System.in)); public static void main(String[]args){ int n=scn.nextInt(); ArrayList<Integer>arr=new ArrayList<>(); HashMap<Integer,Integer>map=new HashMap<>(); HashSet<Integer>map1=new HashSet<>(); HashSet<Integer>map2=new HashSet<>(); while(n-->0){ int b=0; int a=scn.nextInt(); if(!map.containsKey(a)){ arr.add(a); map.put(a,1); b=1; }else{ b=map.get(a)+1; map.put(a,b); } if(b==4){ map1.remove(a); map2.add(a); } else if(b==2) map1.add(a); } int q=scn.nextInt(); while(q-->0){ char ch=scn.next().charAt(0); int a=scn.nextInt(); int b=0; if(ch=='+'){ if(map.containsKey(a)){ b=map.get(a)+1; map.put(a,b); if(b==4){ map1.remove(a); map2.add(a); } else if(b==2){ map1.add(a); } } else{ map.put(a,1); arr.add(a); b=1; } // // System.out.println(map); // System.out.println("map1: "+map1); // System.out.println("map2: "+map2); } else{ b=map.get(a)-1; map.put(a,b); // // System.out.println(map); // System.out.println("map1: "+map1); // System.out.println("map2: "+map2); if(b==3){ map2.remove(a); map1.add(a); } else if(b==1){ map1.remove(a); } else if(b==0){ map.remove(a); // for(int i=0;i<arr.size();i++){ // if(arr.get(i)==a){ // arr.remove(i); // break; // } // } } } if(map2.size()>=2){ System.out.println("YES"); } else if(map2.size()==1){ int c=map2.iterator().next(); // map2.add(c); int size=map.get(c); if(size>=8) System.out.println("YES"); else if(size>=6){ if(map1.size()>=1) System.out.println("YES"); else System.out.println("NO"); } else{//4 or 5 if(map1.size()>=2) System.out.println("YES"); else System.out.println("NO"); } } else System.out.println("NO"); } } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
abd137697cf31a13a669fb4687f3e0bc
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.io.InputStream; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStreamReader; import java.io.IOException; import java.util.*; public class AppleStore { public static void main(String[] args) throws IOException { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n, q, countSq, countRec, planck; char query; int[] countAll; n = in.nextInt(); countAll = new int[(int)1e5+1]; for (int i = 0; i < n; i++) { planck = in.nextInt(); countAll[planck]++; } countSq = countRec = 0; for (int i = 0; i < countAll.length; i++) { countSq += countAll[i] / 4; countRec += (countAll[i] % 4) / 2; } q = in.nextInt(); for (int i = 0; i < q; i++) { query = in.next().charAt(0); planck = in.nextInt(); countSq -= countAll[planck] / 4; countRec -= (countAll[planck] % 4) / 2; if (query == '+') countAll[planck]++; else countAll[planck]--; countSq += countAll[planck] / 4; countRec += (countAll[planck] % 4) / 2; if (countSq >= 2 || (countSq == 1 && countRec >= 2)) pw.println("YES"); else pw.println("NO"); } pw.close(); } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
3888d47b5862abb07b8ff6589ec37116
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.util.Scanner; /** * @author Carry * @date 2020/11/15 */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); final int n = sc.nextInt(); int cnt4 = 0; int cnt2 = 0; int[] cnt = new int[100_000 + 1]; for (int i = 0; i < n; i++) { int num = sc.nextInt(); cnt[num]++; if (cnt[num] >= 2 && cnt[num] % 2 == 0) { cnt2++; } if (cnt[num] >= 4 && cnt[num] % 4 == 0) { cnt4++; } } int m = sc.nextInt(); while (m-- > 0) { boolean add = "+".equals(sc.next()); int num = sc.nextInt(); if (add) { cnt[num]++; if (cnt[num] >= 2 && cnt[num] % 2 == 0) { cnt2++; } if (cnt[num] >= 4 && cnt[num] % 4 == 0) { cnt4++; } } else { if (cnt[num] >= 2 && cnt[num] % 2 == 0) { cnt2--; } if (cnt[num] >= 4 && cnt[num] % 4 == 0) { cnt4--; } cnt[num]--; } if (cnt4 >= 1 && cnt2 >= 4) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
25e4204d208581c8d966e679ebf1c6de
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader In = new FastReader(); HashMap<Integer, Integer> map = new HashMap<>(); HashSet<Integer> dos = new HashSet<>(); HashSet<Integer> cuatro = new HashSet<>(); int n = In.nextInt(); for (int i = 0; i < n; i++) { int a = In.nextInt(); if (map.containsKey(a)) { map.replace(a, map.get(a) + 1); if (map.get(a) > 3 && dos.contains(a)) { dos.remove(a); cuatro.add(a); } else if (!cuatro.contains(a)) dos.add(a); } else map.put(a, 1); } int q = In.nextInt(); for (int i = 0; i < q; i++) { String[] string = In.nextLine().split(" "); int a = Integer.parseInt(string[1]); if (string[0].equals("+")) { if (!map.containsKey(a)) map.put(a, 0); map.replace(a, map.get(a) + 1); if (dos.contains(a) && map.get(a) > 3) { dos.remove(a); cuatro.add(a); } else if (map.get(a) > 1 && !cuatro.contains(a)) dos.add(a); } else { map.replace(a, map.get(a) - 1); if (cuatro.contains(a) && map.get(a) == 3) { cuatro.remove(a); dos.add(a); } else if (dos.contains(a) && map.get(a) < 2) dos.remove(a); } if(cuatro.size() >= 2) System.out.println("YES"); else if(cuatro.isEmpty()) System.out.println("NO"); else{ int num1 = -1; for(int j : cuatro) num1 = map.get(j); if(num1 >= 8) System.out.println("YES"); else if(dos.isEmpty()) System.out.println("NO"); else if(dos.size() >= 2) System.out.println("YES"); else if(num1 >= 6) System.out.println("YES"); else System.out.println("NO"); } } } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
d11c7cb3228138579c093a85728917b9
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.util.*; import java.io.*; public class ApplejackandStorages2 { // https://codeforces.com/contest/1393/problem/B public static void main(String[] args) throws IOException, FileNotFoundException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader("ApplejackandStorages")); int n = Integer.parseInt(in.readLine()); TreeMap<Long, Long> treemap = new TreeMap<>(); HashMap<Integer, Long> map = new HashMap<>(); StringTokenizer st = new StringTokenizer(in.readLine()); for (int i=0; i<n; i++) { int c = Integer.parseInt(st.nextToken()); if (map.containsKey(c)) { treemap.put(map.get(c), treemap.get(map.get(c))-1); if (treemap.get(map.get(c)) <= 0) treemap.remove(map.get(c)); } map.put(c, map.getOrDefault(c, 0l)+1); treemap.put(map.get(c), treemap.getOrDefault(map.get(c), 0l)+1); } int q = Integer.parseInt(in.readLine()); for (int i=0; i<q; i++) { st = new StringTokenizer(in.readLine()); char x = st.nextToken().charAt(0); int c = Integer.parseInt(st.nextToken()); if (x == '+') { if (map.containsKey(c)) { treemap.put(map.get(c), treemap.get(map.get(c))-1); if (treemap.get(map.get(c)) <= 0) treemap.remove(map.get(c)); } map.put(c, map.getOrDefault(c, 0l)+1); treemap.put(map.get(c), treemap.getOrDefault(map.get(c), 0l)+1); } else { if (map.containsKey(c)) { treemap.put(map.get(c), treemap.get(map.get(c))-1); if (treemap.get(map.get(c)) <= 0) treemap.remove(map.get(c)); } map.put(c, map.getOrDefault(c, 0l)-1); treemap.put(map.get(c), treemap.getOrDefault(map.get(c), 0l)+1); } check(treemap); } } public static void check(TreeMap<Long, Long> treemap) { boolean twofound1=false; boolean twofound2=false; boolean fourfound=false; o: for (Long a : treemap.descendingMap().keySet()) { long count = treemap.get(a); if (twofound1 && twofound2 && fourfound) break o; if (a <= 1) break o; if (a>=8) { System.out.println("YES"); return; } else if (a >= 6) { if (count >=2) { System.out.println("YES"); return; } if (fourfound) { twofound1=true; twofound2=true; } else { fourfound=true; if (twofound1) twofound2 = true; else twofound1 = true; } } else if (a >= 4) { if (count >= 2) { System.out.println("YES"); return; } if (fourfound) { twofound1=true; twofound2=true; } else fourfound=true; } else if (a >= 2) { if (count >= 2) { twofound2=true; twofound1=true; } else { if (twofound1) twofound2 = true; else twofound1 = true; } } } if (fourfound && twofound1 && twofound2) { System.out.println("YES"); } else System.out.println("NO"); } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
11a66bfccd7bce967e94824844e5d37a
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /** * @author hypnos * @date 2020/11/13 */ public class Main2 { public static void main(String[] args) throws IOException { // Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); // System.out.println(n); HashMap<Integer, Integer> map1 = new HashMap<>(); HashMap<Integer, Integer> map2 = new HashMap<>(); String[] strings = br.readLine().split(" "); for (int i = 0; i < n; i++) { int len = Integer.parseInt(strings[i]); map1.put(len, map1.getOrDefault(len, 0)+1); map2.put(map1.get(len), map2.getOrDefault(map1.get(len), 0)+1); // System.out.println(map); } int q = Integer.parseInt(br.readLine()); for (int i = 0; i < q; i++) { String[] read = br.readLine().split(" "); // System.out.println(Arrays.toString(read)); String op = read[0]; int len = Integer.parseInt(read[1]); if (op.equals("+")){ map1.put(len, map1.getOrDefault(len, 0)+1); map2.put(map1.get(len), map2.getOrDefault(map1.get(len), 0)+1); }else { map2.put(map1.get(len), map2.get(map1.get(len))-1); map1.put(len, map1.get(len)-1); } // LinkedList<Integer> list = new LinkedList<>(); boolean flag = map2.getOrDefault(8,0) > 0 || (map2.getOrDefault(6,0) > 0 && map2.getOrDefault(2,0) > 1) || map2.getOrDefault(4,0) > 1 || (map2.getOrDefault(4,0) > 0 && map2.getOrDefault(2,0) > 2); if (flag){ System.out.println("YES"); }else { System.out.println("NO"); } // int a; // if (list.size()>0){ // a = list.removeLast(); // }else { // writer.println("NO"); // continue; // } // if (a>=8){ // writer.println("YES"); // }else if (a>=6){ // if (list.size()>=1){ // writer.println("YES"); // }else { // writer.println("NO"); // } // }else if (a>=4){ // if (list.size()>1){ // writer.println("YES"); // }else { // if (list.size()==1){ // if (list.removeLast()>=4){ // writer.println("YES"); // }else { // writer.println("NO"); // } // }else { // writer.println("NO"); // } // } // }else { // writer.println("NO"); // } } br.close(); writer.flush(); } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
af8cf246969bd5e14514c8eecc15e068
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.util.Scanner; /** * @author hypnos * @date 2020/11/13 */ public class test { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int i; int[] a = new int[100001]; int[] c = new int[100001]; for (i = 0; i < n; i++) { int x = in.nextInt(); a[x]++; c[a[x]]++; } int q = in.nextInt(); while (q-- > 0) { String s = in.next(); int x = in.nextInt(); if (s.equals("+")) { a[x]++; c[a[x]]++; } else { c[a[x]]--; a[x]--; } boolean flag = c[8] > 0 || (c[6] > 0 && c[2] > 1) || c[4] > 1 || (c[4] > 0 && c[2] > 2); if (flag){ System.out.println("YES"); }else { System.out.println("NO"); } } } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
05ae0b93df64adda904155168ed6d59e
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int[] ar=new int[100001]; int n=Integer.parseInt(br.readLine()); String[] str=br.readLine().split(" "); int c4=0,c6=0,c2=0,c8=0; for(int i=0;i<n;i++){ int x=Integer.parseInt(str[i]); ar[x]++; } for(int i=0;i<100001;i++){ if(ar[i]>=8) c8++; else if(ar[i]>=6) c6++; else if(ar[i]>=4) c4++; else if(ar[i]==2 || ar[i]==3) c2++; } int t=Integer.parseInt(br.readLine()); while(t-->0){ String[] str1=br.readLine().split(" "); if(str1[0].equals("+")){ int x=Integer.parseInt(str1[1]); if((ar[x]+1)==8){ c8++; c6--; } else if((ar[x]+1)==6){ c6++; c4--; } else if((ar[x]+1)==4){ c4++; c2--; } else if((ar[x]+1)==2) c2++; ar[x]++; if(c8>0 || c6>=2 || c4>=2 ||(c2>=1 && c6>=1) || (c4>=1 && c2>=2) || (c6>=1 && c4>=1)){ System.out.println("YES"); } else System.out.println("NO"); } else{ int x=Integer.parseInt(str1[1]); if((ar[x]-1)==7){ c8--; c6++; } else if((ar[x]-1)==5){ c6--; c4++; } else if((ar[x]-1)==3){ c4--; c2++; } else if((ar[x]-1)==1){ c2--; } ar[x]--; if(c8>0 || c6>=2 || c4>=2 ||(c2>=1 && c6>=1) || (c4>=1 && c2>=2) || (c6>=1 && c4>=1)){ System.out.println("YES"); } else System.out.println("NO"); } } } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
c4e51656189671d237723ca3034baba0
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; /** * @author b * */ public class B { public static void main(String[] args) { Scanner scanner = new Scanner(); solve(scanner); } private static void solve(Scanner scanner) { int n = scanner.nextInt(); int[] a = scanner.nextIntArr(n); int numOfPairs = 0, numOfQuad = 0, numOfSix = 0,numOfEights = 0; Map<Integer,Integer> counts = new HashMap<Integer, Integer>(); for (int value : a) { counts.putIfAbsent(value, 0); Integer newVal = counts.computeIfPresent(value, (k, oldv) -> oldv + 1); if (newVal == 8) { numOfEights++; numOfSix--; } else if (newVal == 6) { numOfSix++; numOfQuad--; } else if (newVal == 4) { numOfQuad++; numOfPairs--; } else if (newVal == 2) { numOfPairs++; } } int q = scanner.nextInt(); for (int i =0; i < q ; ++i) { String command = scanner.next().trim(); int plankSize = scanner.nextInt(); if (command.contains("+")) { counts.putIfAbsent(plankSize, 0); Integer newVal = counts.computeIfPresent(plankSize, (k, oldv) -> oldv + 1); if (newVal == 8) { numOfEights++; numOfSix--; } else if (newVal == 6) { numOfSix++; numOfQuad--; } else if (newVal == 4) { numOfQuad++; numOfPairs--; } else if (newVal == 2) { numOfPairs++; } } else if (command.contains("-")) { counts.putIfAbsent(plankSize, 0); Integer newVal = counts.computeIfPresent(plankSize, (k, oldv) -> oldv - 1); if (newVal == 7) { numOfEights--; numOfSix++; } else if (newVal == 5) { numOfSix--; numOfQuad++; } else if (newVal == 3) { numOfQuad--; numOfPairs++; } else if (newVal == 1) { numOfPairs--; } } else { System.out.println(command); throw new RuntimeException(); } boolean ok = (numOfEights > 0) || (numOfSix > 0 && numOfPairs > 0) || (numOfSix >= 2) || (numOfSix > 0 && numOfQuad > 0) || (numOfQuad >= 2) || (numOfQuad >= 1 && numOfPairs >= 2); if (ok) { System.out.println("YES"); } else { System.out.println("NO"); } } } // Props to SecondThread static class Scanner { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokenizer = new StringTokenizer(""); String next() { while (!tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArr(int numberOfElements) { int[] values = new int[numberOfElements]; for (int i = 0; i < numberOfElements; i++) values[i] = nextInt(); return values; } long nextLong() { return Long.parseLong(next()); } } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
d57042499101eba6013ecabc8e8086f7
train_002.jsonl
1596810900
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class CodeForce_662 { public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); //long startTime = System.nanoTime(); int num = sc.nextInt(); int[] elements = new int[100001]; int two = 0, four = 0; for (int i = 0; i < num; i++) { int val = sc.nextInt(); elements[val]++; if (elements[val] % 4 == 0) { four++; two--; } else if (elements[val] %2 == 0) { two++; } } int events = sc.nextInt(); for (int i = 0; i < events; i++) { String op = sc.next(); if (op.equals("+")) { int val = sc.nextInt(); elements[val]++; if (elements[val] % 4 == 0) { four++; two--; } else if (elements[val] %2 == 0) { two++; } } else if (op.equals("-")) { int val = sc.nextInt(); if (elements[val] % 4 == 0) { four--; two++; } else if (elements[val] %2 == 0) { two--; } elements[val]--; } if (four >= 2) { pw.println("YES"); } else if (four == 1 && two >= 2) { pw.println("YES"); } else { pw.println("NO"); } } //long elapsedTime = System.nanoTime() - startTime; //pw.println(elapsedTime/1000000); pw.close(); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"]
2 seconds
["NO\nYES\nNO\nNO\nNO\nYES"]
NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.
Java 8
standard input
[ "data structures", "constructive algorithms", "implementation", "greedy" ]
d14bad9abf2a27ba57c80851405a360b
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).
1,400
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
standard output
PASSED
c680d81c666ab9fcf5af6c6a3dba784c
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.io.*; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main implements Runnable { static boolean use_n_tests = true; static int stack_size = 1 << 27; void solve(FastScanner in, PrintWriter out, int testNumber) { int n = in.nextInt(); int q = in.nextInt(); int[] a = new int[n]; boolean[] peek = new boolean[n]; boolean[] upeek = new boolean[n]; long ans = 0; for (int i = 0; i < a.length; i++) { a[i] = in.nextInt(); ans = Math.max(ans, a[i]); } for (int i = 0; i < a.length; i++) { if (i + 1 < a.length && i == 0) { if (a[i] > a[i + 1]) { peek[i] = true; } if (a[i] < a[i + 1]) { upeek[i] = true; } } if (i - 1 >= 0 && i == a.length - 1) { if (a[i] > a[i - 1]) { peek[i] = true; } if (a[i] < a[i - 1]) { upeek[i] = true; } } if (i + 1 < a.length && i - 1 >= 0) { if (a[i] > a[i + 1] && a[i] > a[i - 1]) { peek[i] = true; } if (a[i] < a[i + 1] && a[i] < a[i - 1]) { upeek[i] = true; } } } int p = 1; long ans1 = 0; long unpeek = -1; for (int i = 0; i < n; i++) { if (p == 1) { if (peek[i]) { ans1 += a[i]; p = 0; unpeek = -1; } } else { if (upeek[i]) { ans1 -= a[i]; unpeek = a[i]; p = 1; } } } if (p == 1 && unpeek != -1) { ans1 += unpeek; } out.println(Math.max(ans1, ans)); } // ****************************** template code *********** static class Range { int l, r; int id; public int getL() { return l; } public int getR() { return r; } public Range(int l, int r, int id) { this.l = l; this.r = r; this.id = id; } } static class Array { static Range[] readRanges(int n, FastScanner in) { Range[] result = new Range[n]; for (int i = 0; i < n; i++) { result[i] = new Range(in.nextInt(), in.nextInt(), i); } return result; } static public Integer[] read(int n, FastScanner in) { Integer[] out = new Integer[n]; for (int i = 0; i < out.length; i++) { out[i] = in.nextInt(); } return out; } static public int[] readint(int n, FastScanner in) { int[] out = new int[n]; for (int i = 0; i < out.length; i++) { out[i] = in.nextInt(); } return out; } } class Graph { List<List<Integer>> create(int n) { List<List<Integer>> graph = new ArrayList<>(); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } return graph; } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream io) { br = new BufferedReader(new InputStreamReader(io)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } void run_t_tests() { int t = in.nextInt(); int i = 0; while (t-- > 0) { solve(in, out, i++); } } void run_one() { solve(in, out, -1); } @Override public void run() { in = new FastScanner(System.in); out = new PrintWriter(System.out); if (use_n_tests) { run_t_tests(); } else { run_one(); } out.close(); } static FastScanner in; static PrintWriter out; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(null, new Main(), "", stack_size); thread.start(); thread.join(); } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
dca51a14e34cddbd4294f384149a89a5
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class T3 extends PrintWriter { public T3() { super(System.out); } public static void main(String[] args) { Scanner s = new Scanner(System.in); T3 main = new T3(); int n = s.nextInt(); while (n-- > 0) { main.MainPrint(s); } main.flush(); } private void MainPrint(Scanner s) { int n = s.nextInt(); s.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) nums[i] = s.nextInt(); long[] count = new long[n]; int past = -1; for (int i = n - 2; i >= 0; i--) { count[i] = count[i + 1]; if (nums[i + 1] < past){ count[i] +=past - nums[i + 1]; } past = nums[i + 1]; } long ans = 0; for (int i = 0; i < n; i++){ ans = Math.max(ans,nums[i] + count[i]); } // println(Arrays.toString(count)); println(ans); } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
51512de6ce7938e1dae9f6a27ff1923c
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.*; public class PokemonArmy { public static void main(String[] args) { Scanner in = new Scanner (System.in); int t = in.nextInt(); for (int i=0; i<t; i++) { int n = in.nextInt(); in.nextInt(); long [] arr = new long [n]; for (int j=0; j<n; j++) { arr[j] = in.nextLong(); } Solve(arr, n); } } public static void Solve (long[]value, int n) { long [] even = new long [n]; long [] odd = new long [n]; even[0] = 0; odd[0] = value[0]; for (int i=1; i<n; i++) { even[i] = Math.max(even[i-1], odd[i-1] - value[i]); odd[i] = Math.max(odd[i-1], even[i-1] + value[i]); } long maxValue = 0; for (int i=0; i<n; i++) { long temp = Math.max(even[i], odd[i]); maxValue = Math.max(temp, maxValue); } System.out.println(maxValue); /*check System.out.print("even: "); for (int i=0; i<n; i++) { System.out.print(even[i] + " "); } System.out.println(); System.out.print("odd: "); for (int i=0; i<n; i++) { System.out.print(odd[i] + " "); } System.out.println(); */ } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
0ec9c5abae8e904fe39ae6fd8db13d61
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.*; public class hundredsixtyfive { public static void main(String[] args) { int t; Scanner sc=new Scanner(System.in); t=sc.nextInt(); while(t-->0) { int n,q; n=sc.nextInt(); q=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); int pv[]=new int[n]; if(n==1) { System.out.println(a[0]); continue; } int pos=0; if(a[0]>a[1]) pv[pos++]=a[0]; for(int i=1;i<n-1;i++) { if(a[i]>a[i-1] && a[i]>a[i+1]) pv[pos++]=a[i]; if(pos!=0 && a[i]<a[i-1] && a[i]<a[i+1]) pv[pos++]=a[i]; } if(a[n-1]>a[n-2]) pv[pos++]=a[n-1]; //System.out.println(Arrays.toString(pv)); long ans=0; for(int i=0;i<pos;i++) { if(i%2==0) ans+=pv[i]; else ans-=pv[i]; } System.out.println(ans); } } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
199960109aa020373763c8fc30225717
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
// "static void main" must be defined in a public class. import java.util.Scanner; public class Main { private static long f(int index,int neg,int[] a){ if(index >= a.length)return 0; if(dp[index][neg] != null)return dp[index][neg]; long max = Long.MIN_VALUE; if(neg == 0){ max = Math.max(max, a[index]+f(index+1,1,a)); } else{ max = Math.max(max, -a[index]+f(index+1,0,a)); } max = Math.max(max, f(index+1,neg,a)); return dp[index][neg] = max; } static Long[][] dp; public static void main(String[] args) { /* 1 4 3 7 10 0001 0100 0011 0111 1001 1 - 0 4 - 2 3 - 1 7-2 10 - 3 1 2 5 4 3 6 7 state : f(index,sum,neg) */ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int q = sc.nextInt(); dp = new Long[n][2]; int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = sc.nextInt(); System.out.println(f(0,0,a)); } } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
001df76c9001e986877f07fc44ddc86c
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeSet; public class R672 { static int a[]; static int n; static long dp[][]; public static long dp(int idx, int sign) { if (idx == n) return 0; if(dp[idx][sign]!=-1)return dp[idx][sign]; long take = 0; if (sign == 0) take = a[idx] + dp(idx + 1, 1); if (sign == 1) take = -1 * a[idx] + dp(idx + 1, 0); long leave = dp(idx + 1, sign); return dp[idx][sign]=Math.max(take, leave); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { n = sc.nextInt(); int q = sc.nextInt(); a = new int[n]; dp=new long[n][2]; for(long x[]:dp) Arrays.fill(x, -1); for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } pw.println(dp(0,0)); } pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
10b98e4b46e325ef250970be7a10f5c1
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.TreeSet; public class R672 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int q = sc.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } long res = 0; int i=0; while(i<n) { int c=a[i];int max=a[i]; while(i<n&&a[i]>=c) { max=Math.max(a[i], max); c=a[i]; i++; } c=i==n?0:a[i];int min=c; while(i<n&&a[i]<=c) { min=Math.min(a[i], min); c=a[i]; i++; } res+=max; res-=i==n?0:min; } pw.println(res); } pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
87a9b841a9c0828c25a8b6fcb2a1e082
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.*; public class Main { static long dp[][]=new long [300005][2]; static Scanner sc=new Scanner(System.in); public static void main(String[] args) { int n=sc.nextInt(); for(int i=0;i<n;i++) { show(); } } static void show() { int n=sc.nextInt(); int q=sc.nextInt(); long arr[]=new long [n]; for(int i=0;i<n;i++) { arr[i]=sc.nextLong(); } dp[0][0]=0; dp[0][1]=arr[0]; for(int i=1;i<n;i++) { dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]-arr[i]); dp[i][1]=Math.max(dp[i-1][1], Math.max(dp[i-1][0]+arr[i],arr[i])); } System.out.println(Math.max(dp[n-1][1], dp[n-1][0])); } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
f0e261dca5115515fcfa33e5ffe566dc
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.*; public class Main { static long dp[][]=new long [300005][2]; static Scanner sc=new Scanner(System.in); public static void main(String[] args) { int n=sc.nextInt(); for(int i=0;i<n;i++) { show(); } } private static void show() { int n=sc.nextInt(); int q=sc.nextInt(); long arr[]=new long [n]; for(int i=0;i<n;i++) { arr[i]=sc.nextLong(); } dp[0][0]=0; dp[0][1]=arr[0]; for(int i=1;i<n;i++) { dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]-arr[i]); dp[i][1]=Math.max(dp[i-1][1], Math.max(dp[i-1][0]+arr[i],arr[i])); } System.out.println(Math.max(dp[n-1][1], dp[n-1][0])); } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
ab0e23a8cd59117de4b16fd9cfd58671
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.*; import java.io.*; public class pokeeasy { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(in.readLine()); for(int i = 0; i < t; i++) { StringTokenizer line = new StringTokenizer(in.readLine()); int n = Integer.parseInt(line.nextToken()); int[] a = new int[n]; line = new StringTokenizer(in.readLine()); for(int j = 0; j < n; j++) { a[j] = Integer.parseInt(line.nextToken()); } long[][] dp = new long[2][n]; dp[0][0] = a[0]; for(int j = 1; j < n; j++) { dp[1][j] = Math.max(dp[1][j - 1], dp[0][j - 1] - a[j]); dp[0][j] = Math.max(dp[0][j - 1], dp[1][j - 1] + a[j]); } out.println(Math.max(dp[0][n - 1], dp[1][n - 1])); } in.close(); out.close(); } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
0e8c21a2f320b3f3e41185fe6c6eeabd
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.awt.Point; // SHIVAM GUPTA : //NSIT //decoder_1671 // STOP NOT TILL IT IS DONE OR U DIE . // U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................ // ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 = 3.3219 // odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1 x >=4 // FOR ANY ODD NO N : N,N-1,N-2 //ALL ARE PAIRWISE COPRIME //THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS // two consecutive odds are always coprime to each other // two consecutive even have always gcd = 2 ; public class Main { // static int[] arr = new int[100002] ; // static int[] dp = new int[100002] ; static PrintWriter out; static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(System.out); } String next(){ while(st==null || !st.hasMoreElements()){ try{ st= new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str = ""; try{ str=br.readLine(); } catch(IOException e){ e.printStackTrace(); } return str; } } //////////////////////////////////////////////////////////////////////////////////// public static int countDigit(long n) { return (int)Math.floor(Math.log10(n) + 1); } ///////////////////////////////////////////////////////////////////////////////////////// public static int sumOfDigits(long n) { if( n< 0)return -1 ; int sum = 0; while( n > 0) { sum = sum + (int)( n %10) ; n /= 10 ; } return sum ; } ////////////////////////////////////////////////////////////////////////////////////////////////// public static long arraySum(int[] arr , int start , int end) { long ans = 0 ; for(int i = start ; i <= end ; i++)ans += arr[i] ; return ans ; } ///////////////////////////////////////////////////////////////////////////////// public static int mod(int x) { if(x <0)return -1*x ; else return x ; } public static long mod(long x) { if(x <0)return -1*x ; else return x ; } //////////////////////////////////////////////////////////////////////////////// public static void swapArray(int[] arr , int start , int end) { while(start < end) { int temp = arr[start] ; arr[start] = arr[end]; arr[end] = temp; start++ ;end-- ; } } ////////////////////////////////////////////////////////////////////////////////// public static int[][] rotate(int[][] input){ int n =input.length; int m = input[0].length ; int[][] output = new int [m][n]; for (int i=0; i<n; i++) for (int j=0;j<m; j++) output [j][n-1-i] = input[i][j]; return output; } /////////////////////////////////////////////////////////////////////////////////////////////////////// public static int countBits(long n) { int count = 0; while (n != 0) { count++; n = (n) >> (1L) ; } return count; } /////////////////////////////////////////// //////////////////////////////////////////////// public static boolean isPowerOfTwo(long n) { if(n==0) return false; if(((n ) & (n-1)) == 0 ) return true ; else return false ; } ///////////////////////////////////////////////////////////////////////////////////// public static int min(int a ,int b , int c, int d) { int[] arr = new int[4] ; arr[0] = a;arr[1] = b ;arr[2] = c;arr[3] = d;Arrays.sort(arr) ; return arr[0]; } ///////////////////////////////////////////////////////////////////////////// public static int max(int a ,int b , int c, int d) { int[] arr = new int[4] ; arr[0] = a;arr[1] = b ;arr[2] = c;arr[3] = d;Arrays.sort(arr) ; return arr[3]; } /////////////////////////////////////////////////////////////////////////////////// public static String reverse(String input) { StringBuilder str = new StringBuilder("") ; for(int i =input.length()-1 ; i >= 0 ; i-- ) { str.append(input.charAt(i)); } return str.toString() ; } /////////////////////////////////////////////////////////////////////////////////////////// public static boolean sameParity(long a ,long b ) { long x = a% 2L; long y = b%2L ; if(x==y)return true ; else return false ; } //////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean isPossibleTriangle(int a ,int b , int c) { if( a + b > c && c+b > a && a +c > b)return true ; else return false ; } //////////////////////////////////////////////////////////////////////////////////////////// static long xnor(long num1, long num2) { if (num1 < num2) { long temp = num1; num1 = num2; num2 = temp; } num1 = togglebit(num1); return num1 ^ num2; } static long togglebit(long n) { if (n == 0) return 1; long i = n; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return i ^ n; } /////////////////////////////////////////////////////////////////////////////////////////////// public static int xorOfFirstN(int n) { if( n % 4 ==0)return n ; else if( n % 4 == 1)return 1 ; else if( n % 4 == 2)return n+1 ; else return 0 ; } ////////////////////////////////////////////////////////////////////////////////////////////// public static int gcd(int a, int b ) { if(b==0)return a ; else return gcd(b,a%b) ; } public static long gcd(long a, long b ) { if(b==0)return a ; else return gcd(b,a%b) ; } //////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a, int b ,int c , int d ) { int temp = lcm(a,b , c) ; int ans = lcm(temp ,d ) ; return ans ; } /////////////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a, int b ,int c ) { int temp = lcm(a,b) ; int ans = lcm(temp ,c) ; return ans ; } //////////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a , int b ) { int gc = gcd(a,b); return (a*b)/gc ; } public static long lcm(long a , long b ) { long gc = gcd(a,b); return (a*b)/gc ; } /////////////////////////////////////////////////////////////////////////////////////////// static boolean isPrime(long n) { if(n==1) { return false ; } boolean ans = true ; for(long i = 2L; i*i <= n ;i++) { if(n% i ==0) { ans = false ;break ; } } return ans ; } /////////////////////////////////////////////////////////////////////////// static int sieve = 1000000 ; static boolean[] prime = new boolean[sieve + 1] ; public static void sieveOfEratosthenes() { // FALSE == prime // TRUE == COMPOSITE // FALSE== 1 // time complexity = 0(NlogLogN)== o(N) // gives prime nos bw 1 to N for(int i = 4; i<= sieve ; i++) { prime[i] = true ; i++ ; } for(int p = 3; p*p <= sieve; p++) { if(prime[p] == false) { for(int i = p*p; i <= sieve; i += p) prime[i] = true; } p++ ; } } /////////////////////////////////////////////////////////////////////////////////// public static void sortD(int[] arr , int s , int e) { sort(arr ,s , e) ; int i =s ; int j = e ; while( i < j) { int temp = arr[i] ; arr[i] =arr[j] ; arr[j] = temp ; i++ ; j-- ; } return ; } ///////////////////////////////////////////////////////////////////////////////////////// public static long countSubarraysSumToK(long[] arr ,long sum ) { HashMap<Long,Long> map = new HashMap<>() ; int n = arr.length ; long prefixsum = 0 ; long count = 0L ; for(int i = 0; i < n ; i++) { prefixsum = prefixsum + arr[i] ; if(sum == prefixsum)count = count+1 ; if(map.containsKey(prefixsum -sum)) { count = count + map.get(prefixsum -sum) ; } if(map.containsKey(prefixsum )) { map.put(prefixsum , map.get(prefixsum) +1 ); } else{ map.put(prefixsum , 1L ); } } return count ; } /////////////////////////////////////////////////////////////////////////////////////////////// // KMP ALGORITHM : TIME COMPL:O(N+M) // FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING //RETURN THE ARRAYLIST OF INDEXES // IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING public static ArrayList<Integer> kmpAlgorithm(String str , String pat) { ArrayList<Integer> list =new ArrayList<>(); int n = str.length() ; int m = pat.length() ; String q = pat + "#" + str ; int[] lps =new int[n+m+1] ; longestPefixSuffix(lps, q,(n+m+1)) ; for(int i =m+1 ; i < (n+m+1) ; i++ ) { if(lps[i] == m) { list.add(i-2*m) ; } } return list ; } public static void longestPefixSuffix(int[] lps ,String str , int n) { lps[0] = 0 ; for(int i = 1 ; i<= n-1; i++) { int l = lps[i-1] ; while( l > 0 && str.charAt(i) != str.charAt(l)) { l = lps[l-1] ; } if(str.charAt(i) == str.charAt(l)) { l++ ; } lps[i] = l ; } } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n // TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1 // or n and the no will be coprime in nature //time : O(n*(log(logn))) public static void eulerTotientFunction(int[] arr ,int n ) { for(int i = 1; i <= n ;i++)arr[i] =i ; for(int i= 2 ; i<= n ;i++) { if(arr[i] == i) { arr[i] =i-1 ; for(int j =2*i ; j<= n ; j+= i ) { arr[j] = (arr[j]*(i-1))/i ; } } } return ; } ///////////////////////////////////////////////////////////////////////////////////////////// public static long nCr(int n,int k) { long ans=1L; k=k>n-k?n-k:k; int j=1; for(;j<=k;j++,n--) { if(n%j==0) { ans*=n/j; }else if(ans%j==0) { ans=ans/j*n; }else { ans=(ans*n)/j; } } return ans; } /////////////////////////////////////////////////////////////////////////////////////////// public static ArrayList<Integer> allFactors(int n) { ArrayList<Integer> list = new ArrayList<>() ; for(int i = 1; i*i <= n ;i++) { if( n % i == 0) { if(i*i == n) { list.add(i) ; } else{ list.add(i) ; list.add(n/i) ; } } } return list ; } public static ArrayList<Long> allFactors(long n) { ArrayList<Long> list = new ArrayList<>() ; for(long i = 1L; i*i <= n ;i++) { if( n % i == 0) { if(i*i == n) { list.add(i) ; } else{ list.add(i) ; list.add(n/i) ; } } } return list ; } //////////////////////////////////////////////////////////////////////////////////////////////////// static final int MAXN = 10000001; static int spf[] = new int[MAXN]; static void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) spf[i] = i; for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { if (spf[i] == i) { for (int j=i*i; j<MAXN; j+=i) if (spf[j]==j) spf[j] = i; } } } // The above code works well for n upto the order of 10^7. // Beyond this we will face memory issues. // Time Complexity: The precomputation for smallest prime factor is done in O(n log log n) // using sieve. // Where as in the calculation step we are dividing the number every time by // the smallest prime number till it becomes 1. // So, let’s consider a worst case in which every time the SPF is 2 . // Therefore will have log n division steps. // Hence, We can say that our Time Complexity will be O(log n) in worst case. static Vector<Integer> getFactorization(int x) { Vector<Integer> ret = new Vector<>(); while (x != 1) { ret.add(spf[x]); x = x / spf[x]; } return ret; } ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// public static void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; //Copy data to temp arrays for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() public static void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; //Copy data to temp arrays for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } ///////////////////////////////////////////////////////////////////////////////////////// public static long knapsack(int[] weight,long value[],int maxWeight){ int n= value.length ; //dp[i] stores the profit with KnapSack capacity "i" long []dp = new long[maxWeight+1]; //initially profit with 0 to W KnapSack capacity is 0 Arrays.fill(dp, 0); // iterate through all items for(int i=0; i < n; i++) //traverse dp array from right to left for(int j = maxWeight; j >= weight[i]; j--) dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]); /*above line finds out maximum of dp[j](excluding ith element value) and val[i] + dp[j-wt[i]] (including ith element value and the profit with "KnapSack capacity - ith element weight") */ return dp[maxWeight]; } /////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// // to return max sum of any subarray in given array public static long kadanesAlgorithm(long[] arr) { long[] dp = new long[arr.length] ; dp[0] = arr[0] ; long max = dp[0] ; for(int i = 1; i < arr.length ; i++) { if(dp[i-1] > 0) { dp[i] = dp[i-1] + arr[i] ; } else{ dp[i] = arr[i] ; } if(dp[i] > max)max = dp[i] ; } return max ; } ///////////////////////////////////////////////////////////////////////////////////////////// public static long kadanesAlgorithm(int[] arr) { long[] dp = new long[arr.length] ; dp[0] = arr[0] ; long max = dp[0] ; for(int i = 1; i < arr.length ; i++) { if(dp[i-1] > 0) { dp[i] = dp[i-1] + arr[i] ; } else{ dp[i] = arr[i] ; } if(dp[i] > max)max = dp[i] ; } return max ; } /////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// public static long binarySerachGreater(int[] arr , int start , int end , int val) { // fing total no of elements strictly grater than val in sorted array arr if(start > end)return 0 ; //Base case int mid = (start + end)/2 ; if(arr[mid] <=val) { return binarySerachGreater(arr,mid+1, end ,val) ; } else{ return binarySerachGreater(arr,start , mid -1,val) + end-mid+1 ; } } ////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// //TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING // JUST CALL generatePermutation( str, start, end) start :inclusive ,end : exclusive //Function for swapping the characters at position I with character at position j public static String swapString(String a, int i, int j) { char[] b =a.toCharArray(); char ch; ch = b[i]; b[i] = b[j]; b[j] = ch; return String.valueOf(b); } //Function for generating different permutations of the string public static void generatePermutation(String str, int start, int end) { //Prints the permutations if (start == end-1) System.out.println(str); else { for (int i = start; i < end; i++) { //Swapping the string by fixing a character str = swapString(str,start,i); //Recursively calling function generatePermutation() for rest of the characters generatePermutation(str,start+1,end); //Backtracking and swapping the characters again. str = swapString(str,start,i); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// public static long factMod(long n, long mod) { if (n <= 1) return 1; long ans = 1; for (int i = 1; i <= n; i++) { ans = (ans * i) % mod; } return ans; } ///////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// public static long power(long x ,long n) { //time comp : o(logn) if(n==0)return 1L ; if(n==1)return x; long ans =1L ; while(n>0) { if(n % 2 ==1) { ans = ans *x ; } n /= 2 ; x = x*x ; } return ans ; } //////////////////////////////////////////////////////////////////////////////////////////////////// public static long powerMod(long x, long n, long mod) { //time comp : o(logn) if(n==0)return 1L ; if(n==1)return x; long ans = 1; while (n > 0) { if (n % 2 == 1) ans = (ans * x) % mod; x = (x * x) % mod; n /= 2; } return ans; } ////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// /* lowerBound - finds largest element equal or less than value paased upperBound - finds smallest element equal or more than value passed if not present return -1; */ public static long lowerBound(long[] arr,long k) { long ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]<=k) { ans=arr[mid]; start=mid+1; } else { end=mid-1; } } return ans; } public static int lowerBound(int[] arr,int k) { int ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]<=k) { ans=arr[mid]; start=mid+1; } else { end=mid-1; } } return ans; } public static long upperBound(long[] arr,long k) { long ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]>=k) { ans=arr[mid]; end=mid-1; } else { start=mid+1; } } return ans; } public static int upperBound(int[] arr,int k) { int ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]>=k) { ans=arr[mid]; end=mid-1; } else { start=mid+1; } } return ans; } ////////////////////////////////////////////////////////////////////////////////////////// public static void printArray(int[] arr , int si ,int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } } public static void printArrayln(int[] arr , int si ,int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } out.println() ; } public static void printLArray(long[] arr , int si , int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } } public static void printLArrayln(long[] arr , int si , int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } out.println() ; } public static void printtwodArray(int[][] ans) { for(int i = 0; i< ans.length ; i++) { for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +" "); out.println() ; } out.println() ; } static long modPow(long a, long x, long p) { //calculates a^x mod p in logarithmic time. long res = 1; while(x > 0) { if( x % 2 != 0) { res = (res * a) % p; } a = (a * a) % p; x /= 2; } return res; } static long modInverse(long a, long p) { //calculates the modular multiplicative of a mod m. //(assuming p is prime). return modPow(a, p-2, p); } static long modBinomial(long n, long k, long p) { // calculates C(n,k) mod p (assuming p is prime). long numerator = 1; // n * (n-1) * ... * (n-k+1) for (int i=0; i<k; i++) { numerator = (numerator * (n-i) ) % p; } long denominator = 1; // k! for (int i=1; i<=k; i++) { denominator = (denominator * i) % p; } // numerator / denominator mod p. return ( numerator* modInverse(denominator,p) ) % p; } ///////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// static ArrayList<Integer>[] tree ; // static long[] child; // static int mod= 1000000007 ; // static int[][] pre = new int[3001][3001]; // static int[][] suf = new int[3001][3001] ; //program to calculate noof nodes in subtree for every vertex including itself public static void countNoOfNodesInsubtree(int child ,int par , int[] dp) { int count = 1 ; for(int x : tree[child]) { if(x== par)continue ; countNoOfNodesInsubtree(x,child,dp) ; count= count + dp[x] ; } dp[child] = count ; } public static void depth(int child ,int par , int[] dp , int d ) { dp[child] =d ; for(int x : tree[child]) { if(x== par)continue ; depth(x,child,dp,d+1) ; } } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// public static void solve() { FastReader scn = new FastReader() ; //Scanner scn = new Scanner(System.in); //int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ; // product of first 11 prime nos is greater than 10 ^ 12; //ArrayList<Integer> arr[] = new ArrayList[n] ; ArrayList<Integer> list = new ArrayList<>() ; ArrayList<Long> listl = new ArrayList<>() ; ArrayList<Integer> lista = new ArrayList<>() ; ArrayList<Integer> listb = new ArrayList<>() ; //ArrayList<String> lists = new ArrayList<>() ; //HashMap<Integer,Integer> map = new HashMap<>() ; HashMap<Long,Long> map = new HashMap<>() ; HashMap<Integer,Integer> map1 = new HashMap<>() ; HashMap<Integer,Integer> map2 = new HashMap<>() ; //HashMap<String,Integer> maps = new HashMap<>() ; //HashMap<Integer,Boolean> mapb = new HashMap<>() ; //HashMap<Point,Integer> point = new HashMap<>() ; Set<Integer> set = new HashSet<>() ; Set<Integer> setx = new HashSet<>() ; Set<Integer> sety = new HashSet<>() ; StringBuilder sb =new StringBuilder("") ; //Collections.sort(list); //if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ; //else map.put(arr[i],1) ; // if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ; // else map.put(temp,1) ; //int bit =Integer.bitCount(n); // gives total no of set bits in n; // Arrays.sort(arr, new Comparator<Pair>() { // @Override // public int compare(Pair a, Pair b) { // if (a.first != b.first) { // return a.first - b.first; // for increasing order of first // } // return a.second - b.second ; //if first is same then sort on second basis // } // }); int testcase = 1; testcase = scn.nextInt() ; for(int testcases =1 ; testcases <= testcase ;testcases++) { //if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ; //if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ; // int n = scn.nextInt() ; // tree = new ArrayList[n] ; // for(int i = 0; i< n; i++) // { // tree[i] = new ArrayList<Integer>(); // } // for(int i = 0 ; i <= n-2 ; i++) // { // int fv = scn.nextInt()-1 ; int sv = scn.nextInt()-1 ; // tree[fv].add(sv) ; // tree[sv].add(fv) ; // } int n = scn.nextInt() ; int q = scn.nextInt() ; long[] arr = new long[n+2] ; for(int i = 1 ; i <= n ; i++)arr[i] = scn.nextLong() ; long ans = arr[1] ; for(int i = 2; i <= n ;i++) { ans = ans + Math.max(0L,arr[i]- arr[i-1]) ; } out.println(ans) ; sb.delete(0 , sb.length()) ; list.clear() ;listb.clear() ; map.clear() ; map1.clear() ; map2.clear() ; set.clear() ;sety.clear() ; } // test case end loop out.flush() ; } // solve fn ends public static void main (String[] args) throws java.lang.Exception { solve() ; } } class Pair { int first ; int second ; @Override public String toString() { String ans = "" ; ans += this.first ; ans += " "; ans += this.second ; return ans ; } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
54dc2d87db930a3518c2fca8c2cebcd0
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.awt.Point; // SHIVAM GUPTA : //NSIT //decoder_1671 // STOP NOT TILL IT IS DONE OR U DIE . // U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................ // ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 = 3.3219 // odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1 x >=4 // FOR ANY ODD NO N : N,N-1,N-2 //ALL ARE PAIRWISE COPRIME //THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS // two consecutive odds are always coprime to each other // two consecutive even have always gcd = 2 ; public class Main { // static int[] arr = new int[100002] ; // static int[] dp = new int[100002] ; static PrintWriter out; static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(System.out); } String next(){ while(st==null || !st.hasMoreElements()){ try{ st= new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str = ""; try{ str=br.readLine(); } catch(IOException e){ e.printStackTrace(); } return str; } } //////////////////////////////////////////////////////////////////////////////////// public static int countDigit(long n) { return (int)Math.floor(Math.log10(n) + 1); } ///////////////////////////////////////////////////////////////////////////////////////// public static int sumOfDigits(long n) { if( n< 0)return -1 ; int sum = 0; while( n > 0) { sum = sum + (int)( n %10) ; n /= 10 ; } return sum ; } ////////////////////////////////////////////////////////////////////////////////////////////////// public static long arraySum(int[] arr , int start , int end) { long ans = 0 ; for(int i = start ; i <= end ; i++)ans += arr[i] ; return ans ; } ///////////////////////////////////////////////////////////////////////////////// public static int mod(int x) { if(x <0)return -1*x ; else return x ; } public static long mod(long x) { if(x <0)return -1*x ; else return x ; } //////////////////////////////////////////////////////////////////////////////// public static void swapArray(int[] arr , int start , int end) { while(start < end) { int temp = arr[start] ; arr[start] = arr[end]; arr[end] = temp; start++ ;end-- ; } } ////////////////////////////////////////////////////////////////////////////////// public static int[][] rotate(int[][] input){ int n =input.length; int m = input[0].length ; int[][] output = new int [m][n]; for (int i=0; i<n; i++) for (int j=0;j<m; j++) output [j][n-1-i] = input[i][j]; return output; } /////////////////////////////////////////////////////////////////////////////////////////////////////// public static int countBits(long n) { int count = 0; while (n != 0) { count++; n = (n) >> (1L) ; } return count; } /////////////////////////////////////////// //////////////////////////////////////////////// public static boolean isPowerOfTwo(long n) { if(n==0) return false; if(((n ) & (n-1)) == 0 ) return true ; else return false ; } ///////////////////////////////////////////////////////////////////////////////////// public static int min(int a ,int b , int c, int d) { int[] arr = new int[4] ; arr[0] = a;arr[1] = b ;arr[2] = c;arr[3] = d;Arrays.sort(arr) ; return arr[0]; } ///////////////////////////////////////////////////////////////////////////// public static int max(int a ,int b , int c, int d) { int[] arr = new int[4] ; arr[0] = a;arr[1] = b ;arr[2] = c;arr[3] = d;Arrays.sort(arr) ; return arr[3]; } /////////////////////////////////////////////////////////////////////////////////// public static String reverse(String input) { StringBuilder str = new StringBuilder("") ; for(int i =input.length()-1 ; i >= 0 ; i-- ) { str.append(input.charAt(i)); } return str.toString() ; } /////////////////////////////////////////////////////////////////////////////////////////// public static boolean sameParity(long a ,long b ) { long x = a% 2L; long y = b%2L ; if(x==y)return true ; else return false ; } //////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean isPossibleTriangle(int a ,int b , int c) { if( a + b > c && c+b > a && a +c > b)return true ; else return false ; } //////////////////////////////////////////////////////////////////////////////////////////// static long xnor(long num1, long num2) { if (num1 < num2) { long temp = num1; num1 = num2; num2 = temp; } num1 = togglebit(num1); return num1 ^ num2; } static long togglebit(long n) { if (n == 0) return 1; long i = n; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return i ^ n; } /////////////////////////////////////////////////////////////////////////////////////////////// public static int xorOfFirstN(int n) { if( n % 4 ==0)return n ; else if( n % 4 == 1)return 1 ; else if( n % 4 == 2)return n+1 ; else return 0 ; } ////////////////////////////////////////////////////////////////////////////////////////////// public static int gcd(int a, int b ) { if(b==0)return a ; else return gcd(b,a%b) ; } public static long gcd(long a, long b ) { if(b==0)return a ; else return gcd(b,a%b) ; } //////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a, int b ,int c , int d ) { int temp = lcm(a,b , c) ; int ans = lcm(temp ,d ) ; return ans ; } /////////////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a, int b ,int c ) { int temp = lcm(a,b) ; int ans = lcm(temp ,c) ; return ans ; } //////////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a , int b ) { int gc = gcd(a,b); return (a*b)/gc ; } public static long lcm(long a , long b ) { long gc = gcd(a,b); return (a*b)/gc ; } /////////////////////////////////////////////////////////////////////////////////////////// static boolean isPrime(long n) { if(n==1) { return false ; } boolean ans = true ; for(long i = 2L; i*i <= n ;i++) { if(n% i ==0) { ans = false ;break ; } } return ans ; } /////////////////////////////////////////////////////////////////////////// static int sieve = 1000000 ; static boolean[] prime = new boolean[sieve + 1] ; public static void sieveOfEratosthenes() { // FALSE == prime // TRUE == COMPOSITE // FALSE== 1 // time complexity = 0(NlogLogN)== o(N) // gives prime nos bw 1 to N for(int i = 4; i<= sieve ; i++) { prime[i] = true ; i++ ; } for(int p = 3; p*p <= sieve; p++) { if(prime[p] == false) { for(int i = p*p; i <= sieve; i += p) prime[i] = true; } p++ ; } } /////////////////////////////////////////////////////////////////////////////////// public static void sortD(int[] arr , int s , int e) { sort(arr ,s , e) ; int i =s ; int j = e ; while( i < j) { int temp = arr[i] ; arr[i] =arr[j] ; arr[j] = temp ; i++ ; j-- ; } return ; } ///////////////////////////////////////////////////////////////////////////////////////// public static long countSubarraysSumToK(long[] arr ,long sum ) { HashMap<Long,Long> map = new HashMap<>() ; int n = arr.length ; long prefixsum = 0 ; long count = 0L ; for(int i = 0; i < n ; i++) { prefixsum = prefixsum + arr[i] ; if(sum == prefixsum)count = count+1 ; if(map.containsKey(prefixsum -sum)) { count = count + map.get(prefixsum -sum) ; } if(map.containsKey(prefixsum )) { map.put(prefixsum , map.get(prefixsum) +1 ); } else{ map.put(prefixsum , 1L ); } } return count ; } /////////////////////////////////////////////////////////////////////////////////////////////// // KMP ALGORITHM : TIME COMPL:O(N+M) // FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING //RETURN THE ARRAYLIST OF INDEXES // IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING public static ArrayList<Integer> kmpAlgorithm(String str , String pat) { ArrayList<Integer> list =new ArrayList<>(); int n = str.length() ; int m = pat.length() ; String q = pat + "#" + str ; int[] lps =new int[n+m+1] ; longestPefixSuffix(lps, q,(n+m+1)) ; for(int i =m+1 ; i < (n+m+1) ; i++ ) { if(lps[i] == m) { list.add(i-2*m) ; } } return list ; } public static void longestPefixSuffix(int[] lps ,String str , int n) { lps[0] = 0 ; for(int i = 1 ; i<= n-1; i++) { int l = lps[i-1] ; while( l > 0 && str.charAt(i) != str.charAt(l)) { l = lps[l-1] ; } if(str.charAt(i) == str.charAt(l)) { l++ ; } lps[i] = l ; } } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n // TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1 // or n and the no will be coprime in nature //time : O(n*(log(logn))) public static void eulerTotientFunction(int[] arr ,int n ) { for(int i = 1; i <= n ;i++)arr[i] =i ; for(int i= 2 ; i<= n ;i++) { if(arr[i] == i) { arr[i] =i-1 ; for(int j =2*i ; j<= n ; j+= i ) { arr[j] = (arr[j]*(i-1))/i ; } } } return ; } ///////////////////////////////////////////////////////////////////////////////////////////// public static long nCr(int n,int k) { long ans=1L; k=k>n-k?n-k:k; int j=1; for(;j<=k;j++,n--) { if(n%j==0) { ans*=n/j; }else if(ans%j==0) { ans=ans/j*n; }else { ans=(ans*n)/j; } } return ans; } /////////////////////////////////////////////////////////////////////////////////////////// public static ArrayList<Integer> allFactors(int n) { ArrayList<Integer> list = new ArrayList<>() ; for(int i = 1; i*i <= n ;i++) { if( n % i == 0) { if(i*i == n) { list.add(i) ; } else{ list.add(i) ; list.add(n/i) ; } } } return list ; } public static ArrayList<Long> allFactors(long n) { ArrayList<Long> list = new ArrayList<>() ; for(long i = 1L; i*i <= n ;i++) { if( n % i == 0) { if(i*i == n) { list.add(i) ; } else{ list.add(i) ; list.add(n/i) ; } } } return list ; } //////////////////////////////////////////////////////////////////////////////////////////////////// static final int MAXN = 10000001; static int spf[] = new int[MAXN]; static void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) spf[i] = i; for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { if (spf[i] == i) { for (int j=i*i; j<MAXN; j+=i) if (spf[j]==j) spf[j] = i; } } } // The above code works well for n upto the order of 10^7. // Beyond this we will face memory issues. // Time Complexity: The precomputation for smallest prime factor is done in O(n log log n) // using sieve. // Where as in the calculation step we are dividing the number every time by // the smallest prime number till it becomes 1. // So, let’s consider a worst case in which every time the SPF is 2 . // Therefore will have log n division steps. // Hence, We can say that our Time Complexity will be O(log n) in worst case. static Vector<Integer> getFactorization(int x) { Vector<Integer> ret = new Vector<>(); while (x != 1) { ret.add(spf[x]); x = x / spf[x]; } return ret; } ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// public static void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; //Copy data to temp arrays for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() public static void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; //Copy data to temp arrays for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } ///////////////////////////////////////////////////////////////////////////////////////// public static long knapsack(int[] weight,long value[],int maxWeight){ int n= value.length ; //dp[i] stores the profit with KnapSack capacity "i" long []dp = new long[maxWeight+1]; //initially profit with 0 to W KnapSack capacity is 0 Arrays.fill(dp, 0); // iterate through all items for(int i=0; i < n; i++) //traverse dp array from right to left for(int j = maxWeight; j >= weight[i]; j--) dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]); /*above line finds out maximum of dp[j](excluding ith element value) and val[i] + dp[j-wt[i]] (including ith element value and the profit with "KnapSack capacity - ith element weight") */ return dp[maxWeight]; } /////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// // to return max sum of any subarray in given array public static long kadanesAlgorithm(long[] arr) { long[] dp = new long[arr.length] ; dp[0] = arr[0] ; long max = dp[0] ; for(int i = 1; i < arr.length ; i++) { if(dp[i-1] > 0) { dp[i] = dp[i-1] + arr[i] ; } else{ dp[i] = arr[i] ; } if(dp[i] > max)max = dp[i] ; } return max ; } ///////////////////////////////////////////////////////////////////////////////////////////// public static long kadanesAlgorithm(int[] arr) { long[] dp = new long[arr.length] ; dp[0] = arr[0] ; long max = dp[0] ; for(int i = 1; i < arr.length ; i++) { if(dp[i-1] > 0) { dp[i] = dp[i-1] + arr[i] ; } else{ dp[i] = arr[i] ; } if(dp[i] > max)max = dp[i] ; } return max ; } /////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// public static long binarySerachGreater(int[] arr , int start , int end , int val) { // fing total no of elements strictly grater than val in sorted array arr if(start > end)return 0 ; //Base case int mid = (start + end)/2 ; if(arr[mid] <=val) { return binarySerachGreater(arr,mid+1, end ,val) ; } else{ return binarySerachGreater(arr,start , mid -1,val) + end-mid+1 ; } } ////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// //TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING // JUST CALL generatePermutation( str, start, end) start :inclusive ,end : exclusive //Function for swapping the characters at position I with character at position j public static String swapString(String a, int i, int j) { char[] b =a.toCharArray(); char ch; ch = b[i]; b[i] = b[j]; b[j] = ch; return String.valueOf(b); } //Function for generating different permutations of the string public static void generatePermutation(String str, int start, int end) { //Prints the permutations if (start == end-1) System.out.println(str); else { for (int i = start; i < end; i++) { //Swapping the string by fixing a character str = swapString(str,start,i); //Recursively calling function generatePermutation() for rest of the characters generatePermutation(str,start+1,end); //Backtracking and swapping the characters again. str = swapString(str,start,i); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// public static long factMod(long n, long mod) { if (n <= 1) return 1; long ans = 1; for (int i = 1; i <= n; i++) { ans = (ans * i) % mod; } return ans; } ///////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// public static long power(long x ,long n) { //time comp : o(logn) if(n==0)return 1L ; if(n==1)return x; long ans =1L ; while(n>0) { if(n % 2 ==1) { ans = ans *x ; } n /= 2 ; x = x*x ; } return ans ; } //////////////////////////////////////////////////////////////////////////////////////////////////// public static long powerMod(long x, long n, long mod) { //time comp : o(logn) if(n==0)return 1L ; if(n==1)return x; long ans = 1; while (n > 0) { if (n % 2 == 1) ans = (ans * x) % mod; x = (x * x) % mod; n /= 2; } return ans; } ////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// /* lowerBound - finds largest element equal or less than value paased upperBound - finds smallest element equal or more than value passed if not present return -1; */ public static long lowerBound(long[] arr,long k) { long ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]<=k) { ans=arr[mid]; start=mid+1; } else { end=mid-1; } } return ans; } public static int lowerBound(int[] arr,int k) { int ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]<=k) { ans=arr[mid]; start=mid+1; } else { end=mid-1; } } return ans; } public static long upperBound(long[] arr,long k) { long ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]>=k) { ans=arr[mid]; end=mid-1; } else { start=mid+1; } } return ans; } public static int upperBound(int[] arr,int k) { int ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]>=k) { ans=arr[mid]; end=mid-1; } else { start=mid+1; } } return ans; } ////////////////////////////////////////////////////////////////////////////////////////// public static void printArray(int[] arr , int si ,int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } } public static void printArrayln(int[] arr , int si ,int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } out.println() ; } public static void printLArray(long[] arr , int si , int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } } public static void printLArrayln(long[] arr , int si , int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } out.println() ; } public static void printtwodArray(int[][] ans) { for(int i = 0; i< ans.length ; i++) { for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +" "); out.println() ; } out.println() ; } static long modPow(long a, long x, long p) { //calculates a^x mod p in logarithmic time. long res = 1; while(x > 0) { if( x % 2 != 0) { res = (res * a) % p; } a = (a * a) % p; x /= 2; } return res; } static long modInverse(long a, long p) { //calculates the modular multiplicative of a mod m. //(assuming p is prime). return modPow(a, p-2, p); } static long modBinomial(long n, long k, long p) { // calculates C(n,k) mod p (assuming p is prime). long numerator = 1; // n * (n-1) * ... * (n-k+1) for (int i=0; i<k; i++) { numerator = (numerator * (n-i) ) % p; } long denominator = 1; // k! for (int i=1; i<=k; i++) { denominator = (denominator * i) % p; } // numerator / denominator mod p. return ( numerator* modInverse(denominator,p) ) % p; } ///////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// static ArrayList<Integer>[] tree ; // static long[] child; // static int mod= 1000000007 ; // static int[][] pre = new int[3001][3001]; // static int[][] suf = new int[3001][3001] ; //program to calculate noof nodes in subtree for every vertex including itself public static void countNoOfNodesInsubtree(int child ,int par , int[] dp) { int count = 1 ; for(int x : tree[child]) { if(x== par)continue ; countNoOfNodesInsubtree(x,child,dp) ; count= count + dp[x] ; } dp[child] = count ; } public static void depth(int child ,int par , int[] dp , int d ) { dp[child] =d ; for(int x : tree[child]) { if(x== par)continue ; depth(x,child,dp,d+1) ; } } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// public static void solve() { FastReader scn = new FastReader() ; //Scanner scn = new Scanner(System.in); //int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ; // product of first 11 prime nos is greater than 10 ^ 12; //ArrayList<Integer> arr[] = new ArrayList[n] ; ArrayList<Integer> list = new ArrayList<>() ; ArrayList<Long> listl = new ArrayList<>() ; ArrayList<Integer> lista = new ArrayList<>() ; ArrayList<Integer> listb = new ArrayList<>() ; //ArrayList<String> lists = new ArrayList<>() ; //HashMap<Integer,Integer> map = new HashMap<>() ; HashMap<Long,Long> map = new HashMap<>() ; HashMap<Integer,Integer> map1 = new HashMap<>() ; HashMap<Integer,Integer> map2 = new HashMap<>() ; //HashMap<String,Integer> maps = new HashMap<>() ; //HashMap<Integer,Boolean> mapb = new HashMap<>() ; //HashMap<Point,Integer> point = new HashMap<>() ; Set<Integer> set = new HashSet<>() ; Set<Integer> setx = new HashSet<>() ; Set<Integer> sety = new HashSet<>() ; StringBuilder sb =new StringBuilder("") ; //Collections.sort(list); //if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ; //else map.put(arr[i],1) ; // if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ; // else map.put(temp,1) ; //int bit =Integer.bitCount(n); // gives total no of set bits in n; // Arrays.sort(arr, new Comparator<Pair>() { // @Override // public int compare(Pair a, Pair b) { // if (a.first != b.first) { // return a.first - b.first; // for increasing order of first // } // return a.second - b.second ; //if first is same then sort on second basis // } // }); int testcase = 1; testcase = scn.nextInt() ; for(int testcases =1 ; testcases <= testcase ;testcases++) { //if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ; //if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ; // int n = scn.nextInt() ; // tree = new ArrayList[n] ; // for(int i = 0; i< n; i++) // { // tree[i] = new ArrayList<Integer>(); // } // for(int i = 0 ; i <= n-2 ; i++) // { // int fv = scn.nextInt()-1 ; int sv = scn.nextInt()-1 ; // tree[fv].add(sv) ; // tree[sv].add(fv) ; // } int n = scn.nextInt() ;int q = scn.nextInt() ; long[] arr = new long[n] ; for(int i = 0 ;i < n ;i++) {arr[i] = scn.nextLong() ; } long[] b = new long[n] ;long[] w = new long[n] ; b[n-1] = arr[n-1] ;w[n-1] = arr[n-1] ; long max = arr[n-1] ; for(int i =n-2; i >= 0 ;i--) { b[i] = Math.max(-1*w[i+1] + arr[i] , Math.max(arr[i] , b[i+1]) ) ; w[i] = Math.min(-1*b[i+1] + arr[i] , Math.min(arr[i] , w[i+1] ) ) ; if(b[i] >max)max =b[i] ; } //printLArrayln(b,0,n-1) ;printLArrayln(w,0,n-1) ; out.println(max) ; sb.delete(0 , sb.length()) ; list.clear() ;listb.clear() ; map.clear() ; map1.clear() ; map2.clear() ; set.clear() ;sety.clear() ; } // test case end loop out.flush() ; } // solve fn ends public static void main (String[] args) throws java.lang.Exception { solve() ; } } class Pair { int first ; int second ; @Override public String toString() { String ans = "" ; ans += this.first ; ans += " "; ans += this.second ; return ans ; } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
2ff81e6acef266b6527cb285d778d2f3
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class P672C1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { solve(in); } } private static void solve(Scanner in) { long res = 0; int n = in.nextInt(); int q = in.nextInt(); int[] a = new int[n + 2]; a[0] = a[n + 1] = 0; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); } for (int i = 1; i <= n; i++) { res = add(a, res, i, 1); } System.out.println(res); for (int i = 0; i < q; i++) { int l = in.nextInt(); int r = in.nextInt(); Set<Integer> set = new HashSet<>(6); for (int j = -1; j <= 1; j++) { if (l + j > 0 && l + j <= n) { set.add(l + j); } if (r + j > 0 && r + j <= n) { set.add(r + j); } } for (Integer p : set) { res = add(a, res, p, -1); } int t = a[l]; a[l] = a[r]; a[r] = t; for (Integer p : set) { res = add(a, res, p, 1); } System.out.println(res); } } private static long add(int[] a, long res, int idx, long x) { x *= a[idx]; if (a[idx] > a[idx - 1] && a[idx] > a[idx + 1]) { res += x; } if (a[idx] < a[idx - 1] && a[idx] < a[idx + 1]) { res -= x; } return res; } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
1d1c19d8786ca4e86f4547320d218fb0
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<27).start(); } static class Pair{ int nod; int ucn; Pair(int nod,int ucn){ this.nod=nod; this.ucn=ucn; } public static Comparator<Pair> wc = new Comparator<Pair>(){ public int compare(Pair e1,Pair e2){ //reverse order if(e1.ucn < e2.ucn) return 1; // 1 for swaping. else if (e1.ucn > e2.ucn) return -1; else{ // if(e1.siz>e2.siz) // return 1; // else // return -1; return 0; } } }; } public static long gcd(long a,long b){ if(b==0)return a; else return gcd(b,a%b); } ////recursive BFS public static int bfsr(int s,ArrayList<Integer>[] a,boolean[] b,int[] pre){ b[s]=true; int p = 1; int n = pre.length -1; int t = a[s].size(); int max = 1; for(int i=0;i<t;i++){ int x = a[s].get(i); if(!b[x]){ //dist[x] = dist[s] + 1; int xz = (bfsr(x,a,b,pre)); p+=xz; max = Math.max(xz,max); } } max = Math.max(max,(n-p)); pre[s] = max; return p; } //// iterative BFS public static int bfs(int s,ArrayList<Integer>[] a,int[] dist,boolean[] b,PrintWriter w){ b[s]=true; int siz = 0; Queue<Integer> q = new LinkedList<>(); q.add(s); while(q.size()!=0){ int i=q.poll(); Iterator<Integer> it = a[i].listIterator(); int z=0; while(it.hasNext()){ z=it.next(); if(!b[z]){ b[z]=true; dist[z] = dist[i] + 1; siz++; q.add(z); } } } return siz; } public static int lower(int key, int[] a){ int l = 0; int r = a.length-1; int res = 0; while(l<=r){ int mid = (l+r)/2; if(a[mid]<=key){ l = mid+1; res = mid+1; } else{ r = mid -1; } } return res; } ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int defaultValue=0; int tc = sc.nextInt(); while(tc-->0){ int n = sc.nextInt(); int q = sc.nextInt(); int[] a = new int[n]; int x = 0; long ans = 0; for(int i=0;i<n;i++){ a[i] = sc.nextInt(); } for(int i=0;i<n;i++){ if(x==0){ if((i==n-1 || a[i]>a[i+1]) || i==n-1){ ans+= a[i]; x = (x+1)%2; } } else{ if((i<n-1 && a[i]<a[i+1])){ ans-= a[i]; x = (x+1)%2; } } //w.println("*"+ans); } w.println(ans); } w.flush(); w.close(); } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
072560ff30e04fefeb8ea3042c9d99bd
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.*; import java.io.*; public class MyClass { static PrintWriter w; public static void main(String args[]) { Scanner sc = new Scanner(System.in); w=new PrintWriter(System.out); int test=Integer.parseInt(sc.nextLine()); A: while(test-->0){ int n=sc.nextInt(); int q=sc.nextInt(); int[] in = new int[n]; ArrayList<Integer> ar =new ArrayList<>(); for(int i=0; i<n; i++){ in[i] = sc.nextInt(); } if(n==1){ w.println(in[0]); continue A; } boolean flag=true; if(in[0]>in[1]){ ar.add(in[0]); flag=false; } for(int i=1; i<n-1; i++){ if(flag){ if(in[i]>in[i-1] && in[i]>in[i+1]){ ar.add(in[i]); flag=false; } }else{ if(in[i]<in[i-1] && in[i]<in[i+1]){ ar.add(in[i]); flag=true; } } } if(flag){ ar.add(in[n-1]); } long ans=0; for(int i=0; i<ar.size(); i+=2){ if(i+1<ar.size()) ans+=ar.get(i)-ar.get(i+1); else ans+=ar.get(i); } w.println(ans); } w.flush(); w.close(); } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
adf1c7d6da88759d9681b0ed1320e27e
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
// package programs; import java.util.*; import static java.lang.System.out; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class Main { static final long mod = (int)1e9+7; static final long M = (int)1e9+7; static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String next() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } int[] readArray(int n) throws IOException { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static int digitSum(int n) { int sum =0; while(n > 0) { int last = n%10; sum+=last; n/=10; } return sum; } public static boolean isPrime(int n) { for(int i = 2;i*i<=n;i++) { if(n%i == 0) { return false; } } return true; } public static int gcd(int a, int b) { if(b == 0) return a; else return gcd(b,a%b); } public static int traverser(int nums[], int n, int k) { int product = 1; if (nums[n - 1] == 0 && k % 2 != 0) return 0; if (nums[n - 1] <= 0 && k % 2 != 0) { for (int i = n - 1; i >= n - k; i--) product *= nums[i]; return product; } int i = 0; int j = n - 1; if (k % 2 != 0) { product *= nums[j]; j--; k--; } k >>= 1; for (int l = 0; l < k; l++) { int left_product = nums[i] * nums[i + 1]; int right_product = nums[j] * nums[j - 1]; if (left_product > right_product) { product *= left_product; i += 2; } else { product *= right_product; j -= 2; } } return product; } public static int[] computePrefix(int arr[], int n) { int[] prefix = new int[n]; prefix[0] = arr[0]; for(int i = 1;i<n;i++) { prefix[i] = prefix[i-1]+arr[i]; } return prefix; } public static int lcm(int a, int b) { return (a*b)/gcd(a,b); } public static int phi(int n) { int result = 1; for (int i = 2; i < n; i++) if (gcd(i, n) == 1) result++; return result; } public static void main(String[] args) throws IOException { Reader sc=new Reader(); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); int[] a = sc.readArray(n); long res = a[0]; for(int i = 1;i<n;i++) { res += Math.max(0, a[i]-a[i-1]); } System.out.println(res); } } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
b34932c2272805994ede516e878f5367
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.*; public class Main { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int q=0;q<t;q++) { int n=sc.nextInt(); int k=sc.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); } int flip=0; long ans=0; for(int i=0;i<n-1;i++) { if(arr[i]>arr[i+1] && flip==0) { ans+=arr[i]; flip=1; } else if(arr[i]<arr[i+1] && flip==1) { ans-=arr[i]; flip=0; } } if(flip==0) { ans+=arr[n-1]; } System.out.println(ans); } } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
465f922150480710acd78b835d25ee35
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.*; public class solution1 { public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); for(int tt=0;tt<t;tt++) { int n=s.nextInt(); int q=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } long ans=a[0]; for(int i=1;i<n;i++) { ans=ans+Math.max(0,(a[i]-a[i-1])); } System.out.println(ans); } s.close(); } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
9a8a09b44401c2351faf06c1bb84ec82
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { Reader scn = new Reader(); int t = scn.nextInt(); StringBuilder res = new StringBuilder(); while (t-- > 0) { int n = scn.nextInt(); int q = scn.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = scn.nextInt(); long[][] dp = new long[n + 1][2]; // for (long[] d : dp) // Arrays.fill(d, -1); res.append(maxSum_dp(arr, 0, 1, dp) + "\n"); } System.out.print(res); } // public static long maxSum(int[] arr, int idx, int prevM, long[][] dp) { // int i = prevM; // if (i < 0) // i = 0; // if (idx == arr.length) // return dp[idx][i] = 0; // if (dp[idx][i] != -1) // return dp[idx][i]; // return dp[idx][i] = Math.max(prevM * arr[idx] + maxSum(arr, idx + 1, prevM * -1, dp), // maxSum(arr, idx + 1, prevM, dp)); // } public static long maxSum_dp(int[] arr, int idx, int prevM, long[][] dp) { int N = arr.length; for (idx = N; idx >= 0; idx--) { for (prevM = 1; prevM >= 0; prevM--) { if (idx == arr.length) { dp[idx][prevM] = 0; continue; } if(prevM == 1){ dp[idx][prevM] = Math.max(arr[idx] + dp[idx + 1][0], dp[idx + 1][1]); }else{ dp[idx][prevM] = Math.max(-arr[idx] + dp[idx + 1][1] , dp[idx + 1][0]); } } } return Math.max(dp[0][0], dp[0][1]); } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
0b50c285887832c62a704121ad73ff5c
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.Scanner; public class dp { public static void main(String args[]) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while (t-- > 0) { int n = scn.nextInt(); int q = scn.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = scn.nextInt(); } long odd = 0; long even = 0; for (int i = 0; i < n; i++) { even = Math.max(even, odd - arr[i]); odd = Math.max(odd, even + arr[i]); } System.out.println(Math.max(even, odd)); } } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
63cdfaf8fd2a17377c0cedb4b725ee77
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.*; public class sex { public static void main (String args[]){ Scanner s = new Scanner(System.in); int T = s.nextInt(); for(int ii=0;ii<T;ii++){ int n = s.nextInt(); int q=s.nextInt(); int [] a = new int [n]; for(int j=0;j<n;j++){ a[j]=s.nextInt(); } // int [] str = new int[n]; // System.out.println(Arrays.toString(a)); long maxj=a[0]; for(int i=1;i<n;i++){ maxj+=Math.max(a[i]-a[i-1],0); } System.out.println(maxj); } } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output
PASSED
d8dd671147ae580ccccadd1e850b469e
train_002.jsonl
1600958100
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 &lt; b_2 &lt; \dots &lt; b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!
256 megabytes
import java.util.*; public class MAIN1 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int q=sc.nextInt(); int[] a=new int[n+2]; boolean ans=false; for(int i=1;i<=n;i++) { a[i]=sc.nextInt(); } a[n+1]=0; a[0]=0; int[] b=new int[q]; int[] c=new int[q]; for(int i=0;i<q;i++) { b[i]=sc.nextInt(); c[i]=sc.nextInt(); } System.out.println(maxSub(a,n)); for(int i=0;i<q;i++) { int p=a[c[i]]; a[c[i]]=a[b[i]]; a[b[i]]=p; a[n]=a[n-2]; System.out.println(maxSub(a,n)); } } } public static long maxSub(int[] a,int n) { long sum=0,max1=0; ArrayList<Integer> al=new ArrayList<>(); int flag=0; for(int i=1;i<=n;i++) { if(flag==0) { if(a[i]>a[i-1]&&a[i]>a[i+1]) { al.add(a[i]); flag=1; } } else if(flag==1) { if(a[i]<a[i+1]&&a[i]<a[i-1]) { al.add(a[i]); flag=0; } } } if(al.size()%2!=0) { al.add(0); } for(int i=0;i<al.size();i+=2) { max1=al.get(i)-al.get(i+1); sum+=max1; } return sum; } }
Java
["3\n3 0\n1 3 2\n2 0\n1 2\n7 0\n1 2 5 4 3 6 7"]
2 seconds
["3\n2\n9"]
NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.
Java 11
standard input
[ "dp", "constructive algorithms", "greedy" ]
2d088e622863ab0d966862ec29588db1
Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
1,300
For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.
standard output