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
sequencelengths
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
82eaa2e74d465ce80e9d41d063d0a838
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.io.*; import java.util.*; public class noob{ InputReader in; final long mod=1000000007; StringBuilder sb; public static void main(String[] args) throws java.lang.Exception{ new noob().run(); } void run() throws Exception { in=new InputReader(System.in); sb = new StringBuilder(); int t=i(); while(t-->0) solve(); System.out.print(sb); } ArrayList<Integer> adj[]; int cnt[],a[],h[],a1[],a2[];//a1->happy, a2->sad int z; void dfs(int u,int v) { cnt[u]=a[u]; for(Integer i : adj[u]) { if(i==v) continue; dfs(i,u); cnt[u]+=cnt[i]; } } void dfs1(int u,int v) { int x=(cnt[u]+h[u]); int y=(cnt[u]-h[u]); if(x%2==1 || y%2==1 || x<0 || y<0) z=-1; a2[u]=x/2; for(Integer i : adj[u]) { if(i==v) continue; dfs1(i,u); a1[u]+=a2[i]; } if(a1[u]>a2[u]) z=-1; } void solve() { int i,j; int n=i(),m=i(); a=new int[n+1]; h=new int[n+1]; a1=new int[n+1]; a2=new int[n+1]; for(i=1;i<=n;i++) a[i]=i(); for(i=1;i<=n;i++) h[i]=i(); adj=new ArrayList[n+1]; for(i=0;i<=n;i++) adj[i]=new ArrayList<>(); for(i=1;i<n;i++) { int x=i(),y=i(); adj[x].add(y); adj[y].add(x); } z=0; cnt=new int[n+1]; dfs(1,0); dfs1(1,0); /*for(i=1;i<=n;i++) System.out.print(a1[i]+" "); System.out.println();*/ if(z==0) System.out.println("YES"); else System.out.println("NO"); } long power(long x, long y, long p) { long res = 1; x = x % p; if (x == 0) return 0; while (y > 0) { if((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res%p; } int gcd(int a, int b) { return (b==0)?a:gcd(b,a%b); } String s(){return in.next();} int i(){return in.nextInt();} long l(){return in.nextLong();} class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public void skip(int x) { while (x-->0) read(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextString() { return next(); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } 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 boolean hasNext() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value != -1; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
c15d8aafe9c562cd16da0037c21c2523
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.util.Scanner; import java.util.ArrayList; public class Sample { public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); for(int i = 0; i < t; ++i) { int n = input.nextInt(); int m = input.nextInt(); int population[] = new int[n]; for(int j = 0; j < n; ++j) { population[j] = input.nextInt(); } int happiness[] = new int[n]; for(int j = 0; j < n; ++j) { happiness[j] = input.nextInt(); } ArrayList<ArrayList<Integer>> neighbours = new ArrayList<ArrayList<Integer>>(); for(int j = 0; j < n; ++j) { neighbours.add(new ArrayList<Integer>()); } for(int j = 0; j < n-1; ++j) { int a = input.nextInt(); int b = input.nextInt(); neighbours.get(a-1).add(b-1); neighbours.get(b-1).add(a-1); } int[] total_people = new int[n]; int printed = 0; int[] good = new int[n]; int[] bad = new int[n]; func(0, -1, neighbours, total_people, population); for(int j = 0; j < n; ++j) { if((happiness[j] + total_people[j]) % 2 != 0) { System.out.println("NO"); printed = 1; break; } else { good[j] = (happiness[j] + total_people[j])/2; bad[j] = (total_people[j] - happiness[j])/2; if(good[j] < 0 || bad[j] < 0) { System.out.println("NO"); printed = 1; break; } } } if(printed == 0) { for(int j = 0; j < n; ++j) { int val = 0; ArrayList<Integer> _neighbours = neighbours.get(j); int len = _neighbours.size(); for(int k = 0; k < len; ++k) { val += good[_neighbours.get(k)]; } if(val > good[j]) { System.out.println("NO"); printed = 1; break; } } if(printed == 0) { System.out.println("YES"); } } } input.close(); } public static void func(int current, int parent, ArrayList<ArrayList<Integer>> neighbours, int[] total_people, int[] population) { ArrayList<Integer> _neighbours = neighbours.get(current); ArrayList<Integer> new_neighbours = new ArrayList<Integer>(); int val = population[current]; int len = _neighbours.size(); for(int j = 0; j < len; ++j) { if(_neighbours.get(j) != parent) { new_neighbours.add(_neighbours.get(j)); func(_neighbours.get(j), current, neighbours, total_people, population); val += total_people[_neighbours.get(j)]; } } neighbours.set(current, new_neighbours); total_people[current] = val; } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
04d38b37c65ba6161eed7fe56f637247
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.io.*; import java.sql.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class c { public static void print(String str,long 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(Object[] 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++){ int n = s.nextInt(); int m = s.nextInt(); int[] population = new int[n]; for(int i=0;i<n;i++){ population[i] = s.nextInt(); } int[] h = new int[n]; for(int i=0;i<n;i++){ h[i] = s.nextInt(); } ArrayList<Integer>[] tree = new ArrayList[n]; for(int i=0;i<n;i++){ tree[i] = new ArrayList<>(); } for(int i=0;i<(n-1);i++){ int u = s.nextInt()-1; int v = s.nextInt()-1; tree[u].add(v); tree[v].add(u); } System.out.println(solve(n,m,population,h,tree)); } } static String solve(int n,int m,int[] p,int [] h,ArrayList<Integer>[] tree){ int[][] subsize = new int[n][3]; boolean b = dfs(0,-1,subsize,tree,p,h); // debug(subsize); if(b){ return "YES"; } else { return "NO"; } } static boolean dfs(int curr,int par,int[][] subtreesize,ArrayList<Integer>[] tree,int[] p,int[] h){ if(tree[curr].size()==1 && tree[curr].get(0)==par){ subtreesize[curr][0] = p[curr]; if((p[curr]-h[curr])%2==0){ int good = (p[curr]+h[curr])/2; int bad = (p[curr]-h[curr])/2; if(good<0 || bad<0){ return false; } // print(good+" "+bad,curr); subtreesize[curr][1] = good; subtreesize[curr][2] = bad; } else { return false; } return true; } else { // print("vertex",curr); int good_from_child =0; int bad_from_child =0; for(int child:tree[curr]){ if(child!=par){ boolean b =dfs(child,curr,subtreesize,tree,p,h); if(!b){ return false; } subtreesize[curr][0]+=subtreesize[child][0]; good_from_child+=subtreesize[child][1]; bad_from_child+=subtreesize[child][2]; } } subtreesize[curr][0] +=p[curr]; int size = subtreesize[curr][0]; // print("subtreesize",size); if(!((size-h[curr])%2==0)){ return false; } int good = (subtreesize[curr][0]+h[curr])/2; int bad = (subtreesize[curr][0]-h[curr])/2; // print("good "+good_from_child,good); // print("bad "+bad_from_child,bad); if(good<0 || bad<0){ return false; } if(good<(good_from_child)){ return false; } subtreesize[curr][1] =good; subtreesize[curr][2] = bad; return true; } } // 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
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
7e9221e5a56437a6114034072c1daacb
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.util.*; import java.io.*; import java.lang.Math; public class C{ static List<Integer>[] adjList; static boolean[] visited; static int[] people; static int[] hIndex; static int[] cp; public static void main(String[] args) throws Exception{ FastScanner fs = new FastScanner(); int t = fs.nextInt(); while(t-->0){ int n = fs.nextInt(), m = fs.nextInt(); people = fs.readArray(n); hIndex = fs.readArray(n); visited = new boolean[n]; adjList = new LinkedList[n]; for(int i=0;i<n;i++) adjList[i] = new LinkedList<Integer>(); for(int i=0;i<n-1;i++){ int x = fs.nextInt(), y = fs.nextInt(); adjList[x-1].add(y-1); adjList[y-1].add(x-1); } cp = new int[n]; System.out.println(dfs(0)?"Yes":"No"); } } static boolean dfs(int node){ visited[node] = true; cp[node] = people[node]; int sumhIndex = 0; for(int a:adjList[node]){ if(!visited[a]){ if(dfs(a)){ cp[node] += cp[a]; sumhIndex += hIndex[a]; } else return false; } } int badPeople = (cp[node]-hIndex[node])/2; if(badPeople<0 || badPeople*2!=(cp[node]-hIndex[node])) return false; int maxHISum; if(people[node]<badPeople){ maxHISum = hIndex[node] + people[node]; } else{ maxHISum = hIndex[node] + 2*badPeople - people[node]; } if(hIndex[node]>cp[node] || hIndex[node]<-cp[node] || sumhIndex>maxHISum){ return false; } return true; } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
1246bf51a717df6e5e40086f4c36ddf9
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.util.*; public class countryMood{ static int n, m; static List<List<Integer>> graph; static long[] pop, moods, commuters, good; static boolean possible = true; public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); while (T-- > 0) { n = in.nextInt(); m = in.nextInt(); pop = new long[n]; for (int i = 0; i < n; i++) pop[i] = in.nextLong(); moods = new long[n]; for (int i = 0; i < n; i++) moods[i] = in.nextLong(); graph = new ArrayList<>(n); for (int i = 0; i < n; i++) graph.add(new ArrayList<>()); for (int i = 0; i < n - 1; i++) { int u = in.nextInt() - 1, v = in.nextInt() - 1; graph.get(u).add(v); graph.get(v).add(u); } commuters = new long[n]; good = new long[n]; check_possib(0, -1); System.out.println(possible ? "YES" : "NO"); possible = true; } in.close(); } static void check_possib(int source, int parent) { long sum_good = 0; for (Integer v: graph.get(source)) { if (v == parent) continue; check_possib(v, source); commuters[source] += commuters[v]; sum_good += good[v]; } commuters[source] += pop[source]; long sum = commuters[source] + moods[source]; good[source] = sum / 2; if (sum < 0 || sum % 2 != 0 || good[source] > commuters[source] || sum_good > good[source]) possible = false; } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
aa0bea417c991d3874e1b73c34aa8192
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.io.*; import java.util.*; /** * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools */ public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { String[] line = br.readLine().split(" "); int n = Integer.parseInt(line[0]), m = Integer.parseInt(line[1]); int[] p = new int[n], h = new int[n]; Node[] graph = new Node[n]; line = br.readLine().split(" "); for (int i = 0; i < n; ++i) { p[i] = Integer.parseInt(line[i]); } line = br.readLine().split(" "); for (int i = 0; i < n; ++i) { h[i] = Integer.parseInt(line[i]); } for (int i = 0; i < n; ++i) { graph[i] = new Node(i, p[i]); } for (int i = 1; i < n; ++i) { line = br.readLine().split(" "); int x = Integer.parseInt(line[0]) - 1, y = Integer.parseInt(line[1]) - 1; graph[x].adj.add(graph[y]); graph[y].adj.add(graph[x]); } boolean valid = true; List<Node> leaves = new ArrayList<>(); dfs1(graph[0], leaves); if (valid) { valid = dfs2(graph[0], h); } bw.write(valid ? "YES" : "NO"); bw.newLine(); } br.close(); bw.close(); } private static class Node { public int index, visited, happy; public List<Node> adj; public Node parent; public Node(int index, int visited) { this.index = index; this.visited = visited; this.happy = 0; this.adj = new ArrayList<>(); this.parent = null; } } private static int dfs1(Node node, List<Node> leaves) { boolean leaf = true; for (Node neighbor: node.adj) { if (neighbor != node.parent) { neighbor.parent = node; node.visited += dfs1(neighbor, leaves); if (leaf) { leaf = false; } } } if (leaf) { leaves.add(node); } return node.visited; } private static boolean dfs2(Node node, int[] h) { int happyDif = node.visited - h[node.index]; if ((happyDif & 1) == 1 || node.visited < Math.abs(h[node.index])) { return false; } node.happy = h[node.index] + (happyDif >> 1); if (node.index != 0) { node.parent.happy -= node.happy; if (node.parent.happy < 0) { return false; } } for (Node neighbor: node.adj) { if (neighbor != node.parent) { neighbor.parent = node; if (!dfs2(neighbor, h)) { return false; } } } return true; } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
3419d3a432b7d1770893a23f955c6928
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import static java.util.Collections.*; import static java.lang.Math.*; @SuppressWarnings("unchecked") public class C_Uncle_Bogdan_and_Country_Happiness { public static PrintWriter out; public static InputReader in; public static long[] p,h; public static boolean ans; public static Graph graph; public static boolean[] vis; static class Graph { public int n; public ArrayList adjacency[]; public Graph(int nodes) { n=nodes; adjacency = new ArrayList[nodes]; for(int i=0;i<nodes;i++) { adjacency[i] = new ArrayList<Integer>(); } } @Override public String toString() { String ret = ""; for (ArrayList temp : adjacency) { ret+=(temp.toString()+"\n"); } return ret; } public void addEdge(int from, int to) { adjacency[from].add(to); adjacency[to].add(from); } } public static long calc(int ix){ ArrayList<Integer> neigh = (ArrayList<Integer>)graph.adjacency[ix]; long peeps = p[ix]; vis[ix] = true; long pos = 0l, neg = 0l; for(int i=0;i<neigh.size();i++){ if(vis[neigh.get(i)]) continue; long neighPeeps = calc(neigh.get(i)); peeps+=neighPeeps; long neighH = h[neigh.get(i)]; if((neighPeeps-neighH)%2!=0) {ans = false; return 0l;} long diff = neighPeeps - neighH; neg+=(diff/2l); pos+=(neighPeeps-(diff/2l)); } long l1 = h[ix]-pos-neg; long r1 = h[ix]-pos+neg; if((peeps-h[ix])%2!=0) ans=false; if(r1<(-1*p[ix]) || l1>p[ix]) { // out.printf("pos = %d, neg = %d\n",pos,neg); // out.printf("l1 = %d, r1 = %d\n",l1,r1); // out.println("ix:"+ix+"ye2"); ans = false; } return peeps; } public static void main(String[] args)throws IOException { in = new InputReader(System.in); out = new PrintWriter(System.out); int cases = in.nextInt(); for(int t = 0; t < cases; t++){ int n = in.nextInt(); int m = in.nextInt(); p = new long[n]; h = new long[n]; graph = new Graph(n); for(int i=0;i<n;i++) p[i] = in.nextLong(); for(int i=0;i<n;i++) h[i] = in.nextLong(); vis = new boolean[n]; Arrays.fill(vis,false); for(int i=0;i<n-1;i++){ int x = in.nextInt()-1; int y = in.nextInt()-1; graph.addEdge(x, y); } ans = true; calc(0); out.println((ans) ? "YES" : "NO"); } out.close(); } 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
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
fe91fd568ccb7ef6842939f649d21a1c
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.math.*; import java.io.*; import java.util.*; import java.awt.*; public class Main implements Runnable { @Override public void run() { try { new Solver().solve(); System.exit(0); } catch (Exception | Error e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) throws Exception { //new Thread(null, new Main(), "Solver", 1l << 25).start(); new Main().run(); } } class Solver { final Helper hp; final int MAXN = 1000_006; final long MOD = (long) 1e9 + 7; final Timer timer; final TimerTask task; Solver() { hp = new Helper(MOD, MAXN); hp.initIO(System.in, System.out); timer = new Timer(); task = new TimerTask() { @Override public void run() { try { hp.flush(); System.exit(0); } catch (Exception e) { } } }; //timer.schedule(task, 4700); } void solve() throws Exception { int tc = TESTCASES ? hp.nextInt() : 1; for (int tce = 1; tce <= tc; ++tce) solve(tce); timer.cancel(); hp.flush(); } boolean TESTCASES = true; int N; long M; ArrayList<Integer>[] graph; long[] C, H; void solve(int tc) throws Exception { int i, j, k; N = hp.nextInt(); M = hp.nextLong(); C = hp.getLongArray(N); H = hp.getLongArray(N); graph = new ArrayList[N]; for (i = 0; i < N; ++i) graph[i] = new ArrayList<>(); for (i = 1; i < N; ++i) { int a = hp.nextInt() - 1, b = hp.nextInt() - 1; graph[a].add(b); graph[b].add(a); } happy = new long[N]; sad = new long[N]; ans = true; dfs(0, -7); hp.println(ans ? "YES" : "NO"); } long[] happy, sad; boolean ans; long dfs(int node, int par) { for (int itr : graph[node]) if (itr != par) { C[node] += dfs(itr, node); } happy[node] = C[node] + H[node] >> 1; sad[node] = C[node] - H[node] >> 1; if (happy[node] + sad[node] != C[node] || happy[node] - sad[node] != H[node] || Math.min(happy[node], sad[node]) < 0 || Math.max(happy[node], sad[node]) > C[node]) { ans = false; } long happies = 0; for (int itr : graph[node]) if (itr != par) { happies += happy[itr]; } if (happies > happy[node]) ans = false; return C[node]; } } class Helper { final long MOD; final int MAXN; final Random rnd; public Helper(long mod, int maxn) { MOD = mod; MAXN = maxn; rnd = new Random(); } public static int[] sieve; public static ArrayList<Integer> primes; public void setSieve() { primes = new ArrayList<>(); sieve = new int[MAXN]; int i, j; for (i = 2; i < MAXN; ++i) if (sieve[i] == 0) { primes.add(i); for (j = i; j < MAXN; j += i) { sieve[j] = i; } } } public static long[] factorial; public void setFactorial() { factorial = new long[MAXN]; factorial[0] = 1; for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD; } public long getFactorial(int n) { if (factorial == null) setFactorial(); return factorial[n]; } public long ncr(int n, int r) { if (r > n) return 0; if (factorial == null) setFactorial(); long numerator = factorial[n]; long denominator = factorial[r] * factorial[n - r] % MOD; return numerator * pow(denominator, MOD - 2, MOD) % MOD; } public long[] getLongArray(int size) throws Exception { long[] ar = new long[size]; for (int i = 0; i < size; ++i) ar[i] = nextLong(); return ar; } public int[] getIntArray(int size) throws Exception { int[] ar = new int[size]; for (int i = 0; i < size; ++i) ar[i] = nextInt(); return ar; } public String[] getStringArray(int size) throws Exception { String[] ar = new String[size]; for (int i = 0; i < size; ++i) ar[i] = next(); return ar; } public String joinElements(long... ar) { StringBuilder sb = new StringBuilder(); for (long itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(int... ar) { StringBuilder sb = new StringBuilder(); for (int itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(String... ar) { StringBuilder sb = new StringBuilder(); for (String itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(Object... ar) { StringBuilder sb = new StringBuilder(); for (Object itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } public int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public long max(long... ar) { long ret = ar[0]; for (long itr : ar) ret = Math.max(ret, itr); return ret; } public int max(int... ar) { int ret = ar[0]; for (int itr : ar) ret = Math.max(ret, itr); return ret; } public long min(long... ar) { long ret = ar[0]; for (long itr : ar) ret = Math.min(ret, itr); return ret; } public int min(int... ar) { int ret = ar[0]; for (int itr : ar) ret = Math.min(ret, itr); return ret; } public long sum(long... ar) { long sum = 0; for (long itr : ar) sum += itr; return sum; } public long sum(int... ar) { long sum = 0; for (int itr : ar) sum += itr; return sum; } public void shuffle(int[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public void shuffle(long[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public void reverse(int[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = ar.length - 1 - i; if (r > i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public void reverse(long[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = ar.length - 1 - i; if (r > i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public long pow(long base, long exp, long MOD) { base %= MOD; long ret = 1; while (exp > 0) { if ((exp & 1) == 1) ret = ret * base % MOD; base = base * base % MOD; exp >>= 1; } return ret; } static final int BUFSIZE = 1 << 20; static byte[] buf; static int index, total; static InputStream in; static BufferedWriter bw; public void initIO(InputStream is, OutputStream os) { try { in = is; bw = new BufferedWriter(new OutputStreamWriter(os)); buf = new byte[BUFSIZE]; } catch (Exception e) { } } public void initIO(String inputFile, String outputFile) { try { in = new FileInputStream(inputFile); bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputFile))); buf = new byte[BUFSIZE]; } catch (Exception e) { } } private int scan() throws Exception { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } public String next() throws Exception { 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(); } public int nextInt() throws Exception { 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; } public long nextLong() throws Exception { 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; } public void print(Object a) throws Exception { bw.write(a.toString()); } public void printsp(Object a) throws Exception { print(a); print(" "); } public void println() throws Exception { bw.write("\n"); } public void println(Object a) throws Exception { print(a); println(); } public void flush() throws Exception { bw.flush(); } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
c1a07a5d6af7e40fd92e7bbe9cc260e3
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.util.*; import java.io.*; public class happiness { 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 m = Integer.parseInt(line.nextToken()); line = new StringTokenizer(in.readLine()); StringTokenizer line2 = new StringTokenizer(in.readLine()); int[] living = new int[n]; int[] happiness = new int[n]; for(int j = 0; j < n; j++) { living[j] = Integer.parseInt(line.nextToken()); happiness[j] = Integer.parseInt(line2.nextToken()); } ArrayList[] tree = new ArrayList[n]; for(int j = 0; j < n; j++) tree[j] = new ArrayList<Integer>(); for(int j = 0; j < n - 1; j++) { line = new StringTokenizer(in.readLine()); int v1 = Integer.parseInt(line.nextToken()) - 1; int v2 = Integer.parseInt(line.nextToken()) - 1; tree[v1].add(v2); tree[v2].add(v1); } int[] subtreesums = new int[n]; boolean possible = dfs1(tree, subtreesums, happiness, new HashSet<Integer>(), 0, living); out.println(possible ? "YES" : "NO"); } in.close(); out.close(); } static boolean dfs1(ArrayList[] tree, int[] subtreesums, int[] happiness, HashSet<Integer> visited, int curnode, int[] living) { visited.add(curnode); ArrayList<Integer> neighbors = tree[curnode]; int curliving = 0; int totalhappy = 0; boolean ret = true; for(int i = 0; i < neighbors.size(); i++) { int curneighbor = neighbors.get(i); if(!visited.contains(curneighbor)) { ret = ret && dfs1(tree, subtreesums, happiness, visited, curneighbor, living); curliving += subtreesums[curneighbor]; int curhappy = happynum(curneighbor, happiness, subtreesums); if(curhappy == -1) return false; totalhappy += curhappy; } } subtreesums[curnode] = curliving + living[curnode]; int parenthappy = happynum(curnode, happiness, subtreesums); if(parenthappy == -1) return false; if(totalhappy > parenthappy) return false; return ret; } //Given how many people pass through this point and its happiness index, how many people are happy and is it possible static int happynum(int node, int[] happiness, int[] subtreesums) { if(happiness[node] <= subtreesums[node] && happiness[node] >= -1 * subtreesums[node] && Math.abs(happiness[node] % 2) == Math.abs(subtreesums[node] % 2)) { return (subtreesums[node] + happiness[node]) / 2; }else { return -1; } } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
6c02160ddcf5454aea5c10506899f703
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.awt.Point; // 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-- ; } } ////////////////////////////////////////////////////////////////////////////////// static long factorial(long a) { if(a== 0L || a==1L)return 1L ; return a*factorial(a-1L) ; } /////////////////////////////////////////////////////////////////////////////// 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 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 boolean isPrime(int n) { if(n==1) { return false ; } boolean ans = true ; for(int i = 2; 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 = 1000001; 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; } } } static ArrayList<Integer> getPrimeFactorization(int x) { ArrayList<Integer> ret = new ArrayList<Integer>(); 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) { if(arr.length == 0)return 0 ; 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) { if(arr.length == 0)return 0 ; 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(int a ,int b) { //time comp : o(logn) long x = (long)(a) ; long n = (long)(b) ; if(n==0)return 1 ; if(n==1)return x; long ans =1L ; while(n>0) { if(n % 2 ==1) { ans = ans *x ; } n = n/2L ; x = x*x ; } return ans ; } public static long power(long a ,long b) { //time comp : o(logn) long x = (a) ; long n = (b) ; if(n==0)return 1L ; if(n==1)return x; long ans =1L ; while(n>0) { if(n % 2 ==1) { ans = ans *x ; } n = n/2L ; 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 p. //(assuming p is prime). return modPow(a, p-2, p); } static long[] factorial = new long[1000001] ; static void modfac(long mod) { factorial[0]=1L ; factorial[1]=1L ; for(int i = 2; i<= 1000000 ;i++) { factorial[i] = factorial[i-1] *(long)(i) ; factorial[i] = factorial[i] % mod ; } } static long modBinomial(long n, long r, long p) { // calculates C(n,r) mod p (assuming p is prime). long num = factorial[(int)(n)] ; long den = (factorial[(int)(r)]*factorial[(int)(n-r)]) % p ; long ans = num*(modInverse(den,998244353L)) ; ans = ans % 998244353L ; return ans ; } static void update(int val , long[] bit ,int n) { for( ; val <= n ; val += (val &(-val)) ) { bit[val]++ ; } } static long query(int val , long[] bit , int n) { long ans = 0L; for( ; val >=1 ; val-=(val&(-val)) )ans += bit[val]; return ans ; } static int countSetBits(long n) { int count = 0; while (n > 0) { n = (n) & (n - 1L); count++; } return count; } static int abs(int x) { if(x < 0)x = -1*x ; return x ; } static long abs(long x) { if(x < 0)x = -1L*x ; return x ; } static int bs(long[] arr , long key , int n, int s , int e) { int ans = 0 ; while( s <= e) { int m = (s+e)/2 ; if(arr[m] <= key) { ans =m ; s=m+1 ; } else{ e=m-1 ; } } return ans ; } ///////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// 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 // static void dfs(int sv) // { // child[sv] = 1L; // for(Integer x : tree[sv]) // { // if(child[x] == 0) // { // dfs(x) ; // child[sv] += child[x] ; // } // } // } static int n ; static int p ; static int[] no ; static int[] h ; static int ans = 1 ; static int[] dp ; static int[] bad ; static int[] good ; static void dfs(int sv , int par) { dp[sv] = no[sv] ; int badC = 0 ; for(int x : tree[sv]) { if(x == par)continue ; dfs(x,sv) ; dp[sv] = dp[sv] + dp[x] ; badC= badC + bad[x] ; } if(dp[sv] < h[sv])ans = 0 ; if(-1*dp[sv] > h[sv])ans = 0 ; if( ( (dp[sv] + h[sv]) & 1) != 0 )ans = 0 ; bad[sv] = (dp[sv] - h[sv])/2 ; good[sv] = (dp[sv] + h[sv])/2 ; if(bad[sv] > no[sv] + badC)ans = 0; } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// 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; //sieve() ; //ArrayList<Integer> arr[] = new ArrayList[n] ; ArrayList<Integer> list = new ArrayList<>() ; ArrayList<Long> lista = new ArrayList<>() ; ArrayList<Long> listb = 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> mapx = new HashMap<>() ; HashMap<Integer,Integer> mapy = 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) ; n = scn.nextInt() ; p = scn.nextInt() ; no = new int[n] ; h = new int[n] ; dp = new int[n] ;good = new int[n] ;bad = new int[n] ; tree = new ArrayList[n] ; for(int i = 0; i< n; i++) { tree[i] = new ArrayList<Integer>(); } for(int i = 0; i < n;i++)no[i] = scn.nextInt() ; for(int i = 0; i < n;i++)h[i] = scn.nextInt() ; for(int i = 1; i<= n-1 ;i++) { int fv = scn.nextInt() ;int sv = scn.nextInt() ; fv-- ;sv-- ; tree[fv].add(sv) ; tree[sv].add(fv) ; } dfs(0,-1); if(ans ==0)out.println("NO"); else out.println("YES"); ans =1; //out.println(ans+" "+in) ; //out.println("Case #" + testcases + ": " + ans ) ; //out.println("@") ; set.clear() ; sb.delete(0 , sb.length()) ; list.clear() ;lista.clear() ;listb.clear() ; map.clear() ; mapx.clear() ; mapy.clear() ; setx.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
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
d2d168257bdcbc3f31e98c1294a18ae4
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.util.*; import java.io.*; public class div { static StringBuilder ans; static int[] pi,hi; static ArrayList<ArrayList<Integer>> g; public static void main(String[] args) throws IOException { ans = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine().trim()); while (t-- > 0) { StringTokenizer tok=new StringTokenizer(br.readLine()," "); int n=Integer.parseInt(tok.nextToken()); int citizen=Integer.parseInt(tok.nextToken()); tok=new StringTokenizer(br.readLine()," "); pi=new int[n+1]; hi=new int[n+1]; g=new ArrayList<>(); g.add(new ArrayList<>()); for(int i=1;i<=n;i++){ g.add(new ArrayList<>()); pi[i]=Integer.parseInt(tok.nextToken()); } tok=new StringTokenizer(br.readLine()," "); for(int i=1;i<=n;i++){ hi[i]=Integer.parseInt(tok.nextToken()); } for(int i=0;i<n-1;i++){ tok=new StringTokenizer(br.readLine()," "); int a=Integer.parseInt(tok.nextToken()); int b=Integer.parseInt(tok.nextToken()); // System.out.println(a+"=="+b); g.get(a).add(b); g.get(b).add(a); } pair a=call(1,-1); if(a.g==-1)ans.append("NO"); else ans.append("YES"); ans.append("\n"); } out.print(ans); out.close(); } static pair call(int curr,int par){ int currtot=pi[curr]; int childg=0; int childb=0; for(Integer child:g.get(curr)){ if(child==par)continue; // System.out.println("enter"); pair ppp=call(child,curr); if(ppp.g==-1)return ppp; childg+=ppp.g; childb+=ppp.b; currtot+=ppp.tot; } int g=0; int b=0; if(hi[curr]>currtot)return new pair(-1,-1,-1); if(hi[curr]<-currtot)return new pair(-1,-1,-1); if((currtot+hi[curr])%2!=0)return new pair(-1,-1,-1); g=(currtot+hi[curr])/2; b=(currtot-hi[curr])/2; // if(curr==1) // System.out.println(childb+" "+b+" "+currtot); if(b>childb+pi[curr]){return new pair(-1,-1,-1);} return new pair(g,b,currtot); } static class pair{ int g,b,tot; pair(int a,int b,int c){ g=a; this.b=b; tot=c; } } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
ae3240ad2215d37776b3685b43b8aed5
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.util.*; import java.io.*; public class div { static StringBuilder ans; static int[] pi,hi; static ArrayList<ArrayList<Integer>> g; public static void main(String[] args) throws IOException { ans = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine().trim()); while (t-- > 0) { StringTokenizer tok=new StringTokenizer(br.readLine()," "); int n=Integer.parseInt(tok.nextToken()); int citizen=Integer.parseInt(tok.nextToken()); tok=new StringTokenizer(br.readLine()," "); pi=new int[n+1]; hi=new int[n+1]; g=new ArrayList<>(); g.add(new ArrayList<>()); for(int i=1;i<=n;i++){ g.add(new ArrayList<>()); pi[i]=Integer.parseInt(tok.nextToken()); } tok=new StringTokenizer(br.readLine()," "); for(int i=1;i<=n;i++){ hi[i]=Integer.parseInt(tok.nextToken()); } for(int i=0;i<n-1;i++){ tok=new StringTokenizer(br.readLine()," "); int a=Integer.parseInt(tok.nextToken()); int b=Integer.parseInt(tok.nextToken()); // System.out.println(a+"=="+b); g.get(a).add(b); g.get(b).add(a); } pair a=call(1,-1); if(a.g==-1)ans.append("NO"); else ans.append("YES"); ans.append("\n"); } out.print(ans); out.close(); } static pair call(int curr,int par){ int currtot=pi[curr]; int childg=0; int childb=0; for(Integer child:g.get(curr)){ if(child==par)continue; // System.out.println("enter"); pair ppp=call(child,curr); if(ppp.g==-1)return ppp; childg+=ppp.g; childb+=ppp.b; currtot+=ppp.tot; } int g=0; int b=0; if(hi[curr]>currtot)return new pair(-1,-1,-1); if(hi[curr]<-currtot)return new pair(-1,-1,-1); if((currtot+hi[curr])%2!=0)return new pair(-1,-1,-1); g=(currtot+hi[curr])/2; b=(currtot-hi[curr])/2; // if(curr==1) // System.out.println(childb+" "+b+" "+currtot); if(g<childg)return new pair(-1,-1,-1); return new pair(g,b,currtot); } static class pair{ int g,b,tot; pair(int a,int b,int c){ g=a; this.b=b; tot=c; } } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
766511e1ba3fa6d8b9ff09f2b1200105
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.io.*; import java.util.*; public class CF1388C extends PrintWriter { CF1388C() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1388C o = new CF1388C(); o.main(); o.flush(); } int[] oo; int[][] oj; void link(int i, int j) { int o = oo[i]; if (o >= 2 && (o & o - 1) == 0) oj[i] = Arrays.copyOf(oj[i], o << 1); oj[i][oo[i]++] = j; } int[] aa, bb; void init(int n) { oo = new int[n]; oj = new int[n][2]; aa = new int[n]; bb = new int[n]; } boolean dfs(int p, int i) { int a = 0, b = 0; for (int o = 0; o < oo[i]; o++) { int j = oj[i][o]; if (j != p) { if (!dfs(i, j)) return false; a += aa[j]; b += bb[j]; } } if (bb[i] < b - aa[i] || bb[i] > a + aa[i]) return false; aa[i] += a; if ((aa[i] + bb[i]) % 2 != 0) return false; return true; } void main() { int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); init(n); for (int i = 0; i < n; i++) aa[i] = sc.nextInt(); for (int i = 0; i < n; i++) bb[i] = sc.nextInt(); for (int h = 0; h < n - 1; h++) { int i = sc.nextInt() - 1; int j = sc.nextInt() - 1; link(i, j); link(j, i); } println(dfs(-1, 0) ? "YES" : "NO"); } } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
9155499643770def78f3d00733490f9e
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.io.*; import java.util.ArrayDeque; import java.util.Arrays; import java.util.StringJoiner; import java.util.StringTokenizer; public class MainC { public static void main(String[] args) { var sc = new FastScanner(System.in); var pw = new PrintWriter(System.out); var T = sc.nextInt(); for (int t = 0; t < T; t++) { var N = sc.nextInt(); var M = sc.nextInt(); var P = sc.nextIntArray(N); var H = sc.nextIntArray(N); int[] A = new int[N-1]; int[] B = new int[N-1]; for (int i = 0; i < N - 1; i++) { A[i] = sc.nextInt()-1; B[i] = sc.nextInt()-1; } pw.println( solve(N, M, P, H, A, B) ? "YES" : "NO" ); } pw.flush(); } private static boolean solve(int N, int M, int[] P, int[] H, int[] A, int[] B) { int[][] G = adjB(N, A, B); int[] W = new int[N]; int[] L = new int[N]; for (Node node : orderFromLeaf(N, G, 0)) { int uw = 0; int ul = 0; for (int b : G[node.a]) { if( b == node.parent ) continue; uw += W[b]; ul += L[b]; } // W - L = H // W + L = T int t = uw + ul + P[node.a]; int h = H[node.a]; if( Math.abs((h + t))%2 == 1 ) return false; int w = (h+t)/2; int l = t - w; // debug(node.a, t, h, w, l); if( w < 0 || l < 0 ) return false; if( uw > w ) return false; W[node.a] = w; L[node.a] = l; } return true; } static Node[] orderFromLeaf(int N, int[][] G, int root) { ArrayDeque<Node> q = new ArrayDeque<>(); Node[] ret = new Node[N]; int idx = N-1; q.add(new Node(-1, root)); while(!q.isEmpty()) { Node n = q.poll(); ret[idx--] = n; for (int next : G[n.a]) { if( next == n.parent ) continue; q.add(new Node(n.a, next)); } } return ret; } static class Node { int parent, a; public Node(int parent, int a) { this.parent = parent; this.a = a; } } static class Edge { final int a, b; public Edge(int a, int b) { this.a = a; this.b = b; } int opposite(int x) { return a == x ? b : a; } } static int[][] adjB(int n, int[] from, int[] to) { int[][] adj = new int[n][]; int[] cnt = new int[n]; for (int f : from) { cnt[f]++; } for (int t : to) { cnt[t]++; } for (int i = 0; i < n; i++) { adj[i] = new int[cnt[i]]; } for (int i = 0; i < from.length; i++) { adj[from[i]][--cnt[from[i]]] = to[i]; adj[to[i]][--cnt[to[i]]] = from[i]; } return adj; } @SuppressWarnings("unused") static class FastScanner { private final BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { var a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { var a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { var a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static void writeLines(int[] as) { var pw = new PrintWriter(System.out); for (var a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { var pw = new PrintWriter(System.out); for (var a : as) pw.println(a); pw.flush(); } static void writeSingleLine(int[] as) { var pw = new PrintWriter(System.out); for (var i = 0; i < as.length; i++) { if (i != 0) pw.print(" "); pw.print(as[i]); } pw.println(); pw.flush(); } static void debug(Object... args) { var j = new StringJoiner(" "); for (var arg : args) { if (arg == null) j.add("null"); else if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j.toString()); } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
5bbd2eb7d8a9ad526ff404887e3f9a19
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.util.*; import java.io.*; public class C { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int nTest = scanner.nextInt(); for(int iTest = 1; iTest <= nTest; iTest++) { int n = scanner.nextInt(); int m = scanner.nextInt(); int[] a = new int[n + 1]; for(int i = 1; i <= n; i++) { a[i] = scanner.nextInt(); } int[] b = new int[n + 1]; for(int i = 1; i <= n; i++) { b[i] = scanner.nextInt(); } List_Int[] adj = new List_Int[n + 1]; for(int i = 1; i <= n; i++) { adj[i] = new List_Int(); } for(int i = 1; i <= n - 1; i++) { int x = scanner.nextInt(); int y = scanner.nextInt(); adj[x].add(y); adj[y].add(x); } boolean[] used = new boolean[n + 1]; int[] cnt = new int[n + 1]; if(recursiveCheck(1, a, b, adj, used, cnt)) { System.out.println("YES"); } else { System.out.println("NO"); } } } private static boolean recursiveCheck(int x, int[] a, int[] b, List_Int[] adj, boolean[] used, int[] cnt) { used[x] = true; cnt[x] = a[x]; int sum = 0; for(int y : adj[x]) { if(!used[y]) { if(!recursiveCheck(y, a, b, adj, used, cnt)) { return false; } cnt[x] += cnt[y]; sum += cnt[y] + b[y]; } } return (cnt[x] + b[x]) % 2 == 0 && cnt[x] - b[x] >= 0 && cnt[x] + b[x] >= sum; } } class List_Int extends ArrayList<Integer> {}
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
fd672ea754eb97854c2dff6779b6ff3c
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.util.*; import java.io.*; import java.lang.Math; public class C { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int nTest = scanner.nextInt(); for(int iTest = 1; iTest <= nTest; iTest++) { int n = scanner.nextInt(); int m = scanner.nextInt(); int[] a = new int[n + 1]; for(int i = 1; i <= n; i++) { a[i] = scanner.nextInt(); } int[] b = new int[n + 1]; for(int i = 1; i <= n; i++) { b[i] = scanner.nextInt(); } List_Int[] adj = new List_Int[n + 1]; for(int i = 1; i <= n; i++) { adj[i] = new List_Int(); } for(int i = 1; i <= n - 1; i++) { int x = scanner.nextInt(); int y = scanner.nextInt(); adj[x].add(y); adj[y].add(x); } boolean[] used = new boolean[n + 1]; int[] cnt = new int[n + 1]; if(recursiveCheck(1, a, b, adj, used, cnt)) { System.out.println("YES"); } else { System.out.println("NO"); } } } private static boolean recursiveCheck(int x, int[] a, int[] b, List_Int[] adj, boolean[] used, int[] cnt) { used[x] = true; cnt[x] = a[x]; int sum = 0; for(int y : adj[x]) { if(!used[y]) { if(!recursiveCheck(y, a, b, adj, used, cnt)) { return false; } cnt[x] += cnt[y]; sum += cnt[y] + b[y]; } } return (cnt[x] + b[x]) % 2 == 0 && Math.abs(b[x]) <= cnt[x] && cnt[x] + b[x] >= sum; } } class List_Int extends ArrayList<Integer> {}
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
9e142a8b4d9ca97f72a6f9b57a06087f
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.util.*; import java.io.*; public class e{ static int flag=0; static void dfs_visited(int curr,int[] v,int[] good,int[] h,int[] population,int[] total,int[] parent, ArrayList<ArrayList<Integer>> graph){ int good_people=0; int total_visited=population[curr]; for (int i=0;i<graph.get(curr).size();i++){ int child=graph.get(curr).get(i); if(child!=parent[curr]){ parent[child]=curr; dfs_visited(child,v,good,h,population,total,parent,graph); good_people+=good[child]; total_visited+=total[child]; } } int gd=0; total[curr]=total_visited; good[curr]=(h[curr]+total[curr])/2; // System.out.println(good[curr]+" "); gd=good[curr]; if((h[curr]+total[curr])%2!=0){ flag=1; } else{ if(gd<0 || gd>total_visited || gd<good_people){ flag=1; } } // System.out.println("f"+flag); } public static void main(String[] args) throws IOException { FastScanner f = new FastScanner(); int t = f.nextInt(); // int t=1; int count=0; while(t-->0){ count+=1; int n = f.nextInt(); int m = f.nextInt(); int[] population=f.readArray(n); int[] h=f.readArray(n); int[] v=new int[n]; int[] parent=new int[n]; int[] total=new int[n]; int[] good=new int[n]; ArrayList<ArrayList<Integer>> graph=new ArrayList<>(); for(int i=0;i<n;i++){ graph.add(new ArrayList<Integer>()); } int a=0,b=0; for(int i=0;i<n-1;i++){ a=f.nextInt(); b=f.nextInt(); a--; b--; graph.get(a).add(b); graph.get(b).add(a); } parent[0]=-1; // int flag=0; dfs_visited(0,v,good,h,population,total,parent,graph); // for(int i=0;i<n;i++){ // System.out.print(total[i]+" ");} // System.out.println(); // for(int i=0;i<n;i++){ // System.out.print(good[i]+" ");} // System.out.println(); if(flag==1){ System.out.println("NO"); } else{ System.out.println("YES"); } flag=0; } } 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
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
31d0f3273f909e0fc5c690c315079b49
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.util.*; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; public class Solution { static ArrayList<Integer> tree[]; static int live[],happy[],pass[],h[],s[],f; static int dfs(int u, int p){ int count=0; for(int v:tree[u]){ if(v!=p){ count+=dfs(v,u); } } pass[u]=count+live[u]; return pass[u]; } static int dfs1(int u,int p){ int count=0; for(int v:tree[u]){ if(v!=p){ count+=dfs1(v,u); } } if(count>h[u]) f=1; return h[u]; } public static void main(String[] args) throws IOException { int i, j; FastReader in = new FastReader(System.in); StringBuilder sb = new StringBuilder(); boolean testcases = true; int t = testcases ? in.nextInt() : 1; int to = 0; while (to++ < t) { int n=in.nextInt(); int m=in.nextInt(); tree=new ArrayList[n]; live=new int[n]; happy=new int[n]; pass=new int[n]; h=new int[n]; s=new int[n]; for(i=0;i<n;i++){ live[i]=in.nextInt(); } for(i=0;i<n;i++){ happy[i]=in.nextInt(); tree[i]=new ArrayList<>(); } for(i=0;i<n-1;i++){ int x=in.nextInt()-1; int y=in.nextInt()-1; tree[x].add(y); tree[y].add(x); } dfs(0,-1); f=0; for(i=0;i<n;i++){ int x=pass[i]+happy[i]; if(x%2!=0 || x<0 || (pass[i]-x/2)<0){ f=1; break; } h[i]=x; s[i]=pass[i]-x/2; } if(f==1){ sb.append("NO\n"); } else{ dfs1(0,-1); if(f==0) sb.append("YES\n"); else sb.append("NO\n"); } } System.out.print(sb); } } 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(); } 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
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
87eaee35cf12c70e613c97fb0d4f5cf7
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$nβˆ’1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.util.ArrayList; import java.util.Scanner; /* problem: C * author: ShifaYang * date: 2020-08-03 06:03:46 * solve: */ public class Main { static Scanner sc = new Scanner(System.in); static final int N = (int) 2e5 + 10; static class Node { ArrayList<Integer> sons = new ArrayList<Integer>(); int num; // 住在θ―₯θŠ‚η‚Ήηš„δΊΊζ•° int tnum; // δ»₯θ―₯θŠ‚η‚ΉδΈΊζ Ήηš„ε­ζ ‘ηš„ζ€»δΊΊζ•° int good; // δ»₯θ―₯θŠ‚η‚ΉδΈΊζ Ήηš„ε­ζ ‘ηš„εΏƒζƒ…ε₯½ηš„δΊΊζ•° int bad; // δ»₯θ―₯θŠ‚η‚ΉδΈΊζ Ήηš„ε­ζ ‘ηš„εΏƒζƒ…δΈε₯½ηš„δΊΊζ•° int dected; // ζ£€ζ΅‹ε‡Ίηš„good-badδΊΊζ•° public String toString() { return "num:" + num + ",good:" + good + ",bad:" + bad + "dected:" + dected; } } static Node tree[] = new Node[N]; static boolean dfs(int idx, int fa) { int sgood = 0; int sbad = 0; int stnum = 0; ArrayList<Integer> sons = tree[idx].sons; for (int son : sons) { if (son == fa) continue; if (!dfs(son, idx)) return false; stnum += tree[son].tnum; sbad += tree[son].bad; sgood += tree[son].good; } tree[idx].tnum += tree[idx].num + stnum; tree[idx].good = (tree[idx].tnum + tree[idx].dected) / 2; tree[idx].bad = tree[idx].tnum - tree[idx].good; if (tree[idx].good - tree[idx].bad != tree[idx].dected || tree[idx].good < 0 || tree[idx].bad < 0 || tree[idx].bad > sbad + tree[idx].num) return false; return true; } public static void main(String[] args) { int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int num[] = new int[N]; for (int i = 1; i <= n; i++) { tree[i] = new Node(); tree[i].num = sc.nextInt(); } for (int i = 1; i <= n; i++) { tree[i].dected = sc.nextInt(); } for (int i = 1; i < n; i++) { int x = sc.nextInt(); int y = sc.nextInt(); tree[x].sons.add(y); tree[y].sons.add(x); } boolean ans = dfs(1, 0); if (ans) System.out.println("YES"); else System.out.println("NO"); // for (int i = 1; i <= n; i++) { // System.out.println("node:" + i + " " + tree[i]); // } } } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capitalΒ β€” this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$)Β β€” the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$)Β β€” the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n βˆ’ 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NOΒ β€” otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
4644b14681c3a5f7d2d388e333cccef9
train_000.jsonl
1440865800
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
256 megabytes
/** * Created by kapilkrishnakumar on 11/4/15. * http://codeforces.com/problemset/problem/573/A */ import java.util.*; public class BearPoker { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] lowest = new int[n]; for(int i = 0; i < n; i++){ int val = sc.nextInt(); while(val % 2 == 0 || val % 3 == 0){ if(val % 2 == 0){ val /= 2; } if(val % 3 == 0){ val /= 3; } } lowest[i] = val; } int ch = lowest[0]; boolean t = true; for(int j = 0; j < n; j++){ if(lowest[j] != ch){ t = false; break; } } String res = t ? "Yes" : "No"; System.out.println(res); } }
Java
["4\n75 150 75 50", "3\n100 150 250"]
2 seconds
["Yes", "No"]
NoteIn the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.It can be shown that in the second sample test there is no way to make all bids equal.
Java 7
standard input
[ "implementation", "number theory", "math" ]
2bb893703cbffe9aeaa0bed02f42a05c
First line of input contains an integer n (2 ≀ n ≀ 105), the number of players. The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the bids of players.
1,300
Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.
standard output
PASSED
64e051ee258c1438ec4cfd529bf1c572
train_000.jsonl
1440865800
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
256 megabytes
import java.io.*; import java.util.*; import java.util.List; public class Main { private static StringTokenizer st; private static BufferedReader br; public static long MOD = 1000000007; private static double EPS = 0.0000001; public static void print(Object x) { System.out.println(x + ""); } public static void printArr(long[] x) { StringBuilder s = new StringBuilder(); for (int i = 0; i < x.length; i++) { s.append(x[i] + " "); } print(s); } public static void printArr(int[] x) { StringBuilder s = new StringBuilder(); for (int i = 0; i < x.length; i++) { s.append(x[i] + " "); } print(s); } public static void printArr(char[] x) { StringBuilder s = new StringBuilder(); for (int i = 0; i < x.length; i++) { s.append(x[i] + ""); } print(s); } public static String join(Collection<?> x, String space) { if (x.size() == 0) return ""; StringBuilder sb = new StringBuilder(); boolean first = true; for (Object elt : x) { if (first) first = false; else sb.append(space); sb.append(elt); } return sb.toString(); } public static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); st = new StringTokenizer(line.trim()); } return st.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public static long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public static List<Integer> nextInts(int N) throws IOException { List<Integer> ret = new ArrayList<Integer>(); for (int i = 0; i < N; i++) { ret.add(nextInt()); } return ret; } public static long reduce(long x) { while (x % 3 == 0) x /= 3; while (x % 2 == 0) x /= 2; return x; } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); int n = nextInt(); long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = reduce(nextInt()); boolean possible = true; for (int i = 1; i < n; i++) { if (a[i] != a[0]) possible = false; } if (possible) print("Yes"); else print("No"); } }
Java
["4\n75 150 75 50", "3\n100 150 250"]
2 seconds
["Yes", "No"]
NoteIn the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.It can be shown that in the second sample test there is no way to make all bids equal.
Java 7
standard input
[ "implementation", "number theory", "math" ]
2bb893703cbffe9aeaa0bed02f42a05c
First line of input contains an integer n (2 ≀ n ≀ 105), the number of players. The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the bids of players.
1,300
Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.
standard output
PASSED
37b98bc60140be57fb656f332914f281
train_000.jsonl
1440865800
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class B { static String NO = "No"; static String YES = "Yes"; public static void main(String[] args) throws Exception { readIntArray(); int[] a = readIntArray(); int[] nums = new int[] { 2 ,3 }; for (int i = 0; i < a.length; i++) { for (int j = 0; j < nums.length; j++) { while(a[i] % nums[j] == 0) { a[i] /= nums[j]; } } } for (int i = 0; i < a.length; i++) { if (a[i] != a[0]) { System.out.println(NO); return; } } System.out.println(YES); } private static boolean isok(int cnt) { int[] nums = new int[] { 2 ,3 }; for (int i = 0; i < nums.length; i++) { while(cnt % nums[i] == 0) { cnt /= nums[i]; } } return cnt == 1; } private static void inc(HashMap<Integer, Integer> primeCnts2, int prime) { if (!primeCnts2.containsKey(prime)) { primeCnts2.put(prime, 1); } else primeCnts2.put(prime, primeCnts2.get(prime) + 1); } private static HashMap<Integer, Integer> getPrimes(int a) { HashMap<Integer, Integer> p = new HashMap<Integer, Integer>(); for (int i = 2; i <= Math.sqrt(a) + 2; i++) { while(a % i == 0) { a /= i; inc(p, i); } if (a == 1) break; } if (a != 1) inc(p, a); return p; } static void print(int[] a) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; i++) { if (sb.length() > 0) { sb.append(' '); } sb.append(a[i]); } System.out.println(sb); } static InputStreamReader isr = new InputStreamReader(System.in); static BufferedReader br = new BufferedReader(isr); static StringBuilder sb = new StringBuilder(); static String readNextToken() throws IOException { sb.setLength(0); char c = ' '; do { c = ((char) br.read()); if (Character.isWhitespace(c)) { if (sb.length() > 0) { break; } } else { sb.append(c); } } while (true); return sb.toString(); } static int ni() throws Exception { return Integer.parseInt(readNextToken()); } static long nl() throws Exception { return Long.parseLong(readNextToken()); } static int[] readIntArray() throws IOException { String[] v = br.readLine().split(" "); int[] ans = new int[v.length]; for (int i = 0; i < ans.length; i++) { ans[i] = Integer.valueOf(v[i]); } return ans; } static long[] readLongArray() throws IOException { String[] v = br.readLine().split(" "); long[] ans = new long[v.length]; for (int i = 0; i < ans.length; i++) { ans[i] = Long.valueOf(v[i]); } return ans; } static <T> void print(List<T> v) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < v.size(); i++) { if (sb.length() > 0) { sb.append(' '); } sb.append(v.get(i)); } System.out.println(sb); } }
Java
["4\n75 150 75 50", "3\n100 150 250"]
2 seconds
["Yes", "No"]
NoteIn the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.It can be shown that in the second sample test there is no way to make all bids equal.
Java 7
standard input
[ "implementation", "number theory", "math" ]
2bb893703cbffe9aeaa0bed02f42a05c
First line of input contains an integer n (2 ≀ n ≀ 105), the number of players. The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the bids of players.
1,300
Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.
standard output
PASSED
70794f7308e116d9876dc45d1215186f
train_000.jsonl
1440865800
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
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.io.InputStreamReader; 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); while (a[i] % 2 == 0) a[i] /= 2; while (a[i] % 3 == 0) a[i] /= 3; } for (int i = 1; i < n; ++i) { if (a[i] != a[0]) { out.println("No"); return; } } out.println("Yes"); } } 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
["4\n75 150 75 50", "3\n100 150 250"]
2 seconds
["Yes", "No"]
NoteIn the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.It can be shown that in the second sample test there is no way to make all bids equal.
Java 7
standard input
[ "implementation", "number theory", "math" ]
2bb893703cbffe9aeaa0bed02f42a05c
First line of input contains an integer n (2 ≀ n ≀ 105), the number of players. The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the bids of players.
1,300
Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.
standard output
PASSED
6a735f21dbabd0f86eb15460309289b1
train_000.jsonl
1440865800
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
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.math.BigInteger; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static class Reader { BufferedReader r; StringTokenizer str; Reader() { r=new BufferedReader(new InputStreamReader(System.in)); } Reader(String fileName) throws FileNotFoundException { r=new BufferedReader(new FileReader(fileName)); } public String getNextToken() throws IOException { if(str==null||!str.hasMoreTokens()) { str=new StringTokenizer(r.readLine()); } return str.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(getNextToken()); } public long nextLong() throws IOException { return Long.parseLong(getNextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(getNextToken()); } public String nextString() throws IOException { return getNextToken(); } public int[] intArray(int n) throws IOException { int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } public long[] longArray(int n) throws IOException { long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } public String[] stringArray(int n) throws IOException { String a[]=new String[n]; for(int i=0;i<n;i++) a[i]=nextString(); return a; } public long gcd(long a, long b) { if(b == 0){ return a; } return gcd(b, a%b); } public long lcm(long a,long b) { return (a*b)/gcd(a,b); } public BigInteger gcd(BigInteger a,BigInteger b) { if(b.compareTo(BigInteger.ZERO)==0) return a; return gcd(b,a.mod(b)); } public BigInteger lcm(BigInteger a,BigInteger b) { return (a.multiply(b)).divide(gcd(b,a.mod(b))); } } public static long calc(long a) { while(a%2==0) a=a/2; while(a%3==0) a=a/3; return a; } public static void main(String args[]) throws IOException{ Reader r=new Reader(); PrintWriter pr=new PrintWriter(System.out,false); int n=r.nextInt(); long a[]=r.longArray(n); Arrays.sort(a); int flag=0; for(int i=0;i<n-1;i++) { long lcm=r.lcm(a[i],a[i+1]); long x=lcm/a[i]; long y=lcm/a[i+1]; if(calc(x)>1||calc(y)>1) { flag=1; break; } } if(flag==1) System.out.println("No"); else System.out.println("Yes"); pr.flush(); pr.close(); } }
Java
["4\n75 150 75 50", "3\n100 150 250"]
2 seconds
["Yes", "No"]
NoteIn the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.It can be shown that in the second sample test there is no way to make all bids equal.
Java 7
standard input
[ "implementation", "number theory", "math" ]
2bb893703cbffe9aeaa0bed02f42a05c
First line of input contains an integer n (2 ≀ n ≀ 105), the number of players. The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the bids of players.
1,300
Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.
standard output
PASSED
d9d3a4986e17c882ad1492497d514bd4
train_000.jsonl
1440865800
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
256 megabytes
import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.InputMismatchException; public class Main { class MyScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; BufferedInputStream bis = new BufferedInputStream(System.in); public int read() { if (-1 == numChars) { throw new InputMismatchException (); } if (curChar >= numChars) { curChar = 0; try { numChars = bis.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; } private boolean isSpaceChar(int c) { return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c; } } public int div(int x, int k) { while(x % k == 0) { x /= k; } return x; } public void foo() throws IOException { MyScanner scan = new MyScanner(); PrintWriter out = new PrintWriter(System.out); int n = scan.nextInt(); int x0 = scan.nextInt(); x0 = div(x0, 2); x0 = div(x0, 3); boolean isNo = false; for(int i = 1;i < n;++i) { int x = scan.nextInt(); x = div(x, 2); x = div(x, 3); if(x != x0) { isNo = true; } } out.println(isNo ? "No" : "Yes"); out.close(); } public static void main(String[] args) throws IOException { new Main().foo(); } }
Java
["4\n75 150 75 50", "3\n100 150 250"]
2 seconds
["Yes", "No"]
NoteIn the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.It can be shown that in the second sample test there is no way to make all bids equal.
Java 7
standard input
[ "implementation", "number theory", "math" ]
2bb893703cbffe9aeaa0bed02f42a05c
First line of input contains an integer n (2 ≀ n ≀ 105), the number of players. The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the bids of players.
1,300
Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.
standard output
PASSED
31ad8c0d4f040e00141c23d5e42b381d
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); StringBuilder sb = new StringBuilder(); int t = s.nextInt(); while (t --> 0) { int n = s.nextInt(); int[] a = new int[n]; int[] b = new int[n]; int[] c = new int[n]; for(int i = 0 ; i < n ; i++) a[i] = s.nextInt(); for(int i = 0 ; i < n ; i++) b[i] = s.nextInt(); for(int i = 0 ; i < n ; i++) c[i] = s.nextInt(); int[] ans = new int[n + 1]; ans[0] = -1; for(int i = 1 ; i <= n ; i++){ if(i == n){ if(a[i-1] != ans[i-1] && a[i-1] != ans[1]){ ans[i] = a[i-1]; }else if(b[i-1] != ans[i-1] && b[i-1] != ans[1]){ ans[i] = b[i-1]; }else if(c[i-1] != ans[i-1] && c[i-1] != ans[1]){ ans[i] = c[i-1]; } }else if(a[i-1] != ans[i-1]){ ans[i] = a[i-1]; }else if(b[i-1] != ans[i-1]){ ans[i] = b[i-1]; }else if(c[i-1] != ans[i-1]){ ans[i] = c[i-1]; } } for(int i = 1 ; i <= n ; i++) sb.append(ans[i]).append(" "); sb.append("\n"); } System.out.println(sb); } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
98ed9d1441d6a9c6580a3f09b2218102
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.io.*; import java.util.*; import java.math.BigInteger; public class Main { static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int a[]=sc.nextIntArr(n); int b[]=sc.nextIntArr(n); int c[]=sc.nextIntArr(n); int arr[]=new int[n]; arr[0]=a[0]; for(int i=1;i<n;i++) { if(a[i]==arr[i-1])arr[i]=b[i]; else arr[i]=a[i]; } if(arr[n-1]==arr[0]) { if(c[n-1]!=arr[n-2])arr[n-1]=c[n-1]; else if(b[n-1]!=arr[n-2])arr[n-1]=b[n-1]; else if(a[n-1]!=arr[n-2])arr[n-1]=a[n-1]; } for(int i:arr)out.print(i+" "); out.println(); } out.close(); } static class Pair implements Comparable<Pair>{ int x; int y; public Pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(Pair o) { return (this.x!=o.x)?this.x-o.x:this.y-o.y; } public String toString() { return "("+this.x+","+this.y+")"; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws FileNotFoundException { 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 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 { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextIntArr(int n) throws IOException{ int arr[]=new int[n]; for(int i=0;i<n;i++)arr[i]=nextInt(); return arr; } public BigInteger BigInteger(String s) throws IOException{ BigInteger a=new BigInteger(s); return a; } } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
4836bd7e9d80b034eda80ed14510bf32
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
/*package whatever //do not write package name here */ import java.io.*; import java.util.*; public class GFG { public static void main (String[] args) { //System.out.println("GfG!"); int t, n, a[][]; Scanner sc = new Scanner(System.in); t = sc.nextInt(); while(t-- != 0){ n = sc.nextInt(); a = new int[3][n]; for(int i = 0; i < 3; i++){ for(int j = 0; j < n; j++){ a[i][j] = sc.nextInt(); } } int res[] = new int[n]; for(int i = 0; i < n; i++){ int a_ = a[0][i]; int b = a[1][i]; int c = a[2][i]; if(i == 0)res[i] = a_; else if(i != n-1){ if(res[i-1] != a_)res[i] = a_; else if(res[i-1] != b)res[i] = b; else res[i] = c; } else{ if(res[i-1] != a_ && res[0] != a_)res[i] = a_; else if(res[i-1] != b && res[0] != b)res[i] = b; else res[i] = c; } } for(int x: res)System.out.print(x + " "); System.out.println(); } } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
2c3ab007060866eec4575b72ec00344b
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
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 SolA { public static void main(String[] args) throws java.lang.Exception { // your code goes here Reader sc = new Reader(); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int a[] = new int[n]; int b[] = new int[n]; int c[] = new int[n]; int ans[] = new int[n]; for(int i=0;i<n;i++){ a[i]=sc.nextInt(); } for(int i=0;i<n;i++){ b[i]=sc.nextInt(); } for(int i=0;i<n;i++){ c[i]=sc.nextInt(); } ans[0]=a[0]; for(int i=1;i<n-1;i++){ if(a[i]!=ans[i-1]) ans[i]=a[i]; else if(b[i]!=ans[i-1]) ans[i]=b[i]; else ans[i]=c[i]; } if(a[n-1]!=ans[n-2] && a[n-1]!=ans[0]) ans[n-1] = a[n-1]; else if(b[n-1]!=ans[n-2] && b[n-1]!=ans[0]) ans[n-1] =b[n-1]; else ans[n-1] =c[n-1]; for (int ele: ans ) { out.print(ele+" "); } out.println(); } sc.close(); out.close(); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } 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; } 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 { din.close(); } } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
6ce3f9a359aed0ccb176bed5b6fa5314
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.util.*; public class Problem_A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int a[][] = new int[3][n]; for(int i = 0; i < 3; i++) { for(int j = 0; j < n; j++) { a[i][j] = sc.nextInt(); } } int ans [] = new int[n]; ans[0] = a[0][0]; for(int i = 1; i < n; i++) { int u = a[0][i]; int v = a[1][i]; int d = a[2][i]; if(i == n - 1) { if(u != ans[0] && u != ans[i-1]) ans[i] = u; else if(v != ans[0] && v != ans[i-1]) ans[i] = v; else if(d != ans[0] && d != ans[i-1]) ans[i] = d; continue; } if(u != ans[i-1]) ans[i] = u; else if(v != ans[i-1]) ans[i] = v; else if(d != ans[i-1]) ans[i] = d; } for(int i = 0; i < ans.length; i++) { System.out.print(ans[i] + " "); } System.out.println(); } } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
c5945d11febb719e5f4e6bff6eaa57d9
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.util.*; public class A1 { public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t>0) { int n=s.nextInt(); int ans[]=new int[n]; int a[]=new int[n]; int b[]=new int[n]; int c[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } for(int i=0;i<n;i++) { b[i]=s.nextInt(); } for(int i=0;i<n;i++) { c[i]=s.nextInt(); } ans[0]=a[0]; for(int i=1;i<n;i++) { if(i!=n-1) { if(a[i]!=ans[i-1]) ans[i]=a[i]; if(b[i]!=ans[i-1]) ans[i]=b[i]; if(c[i]!=ans[i-1]) ans[i]=c[i]; } else { if(a[i]!=ans[i-1]&&a[i]!=ans[0]) ans[i]=a[i]; if(b[i]!=ans[i-1]&&b[i]!=ans[0]) ans[i]=b[i]; if(c[i]!=ans[i-1]&&c[i]!=ans[0]) ans[i]=c[i]; } } System.out.println(); for(int i=0;i<n;i++) { System.out.print(ans[i]+" "); } t--; } } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
f1c39fa9e9a0a67c3435d8e7c1fb55d6
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.util.Scanner; public class p1408A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); for (int t = sc.nextInt(); t-- > 0;) { int n = sc.nextInt(), a[][] = new int[3][n]; for (int i = 0; i < 3; i++) for (int j = 0; j < n; j++) a[i][j] = sc.nextInt(); int i = 0, x = -1; for (int j = 0; j < n - 1; j++) { if (a[i][j] == x) if (i < 2) i++; else i = 0; x = a[i][j]; System.out.print(x + " "); } i=0; if(a[0][n-1]==x) if(a[1][n-1]==a[0][0]) i=2; else i=1; else if(a[0][n-1]==a[0][0]) if(a[1][n-1]==x) i=2; else i=1; System.out.println(a[i][n-1]); } } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
85f71c4d267b7c5ca011f7ab68d9aa2b
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.util.Scanner; public class p1408A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); for (int t = sc.nextInt(); t-- > 0;) { int n = sc.nextInt(), a[][] = new int[3][n]; for (int i = 0; i < 3; i++) for (int j = 0; j < n; j++) a[i][j] = sc.nextInt(); int i=0,x=-1; for (int j = 0; j < n-1; j++) { if (a[i][j] == x) { if(i<2 && a[i+1][j]!=x) i++; else i=0; } x=a[i][j]; System.out.print(x+" "); } i=0; if(a[0][n-1]==x) if(a[1][n-1]==a[0][0]) i=2; else i=1; else if(a[0][n-1]==a[0][0]) if(a[1][n-1]==x) i=2; else i=1; System.out.println(a[i][n-1]); } } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
a9da7478d930d83306ebdfef950b581c
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
//package MyJavaProject; import java.util.*; import java.lang.Math; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.io.*; import java.math.BigInteger; 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()); } 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; } } static void print(String s) { System.out.print(s); } static void print(boolean s) { System.out.print(s); } static boolean isPrime(long n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop 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 FastReader f=new FastReader(); static long[] inArr(long a[],int n) { for(int i=0;i<n;i++) a[i]=f.nextLong(); return(a); } static void printArr(long a[],int n) { for(int i=0;i<n;i++) System.out.print(a[i]+" "); System.out.println(); } static long bincon(long x,long y) { String binx=Long.toBinaryString(x); String biny=Long.toBinaryString(y); String xpy=binx+biny; String ypx=biny+binx; //System.out.println(binx+" "+biny); return(Long.parseLong(xpy, 2)-Long.parseLong(ypx, 2)); } public static int SumPairs(int[] input, int k){ Map<Integer, Integer> frequencies = new HashMap<>(); int pairsCount = 0; for(int i=0; i<input.length; i++){ int value = input[i]; int complement = k - input[i]; if(frequencies.containsKey(complement)){ int freq = frequencies.get(complement) - 1; pairsCount++; //System.out.println(value + ", " + complement); if(freq == 0){ frequencies.remove(complement); }else{ frequencies.put(complement, freq); } }else{ if(frequencies.containsKey(value)){ frequencies.put(value, frequencies.get(value) + 1); }else{ frequencies.put(value, 1); } } } return pairsCount; } 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++; } } // Main function that sorts arr[l..r] using // merge() 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); } } static int power(int x, int y, int p) { // Initialize result int res = 1; // Update x if it is more // than or equal to p x = x % p; if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x // with result if((y & 1)==1) res = (res%p * x%p) % p; // y must be even now // y = y / 2 y = y >> 1; x = (x%p * x%p) % p; } return res; } static int modFact(int n, int p) { if (n >= p) return 0; int result = 1; for (int i = 1; i <= n; i++) result = (result%p * i%p) % p; return result; } static int nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Returns factorial of n static int fact(int n) { int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; } public static void main(String argsp[]) throws Exception { Main ob=new Main(); BufferedWriter w=new BufferedWriter(new OutputStreamWriter(System.out)); Random rand = new Random(); //Scanner sc=new Scanner(System.in); //int k=f.nextInt(); int t=f.nextInt(); while(t--!=0) { int n=f.nextInt(); int a[]=new int[n]; int b[]=new int[n]; int c[]=new int[n]; for(int i=0;i<n;i++) a[i]=f.nextInt(); for(int i=0;i<n;i++) b[i]=f.nextInt(); for(int i=0;i<n;i++) c[i]=f.nextInt(); int p[]=new int[3*n]; int i0=0; p[0]=a[0]; for(int i=1;i<n-1;i++) { if(a[i]!=p[i-1]) p[i]=a[i]; else if(b[i]!=p[i-1]) p[i]=b[i]; else p[i]=c[i]; } if(a[n-1]!=p[0] && a[n-1]!=p[n-2]) p[n-1]=a[n-1]; else if(b[n-1]!=p[0]&& b[n-1]!=p[n-2]) p[n-1]=b[n-1]; else p[n-1]=c[n-1]; for(int i=0;i<n;i++) w.write(p[i]+" "); w.write("\n"); } w.flush(); } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
744ffc50ccf21ccee25fb24894cda958
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
/** * https://codeforces.com/contest/1408/problem/A */ import java.util.*; import java.io.*; public class CircleColoring { public static BufferedReader in; public static PrintWriter out; public static StringBuilder sol; public static Utilities util; public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sol = new StringBuilder(); util = new Utilities(); int t = Integer.parseInt(in.readLine()); while(t-- > 0) { int n = Integer.parseInt(in.readLine()); String[] inp = in.readLine().trim().split(" "); long[] a = new long[n], b = new long[n], c = new long[n]; for (int i = 0; i < n; i++) a[i] = Long.parseLong(inp[i]); inp = in.readLine().trim().split(" "); for (int i = 0; i < n; i++) b[i] = Long.parseLong(inp[i]); inp = in.readLine().trim().split(" "); for (int i = 0; i < n; i++) c[i] = Long.parseLong(inp[i]); int i = 0; long[] p = new long[n]; p[0] = a[0]; for (i = 1; i < n-1; i++) { if (a[i] == p[i-1]) p[i] = b[i]; else p[i] = a[i]; } if (a[i] == p[i-1] || a[i] == p[0]) if (b[i] == p[i-1] || b[i] == p[0]) p[i] = c[i]; else p[i] = b[i]; else p[i] = a[i]; for (long val : p) sol.append(val + " "); sol.append("\n"); } out.println(sol); out.close(); } /** * IF a[i], b[i], & c[i] CAN BE SAME: * we have to use backtracking * p[i] β‰  p[i-1] - solved * p[0] β‰  p[n-1] - not solved * Not solved for test-cases like: * 2 1 1 * 3 1 1 * 2 2 1 */ public static long[] solve(long[] a, long[] b, long[] c, long[] p, int n, int i) { if (i == n) return p; else if (a[i] != p[i-1]) { p[i] = a[i]; return solve(a, b, c, p, n, i+1); } else if (b[i] != p[i-1]) { p[i] = b[i]; return solve(a, b, c, p, n, i+1); } else if (c[i] != p[i-1]) { p[i] = c[i]; return solve(a, b, c, p, n, i+1); } else return solve(a, b, c, p, n, i-1); } } class Utilities { public static boolean[] prime; public static long[] fact; public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a%b); } public static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a%b); } public static int power(int a, int b) { int res = 1; while (b > 0) { if (b % 2 == 1) res = res * a; a = a * a; b = b / 2; } return res; } public static long power(long a, long b, long mod) { long res = 1; a = a % mod; b = b % mod; while (b > 0) { if (b % 2 == 1) res = (res * a) % mod; a = (a * a) % mod; b = b / 2; } return res; } public static long modInv(long a, long mod) { return power(a, mod - 2, mod); } // finds index of >= key public static int upper_bound_equals(long[] a, long key) { int low = 0, high = a.length - 1; int mid; while (low < high) { mid = low + (high - low)/2; if (a[mid] < key) low = mid + 1; else high = mid; } return low; } // finds index of > key public static int upper_bound(long[] a, long key) { int low = 0, high = a.length - 1; int mid; while (low < high) { mid = low + (high - low)/2; if (a[mid] <= key) low = mid + 1; else high = mid; } return low; } // finds index of <= key public static int lower_bound_equals(long[] a, long key) { int low = 0, high = a.length - 1; int mid; while (low < high) { mid = low + (high - low)/2; if (a[mid] > key) high = mid; else low = mid - 1; } return low; } // finds index of < key public static int lower_bound(long[] a, long key) { int low = 0, high = a.length - 1; int mid; while (low < high) { mid = low + (high - low)/2; if (a[mid] >= key) high = mid; else low = mid - 1; } return low; } public static void sieve(int n) { prime = new boolean[n+1]; Arrays.fill(prime, true); for (int i = 2; i*i <= n; i++) if (prime[i] == true) for (int j = i*i; j <= n; j += i) prime[j] = false; } public static boolean isPrime(int n) { return prime[n]; } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
62c2724668ca99864cd14211beb9e3ec
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Scanner; import java.util.*; //FuCk ThE RaTiNgS. //YoU NeVeR LoSe EiThEr YoU LeArN Or YoU WiN. public class A { 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 Exception { Scanner sc= new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int a[]=new int[n],b[]=new int[n],c[]=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } for(int i=0;i<n;i++) { b[i]=sc.nextInt(); } for(int i=0;i<n;i++) { c[i]=sc.nextInt(); } int p[]=new int[n]; for(int i=0;i<n-1;i++) { if(i==0) { p[i]=a[i]; continue; } if(a[i]!=p[i-1]) { p[i]=a[i]; continue; }else if(b[i]!=p[i-1]) { p[i]=b[i]; continue; }else if(c[i]!=p[i-1]) { p[i]=c[i]; continue; } } if(a[n-1]!=p[0]&&a[n-1]!=p[n-2]) { p[n-1]=a[n-1]; }else if(b[n-1]!=p[0]&&b[n-1]!=p[n-2]) { p[n-1]=b[n-1]; }else if(c[n-1]!=p[0]&&c[n-1]!=p[n-2]) { p[n-1]=c[n-1]; } for(int i:p) { System.out.print(i+" "); } System.out.println(); } } static long modInverse(long fac, int p) { return pow(fac, p - 2); } static long nCr(int n, int r, int p) { if (r == 0) return 1; long [] fac = new long [n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } public static long[] fact; public static long[] invfact; public static long ncr(int n, int r){ if(r > n) return 0; return ((((fact[n]) * (invfact[r])) % mod)* invfact[n-r]) % mod; } static int mod=(int)1e9+7; static long pow(long x,long y) { long res=1l; while(y!=0) { if(y%2==1) { res=x*res%mod; } y/=2; x=x*x%mod; } return res; } } class pair { int x,y; pair(int x,int y){ this.x=x; this.y=y; } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
240cfb992bd7faa62cd419562eb43576
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.io.*; import java.util.*; /* polyakoff */ public class Main { static FastReader in; static PrintWriter out; static Random rand = new Random(); static final int oo = (int) 1e9 + 10; static final long OO = (long) 2e18 + 20; static final int MOD = (int) 1e9 + 7; static void solve() { int n = in.nextInt(); int[][] a = new int[n][3]; for (int i = 0; i < n; i++) { a[i][0] = in.nextInt(); } for (int i = 0; i < n; i++) { a[i][1] = in.nextInt(); } for (int i = 0; i < n; i++) { a[i][2] = in.nextInt(); } int last = -1; for (int i = 0; i < n; i++) { for (int j = 0; j < 3; j++) { if ((i != n - 1 && a[i][j] != last) || (i == n - 1 && a[i][j] != last && a[i][j] != a[0][0])) { out.print(a[i][j] + " "); last = a[i][j]; break; } } } out.println(); } public static void main(String[] args) { in = new FastReader(); out = new PrintWriter(System.out); // fileInputOutput(); int T = 1; T = in.nextInt(); while (T-- > 0) solve(); out.flush(); out.close(); } static void fileInputOutput() { try { in = new FastReader("input.txt"); out = new PrintWriter(new FileOutputStream("output.txt")); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } static void runInThread() { Thread thread = new Thread(null, () -> { int T = 1; // T = in.nextInt(); while (T-- > 0) solve(); }, "thread1", 1 << 28); thread.start(); try { thread.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } } static class FastReader { BufferedReader br; StringTokenizer st; FastReader() { this(System.in); } FastReader(String file) throws FileNotFoundException { this(new FileInputStream(file)); } FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String line; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
7a6268a36c1dcf71395ddfe2cf0340c5
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.io.*; import java.util.*; /* polyakoff */ public class Main { static FastReader in; static PrintWriter out; static Random rand = new Random(); static final int oo = (int) 1e9 + 10; static final long OO = (long) 2e18 + 20; static final int MOD = (int) 1e9 + 7; static void solve() { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int[] b = new int[n]; for (int i = 0; i < n; i++) { b[i] = in.nextInt(); } int[] c = new int[n]; for (int i = 0; i < n; i++) { c[i] = in.nextInt(); } int last = -1; for (int i = 0; i < n; i++) { if (i != n - 1) { if (a[i] != last) { out.print(a[i] + " "); last = a[i]; } else { out.print(b[i] + " "); last = b[i]; } } else { if (a[i] != last && a[i] != a[0]) { out.print(a[i] + " "); } else if (b[i] != last && b[i] != a[0]) { out.print(b[i] + " "); } else { out.print(c[i] + " "); } } } out.println(); } public static void main(String[] args) { in = new FastReader(); out = new PrintWriter(System.out); // fileInputOutput(); int T = 1; T = in.nextInt(); while (T-- > 0) solve(); out.flush(); out.close(); } static void fileInputOutput() { try { in = new FastReader("input.txt"); out = new PrintWriter(new FileOutputStream("output.txt")); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } static void runInThread() { Thread thread = new Thread(null, () -> { int T = 1; // T = in.nextInt(); while (T-- > 0) solve(); }, "thread1", 1 << 28); thread.start(); try { thread.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } } static class FastReader { BufferedReader br; StringTokenizer st; FastReader() { this(System.in); } FastReader(String file) throws FileNotFoundException { this(new FileInputStream(file)); } FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String line; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
06a2aa036fe89d8f2e48f2a98cebfb6d
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; public class FibinacciSeries { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { 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 Character charAt(int i) { // TODO Auto-generated method stub return null; } public BigInteger nextBigInteger() { // TODO Auto-generated method stub return null; } } static void bubble_sort(int[] arr,int n) { for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } for(int i=0;i<n;i++) { System.out.print(arr[i]+" "); } } public static void main(String[] args) throws IOException { FastReader s=new FastReader(); int t = s.nextInt(); while(t-->0) { int n = s.nextInt(); int[] a =new int[n]; int[] b =new int[n]; int[] c =new int[n]; int p=3,k=0; int[] g = new int[3*n+1]; for(int i=0;i<n;i++) { a[i] = s.nextInt(); } for(int i=0;i<n;i++) { b[i] = s.nextInt(); } for(int i=0;i<n;i++) { c[i] = s.nextInt(); } g[0]=a[0]; k=1; for(int i=1;k<n && i<n ;i++) { if(k==i && g[k-1]!=a[i]) { if(k==n-1 && g[0]==a[i])continue; else g[k++]=a[i]; } else if( k==i && g[k-1]!=b[i] && g[k%n-1]!=b[i]) { if(k==n-1 && g[0]==b[i])continue; else g[k++]=b[i]; } else if(k==i && g[k-1]!=c[i] && g[k%n-1]!=c[i]) { if(k==n-1 && g[0]==c[i])continue; else g[k++]=c[i]; } } for(int i=0;i<n;i++) { if(g[i]==0) { if(g[i-1]!=a[i] && a[i]!=g[0])System.out.println(a[i]); else if(g[i-1]!=b[i] && b[i]!=g[0])System.out.println(b[i]); else if(g[i-1]!=c[i] && c[i]!=g[0])System.out.println(c[i]); } else System.out.print(g[i]+" "); } System.out.println(); } } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
977fdf1f12805032727b622e6f5d8bc7
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.util.*; import java.util.stream.*; public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); StringBuilder result = new StringBuilder(); int t = scan.nextInt(); int j; for(int i = 0; i < t; i++) { int n = scan.nextInt(); int[] a = new int[n]; for(j = 0; j < n; j++) { a[j] = scan.nextInt(); } int[] b = new int[n]; for(j = 0; j < n; j++) { b[j] = scan.nextInt(); } int[] c = new int[n]; for(j = 0; j < n; j++) { c[j] = scan.nextInt(); } StringBuilder res = new StringBuilder(); int prev = 0; int first = 0; for(j = 0; j < n; j++) { if(j == 0) { prev = a[j]; first = a[j]; res.append(a[j] + " "); } else if(j == n-1) { if(first != a[j] && prev != a[j]) { res.append(a[j] + " "); } else if(first != b[j] && prev != b[j]) { res.append(b[j] + " "); } else { res.append(c[j] + " "); } } else if(prev == a[j]) { prev = b[j]; res.append(b[j] + " "); } else if(prev == b[j]) { prev = c[j]; res.append(c[j] + " "); } else { prev = a[j]; res.append(a[j] + " "); } } result.append(res + "\n"); } System.out.println(result); } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
01fa32a956b988193e1915e27a3caf1f
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.util.*; import java.io.*; public class Prb64 { static FastReader sc = new FastReader(); public static void main(String[] args) { int t = sc.nextInt(); while(t-- != 0 ){ int n = sc.nextInt(); int a[] = new int[n]; int b[] = new int[n]; int c[] = new int[n]; int p[] = new int[n]; for(int i = 0 ; i < n ; i++){ a[i] = sc.nextInt(); } for(int i = 0 ; i < n ; i++){ b[i] = sc.nextInt(); } for(int i = 0; i < n; i++){ c[i] = sc.nextInt(); } p[0] = a[0]; for(int i = 0 ; i < n ;i ++){ if(i != 0){ if(p[i-1] != a[i]){ p[i] = a[i]; }else if(p[i - 1] != b[i]){ p[i] = b[i]; }else{ p[i] = c[i]; } } } if(p[0] == p[n-1]){ if(p[n-2] != a[n-1] && p[0] != a[n-1]){ p[n-1] = a[n-1]; }else if(p[n-2] != b[n-1] && p[0] != b[n-1]){ p[n-1] = b[n-1]; }else{ p[n-1] = c[n-1]; } } for(int i = 0 ; i < p.length; i++){ if(i != 0) System.out.print(" "); System.out.print(p[i]);} System.out.println(); } } 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
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
ce361d1b41ab757f05677b0f00c94d3e
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int arr1[]= new int[n]; int arr2[]=new int[n]; int arr3[]=new int[n]; for(int i=0; i<n; i++){ arr1[i]=sc.nextInt(); } for(int i=0; i<n; i++){ arr2[i]=sc.nextInt(); } for(int i=0; i<n; i++){ arr3[i]=sc.nextInt(); } int arr[]= new int[n]; arr[0]=arr1[0]; for(int i=1; i<n; i++){ if(arr[i-1]!=arr2[i]) arr[i]=arr2[i]; else if(arr[i-1]!=arr3[i]) arr[i]=arr3[i]; else if(arr[i-1]!=arr1[i]) arr[i]=arr1[i]; } int x=0; if(arr[0]==arr[n-1]){ if(arr1[n-1]!=arr[n-1] && arr[n-2]!=arr1[n-1]) arr[n-1]=arr1[n-1]; else if(arr2[n-1]!=arr[n-1] && arr[n-2]!=arr2[n-1]) arr[n-1]=arr2[n-1]; else if(arr3[n-1]!=arr[n-1] && arr[n-2]!=arr3[n-1]) arr[n-1]=arr3[n-1]; } for(int i=0; i<n; i++) System.out.print(arr[i]+ " "); System.out.println(); } } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
6677ba198fb30aea8f3499008c431c28
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class A { //-----------Integer Array Input---------- static int[] readIntArray(int n){ int arr[]=new int[n]; for(int i=0;i<n;i++) arr[i]=scan.nextInt(); return arr; } //-----------Long Array Input---------- static long[] readLongArray(int n){ long arr[]=new long[n]; for(int i=0;i<n;i++) arr[i]=scan.nextLong(); return arr; } //------------Boolean Array of Prime number---------------- static boolean[] isPrimeArray(int e){ boolean arr[] = new boolean[e+1]; Arrays.fill(arr,true); arr[0]=false; arr[1]=false; for(int i=2;i*i<=e;i++){ for(int j=2*i;j<=e;j+=i) arr[j]=false; } return arr; } //-----------Prime number Check---------------- static boolean isPrime(int e){ for(int i=2;i*i<=e;i++) if(e%i==0) return false; if(e==1) return false; return true; } //----------------Fast Power ------------------ static long fastPower(long a,long b){ long res=1; while(b>0){ if(b%2!=0){ res=(res*a%MOD)%MOD; } a=(a%MOD*a%MOD)%MOD; b=b>>1; } return res; } // ----------------Function for GCD(using recursion)----------- static long gcd(int a,int b){ if(b==0) return a; else return gcd(b,a%b); } //---------Function for Counting Set Bits------------ static int countSetBits(int n){ int count=0; while(n>0){ n=n&(n-1); count++; } return count; } //-------Function for lastDigit -------- static boolean lastDigit(int n){ int a=n; while(a>0){ int ld=a%10; if(ld!=4 || ld!=7) return false; a=a/10; } return true; } //--------- Swap function-------------- static int[] swap(int a,int b){ int temp=a; b=a; a=temp; return (new int[]{a,b}); } //---------- Inverse of a Number in Range of MOD----------- static long Inverse(long n) { return fastPower(n,MOD-2); } //----------Multiplication of two NUMBERS IN MOD------------- static long multiply(long a,long b) { return ((a%MOD * b%MOD)%MOD); } //-----------Factorial of a Number------------- static final int SIZE=1000003; static final long FACT[]=new long[SIZE]; static void computeFactorial() { FACT[0]=1; for(int i=1;i<SIZE;i++) { FACT[i]=multiply(FACT[i-1],i); } } //---------------COMPUTER NcR_MOD------------ static long NCR(long n,long r) { if(r==0 || r==n) return 1; return (multiply(multiply(FACT[(int) n],Inverse(FACT[(int) r])),Inverse(FACT[(int) (n-r)]))); } //-------------------MOD---------------------- static final long MOD=1000000007; //-----------PrintWriter for faster output--------------------------------- static final PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out)); //-----------MyScanner Object---------------------------------- public static MyScanner scan = new MyScanner(); //-----------------Main method---------------- public static void main (String[] args) throws java.lang.Exception { // your code goes here int tc = scan.nextInt(); //computeFactorial(); for (int i = 0; i < tc; i++) { solve(); } pw.close(); } //-----------------Main function Ends here----------------- //------------Solve function for solving queries----------------------- private static void solve() { int n=scan.nextInt(); int arr[][]=new int[3][n]; for(int i=0;i<3;i++) { for(int j=0;j<n;j++) arr[i][j]=scan.nextInt(); } StringBuffer sb=new StringBuffer(); int rowcount=0; sb.append(arr[0][0]+" "); int temp=arr[0][0]; int temp2=0; int i=1; for(;i<n-1;i++) { if(arr[rowcount][i-1]==arr[rowcount][i]) { rowcount++; if(rowcount==3) rowcount=0; sb.append(arr[rowcount][i]+" "); temp2=arr[rowcount][i]; } else { sb.append(arr[rowcount][i]+" "); temp2=arr[rowcount][i]; } } if(i==n-1) { while(temp==arr[rowcount][i] || temp2==arr[rowcount][i] ) { rowcount++; if(rowcount==3) rowcount=0; } sb.append(arr[rowcount][i]+" "); } pw.println(sb); } //------------Solve function ends here----------------- //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { 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; } } //-----------MyScanner class ends here------------------------ }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
a4878aa7b458e0a577889fca60987710
train_000.jsonl
1601476500
You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i&lt;n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); PrintWriter out = new PrintWriter(outputStream); ACircleColoring solver = new ACircleColoring(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } static class ACircleColoring { public void solve(int testNumber, FastInput in, PrintWriter out) { int n = in.readInt(); int[] a = new int[n]; int[] b = new int[n]; int[] c = new int[n]; in.populate(a); in.populate(b); in.populate(c); int last = 0; int first = -1; for (int i = 0; i < n; i++) { if (a[i] != first && a[i] != last) { last = a[i]; } else if (b[i] != first && b[i] != last) { last = b[i]; } else { last = c[i]; } if (i == 0) { first = last; } out.print(last); out.print(' '); } out.println(); } } static class FastInput { private final InputStream is; private StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } public void populate(int[] data) { for (int i = 0; i < data.length; i++) { data[i] = readInt(); } } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public String next() { return readString(); } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } } }
Java
["5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3"]
1 second
["1 2 3\n1 2 1 2\n1 3 4 3 2 4 2\n1 3 2\n1 2 3 1 2 3 1 2 3 2"]
NoteIn the first test case $$$p = [1, 2, 3]$$$.It is a correct answer, because: $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$ $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$ All possible correct answers to this test case are: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.In the second test case $$$p = [1, 2, 1, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Also we can see, that no two adjacent elements of the sequence are equal.In the third test case $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.In this sequence $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Also we can see, that no two adjacent elements of the sequence are equal.
Java 8
standard input
[ "constructive algorithms" ]
7647528166b72c780d332ef4ff28cb86
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.
800
For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.
standard output
PASSED
ccfeaa12edd46e93049541c67ad99e42
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.*; import java.util.HashSet; import java.util.Iterator; /** * Created by Scruel on 2017/5/10. * Personal blog : http://blog.csdn.net/scruelt * Github : https://github.com/scruel * //TODO */ public class CF746E { static BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(System.out), 1 << 16); static BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in), 1 << 16); static HashSet<Integer> M1 = new HashSet<Integer>(); static HashSet<Integer> M2 = new HashSet<Integer>(); static HashSet<Integer> V = new HashSet<Integer>(); static String[] rts; static int[] arr; static boolean[] isRep; static int n, m, exchangeSum; static int oddIndex = 1; static int evenIndex = 2; public static void main(String[] args) throws IOException { rts = bfr.readLine().split("\\s+"); n = new Integer(rts[0]); m = new Integer(rts[1]); arr = new int[n + 1]; isRep = new boolean[n]; rts = bfr.readLine().split("\\s+"); for (int i = 1; i <= n; i++) { int tmp = Integer.parseInt(rts[i - 1]); arr[i] = tmp; if ((arr[i] & 1) == 1) M1.add(arr[i]); else M2.add(arr[i]); } for (int i = 1; i <= Math.min(2 * n, m); i++) { if ((i & 1) == 1) { if (!M1.contains(i)) { V.add(i); M1.remove(i); } } else { if (!M2.contains(i)) { V.add(i); M2.remove(i); } } } int od, ev; if ((m & 1) == 1) od = m / 2 + 1; else od = m / 2; ev = m / 2; for (int i : M1) if (i > m) od++; for (int i : M2) if (i > m) ev++; if (2 * Math.min(od, ev) < n) { bfw.write("-1"); } else { int cnt = 0; if (M1.size() > n / 2) { cnt = M1.size() - n / 2; } for (Iterator<Integer> iter = M1.iterator(); iter.hasNext(); ) { int tmp = iter.next(); if (cnt == 0) break; cnt--; V.add(tmp); iter.remove(); } cnt = 0; if (M2.size() > n / 2) { cnt = M2.size() - n / 2; } for (Iterator<Integer> iter = M2.iterator(); iter.hasNext(); ) { int tmp = iter.next(); if (cnt == 0) break; cnt--; V.add(tmp); iter.remove(); } int x = 1, y = 2; int ans = 0; int qx, qy; qx = M1.size(); qy = M2.size(); for (int i = 1; i <= n; i++) { if ((arr[i] & 1) == 1) { if (M1.contains(arr[i])) M1.remove(arr[i]); else { if (qx <= qy) { while (!V.contains(x)) x += 2; arr[i] = x; ans++; qx++; V.remove(x); } else { while (!V.contains(y)) y += 2; arr[i] = y; ans++; qy++; V.remove(y); } } } else { if (M2.contains(arr[i])) M2.remove(arr[i]); else { if (qx <= qy) { while (!V.contains(x)) x += 2; arr[i] = x; ans++; qx++; V.remove(x); } else { while (!V.contains(y)) y += 2; arr[i] = y; ans++; qy++; V.remove(y); } } } } bfw.write(ans + "\n"); for (int i = 1; i <= n; i++) bfw.write(String.format("%d%c", arr[i], i == n ? '\n' : ' ')); } bfw.close(); bfr.close(); } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
7d6999a351c7f30ff2233df07362dbf9
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.*; import java.util.*; public class E { FastScanner in; PrintWriter out; int i = 0, j = 0; void solve() { /**************START**************/ int n = in.nextInt(), m = in.nextInt(); int[] nums = new int[n]; TreeSet<Integer> evens = new TreeSet<Integer>(); TreeSet<Integer> odds = new TreeSet<Integer>(); int numEvensBelowM = 0, numOddsBelowM = 0; ArrayList<Integer> indicies = new ArrayList<Integer>(); int evenTotal = 0, oddTotal = 0; int target = n/2; for (i = 0; i < n; i++) { nums[i] = in.nextInt(); if (nums[i] % 2 == 0) { if (evens.contains(nums[i]) || evenTotal == target) { indicies.add((Integer)i); nums[i] = 0; } else { evenTotal++; evens.add(nums[i]); if (nums[i] <= m) { numEvensBelowM++; } } } else { if (odds.contains(nums[i]) || oddTotal == target) { indicies.add((Integer)i); nums[i] = 0; } else { oddTotal++; odds.add(nums[i]); if(nums[i] <= m) { numOddsBelowM++; } } } } int oddsNeeded = target - oddTotal; int evensNeeded = target - evenTotal; int oP, eP; if (m % 2 == 0) { oP = m/2; eP = m/2; } else { oP = (m+1)/2; eP = (m-1)/2; } boolean oddPoss = oP - numOddsBelowM >= oddsNeeded; boolean evenPoss = eP - numEvensBelowM >= evensNeeded; if (!oddPoss || !evenPoss) { out.println(-1); return; } out.println((oddsNeeded+evensNeeded)); int last = 0; int next; ArrayList<Integer> evenCandidates = new ArrayList<Integer>(); ArrayList<Integer> oddCandidates = new ArrayList<Integer>(); ArrayList<Integer> allCandidates = new ArrayList<Integer>(); if (evensNeeded > 0) { if (m % 2 == 0) { evens.add(m+2); } else { evens.add(m+1); } while (!evens.isEmpty()) { next = evens.pollFirst(); if (next - last > 2) { for (i = last+2; i < next; i+=2) { evenCandidates.add(i); allCandidates.add(i); if (evenCandidates.size() == evensNeeded) { break; } } if (evenCandidates.size() == evensNeeded) { break; } } last = next; } } if (oddsNeeded > 0) { last = -1; if (m % 2 == 0) { odds.add(m+1); } else { odds.add(m+2); } while (!odds.isEmpty()) { next = odds.pollFirst(); if (next - last > 2) { for (i = last+2; i < next; i+=2) { oddCandidates.add(i); allCandidates.add(i); if (oddCandidates.size() == oddsNeeded) { break; } } if (oddCandidates.size() == oddsNeeded) { break; } } last = next; } } for (int ind = 0; ind < indicies.size(); ind++) { nums[indicies.get(ind).intValue()] = allCandidates.get(ind); } for (i = 0; i < nums.length; i++) { out.print(nums[i] + " "); } out.println(); /***************END***************/ } public static void main(String[] args) { new E().runIO(); } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
b88d9a41eab50f006c86d64824e2681b
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /** * Created by FirΠ΅fly on 12/18/2016. */ public class code { public static void main(String[] args) throws IOException { Woorker worker = new Woorker(); } } class Woorker { Woorker() throws IOException { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out,true); StringBuilder sb=new StringBuilder(); int n=sc.nextInt(); int m=sc.nextInt(); int [] a=new int [n]; TreeSet<Integer> even=new TreeSet<Integer>(); TreeSet<Integer> odd=new TreeSet<Integer>(); ArrayList<Integer> id=new ArrayList<Integer>(); for(int i=0;i<n;i++){ a[i]=sc.nextInt(); if(a[i]%2==0){ if(!even.contains(a[i]) && even.size()<n/2){ even.add(a[i]); }else{ id.add(i); } }else{ if(!odd.contains(a[i]) && odd.size()<n/2){ odd.add(a[i]); }else{ id.add(i); } } } int cnteven=n/2-even.size(); int cntodd=n/2-odd.size(); long ans=id.size(); int p=0; for(int i=2;i<=m;i+=2){ if(!even.contains(i) && cnteven>0 && p<id.size()){ a[id.get(p)]=i; cnteven--; p++; } if(cnteven==0) break; } for(int i=1;i<=m;i+=2){ if(!odd.contains(i) && cntodd>0 && p<id.size()){ a[id.get(p)]=i; cntodd--; p++; } if(cntodd==0) break; } even.clear(); odd.clear(); for(int i=0;i<n;i++){ if(a[i]%2==0) even.add(a[i]); else odd.add(a[i]); } boolean ok=(even.size()==n/2 && odd.size()==n/2); if(!ok) System.out.println(-1); else{ System.out.println(ans); for(int i=0;i<n;i++) if(i<n-1) System.out.print(a[i]+" "); else System.out.println(a[i]); } pw.flush(); pw.close(); } } class FastScannerqq { BufferedReader br; StringTokenizer stok; FastScannerqq(InputStreamReader fr) { br = new BufferedReader(fr); } String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) return null; stok = new StringTokenizer(s); } return stok.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) br.read(); } String nextLine() throws IOException { return br.readLine(); } } class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { 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
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
1025e384993a325e73ab329a51a8b22e
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.LinkedList; import java.util.StringTokenizer; import java.util.TreeSet; public class P746E { public static void main(String[] args) { FastScanner scan = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int n = scan.nextInt(), m = scan.nextInt(); int[] arr = new int[n], ans = new int[n]; for (int i = 0; i < arr.length; i++) arr[i] = ans[i] = scan.nextInt(); TreeSet<Integer> dontHaveE = new TreeSet<>(); TreeSet<Integer> dontHaveO = new TreeSet<>(); int limit = Math.min(m, 2*n+11); for (int i = 2; i <= limit; i+=2) dontHaveE.add(i); for (int i = 1; i <= limit; i+=2) dontHaveO.add(i); HashSet<Integer> even = new HashSet<>(); HashSet<Integer> odd = new HashSet<>(); LinkedList<Integer> exchange = new LinkedList<>(); //indexes for (int i = 0; i < n; i++) { int num = arr[i]; if (num % 2 == 0) { dontHaveE.remove(num); if (even.contains(num)) exchange.add(i); else even.add(num); } else { dontHaveO.remove(num); if (odd.contains(num)) exchange.add(i); else odd.add(num); } } int evenC = even.size(), oddC = odd.size(); boolean possible = true; while (!exchange.isEmpty()) { int ex = exchange.poll(); Integer need = evenC < oddC ? dontHaveE.higher(0) : dontHaveO.higher(0); if (need == null) { possible = false; break; } ans[ex] = need; if (need % 2 == 0) { dontHaveE.remove(need); evenC++; } else { dontHaveO.remove(need); oddC++; } } int index = 0; while (evenC != oddC && index < n) { Integer need = evenC < oddC ? dontHaveE.higher(0) : dontHaveO.higher(0); if (need == null) { possible = false; break; } if (evenC < oddC && ans[index] % 2 == 1) { dontHaveO.add(ans[index]); dontHaveE.remove(need); ans[index] = need; oddC--; evenC++; } else if (evenC >= oddC && ans[index] % 2 == 0) { dontHaveE.add(ans[index]); dontHaveO.remove(need); ans[index] = need; evenC--; oddC++; } index++; } if (evenC != oddC) possible = false; if (!possible) pw.println(-1); else { int changed = 0; for (int i = 0; i < ans.length; i++) if (arr[i] != ans[i]) changed++; pw.println(changed); for (int a : ans) pw.print(a + " "); } pw.flush(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextLine() { String line = ""; try { line = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return line; } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
cf243f6ba66b70c2f05519cffdd46bfc
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.InputMismatchException; public class E { public static void main(String[] args) { FastScannerE sc = new FastScannerE(System.in); int N = sc.nextInt(); int NH = N/2; int M = sc.nextInt(); int[] arr = new int[N]; HashSet<Integer> even = new HashSet<>(); HashSet<Integer> odd = new HashSet<>(); ArrayList<Integer> dup_pos = new ArrayList<>(); ArrayList<Integer> swaps = new ArrayList<>(); for(int i = 0; i<N; i++){ arr[i] = sc.nextInt(); if(arr[i] % 2 == 0){ if(even.contains(arr[i]) || even.size() == NH) dup_pos.add(i); else even.add(arr[i]); } else{ if(odd.contains(arr[i]) || odd.size() == NH) dup_pos.add(i); else odd.add(arr[i]); } } int even_dups = NH - even.size(); int odd_dups = NH - odd.size(); int dups = even_dups + odd_dups; //even for(int i = 2; i <= M && even_dups > 0; i += 2){ if(!even.contains(i)){ swaps.add(i); even_dups--; } } if(even_dups > 0){ System.out.println(-1); System.exit(0); } //odd for(int i = 1; i <= M && odd_dups > 0; i += 2){ if(!odd.contains(i)){ swaps.add(i); odd_dups--; } } if(odd_dups > 0){ System.out.println(-1); System.exit(0); } //do swaps for(int i = 0, len = dup_pos.size(); i<len; i++){ arr[dup_pos.get(i)] = swaps.get(i); } StringBuilder sb = new StringBuilder(); for(int i : arr){ sb.append(i); sb.append(' '); } System.out.println(dups); System.out.println(sb.substring(0, sb.length() - 1)); } } class FastScannerE{ private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastScannerE(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 String next() { 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 String nextLine() { int c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isLineEndChar(c)); return res.toString(); } 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 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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isLineEndChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
384c4fc9e397d9a5063d4747ee291ff8
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.*; import java.util.*; public class A558 { static BufferedReader in = null; static PrintWriter out = null; static StringTokenizer st = new StringTokenizer(""); public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); } } public static String readString() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public static int readInt() { return Integer.parseInt(readString()); } public static long readLong() { return Long.parseLong(readString()); } private static long binPow(long value, long pow) { if (pow == 0) return 1; if (pow == 1) return value; if (pow % 2 == 0) { long temp = binPow(value, pow / 2); return temp * temp; } return value * binPow(value, pow - 1); } private static void solve() throws IOException { int n = readInt(); int m = readInt(); int[] a = new int[n]; HashMap<Integer, Integer> map = new HashMap<>(); int odd = 0; int even = 0; for (int i = 0; i < n; i++) { a[i] = readInt(); if (a[i] % 2 == 0) even++; else odd++; int count = 1; if (map.containsKey(a[i])) { count += map.get(a[i]); } map.put(a[i], count); } int ans = 0; int firstEvenNotUsed = 2; int firstOddNotUsed = 1; for (int i = 0; i < n; i++) { int cur = a[i]; int count = map.get(cur); if (count > 1) { if (cur % 2 != 0 && odd <= even || cur % 2 == 0 && even > odd) { for (; firstOddNotUsed <= m; firstOddNotUsed += 2) { if (!map.containsKey(firstOddNotUsed)) { break; } } if (firstOddNotUsed > m) { out.print(-1); return; } map.put(a[i], count - 1); a[i] = firstOddNotUsed; map.put(firstOddNotUsed, 1); ans++; if (cur % 2 == 0) { even--; odd++; } } else { for (; firstEvenNotUsed <= m; firstEvenNotUsed += 2) { if (!map.containsKey(firstEvenNotUsed)) { break; } } if (firstEvenNotUsed > m) { out.print(-1); return; } map.put(a[i], count - 1); a[i] = firstEvenNotUsed; map.put(firstEvenNotUsed, 1); ans++; if (cur % 2 != 0) { even++; odd--; } } } } for (int i = 0; i < n; i++) { if (odd == even) { break; } if (even > odd) { if (a[i] % 2 == 0) { for (; firstOddNotUsed <= m; firstOddNotUsed += 2) { if (!map.containsKey(firstOddNotUsed)) { break; } } if (firstOddNotUsed > m) { out.print(-1); return; } a[i] = firstOddNotUsed; // Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ Π΅Ρ‰Π΅ Π² ΠΌΠ°ΠΏΡƒ Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ map.put(firstOddNotUsed, 1); ans++; even--; odd++; } } else { if (a[i] % 2 != 0) { for (; firstEvenNotUsed <= m; firstEvenNotUsed += 2) { if (!map.containsKey(firstEvenNotUsed)) { break; } } if (firstEvenNotUsed > m) { out.print(-1); return; } a[i] = firstEvenNotUsed; // Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ Π΅Ρ‰Π΅ Π² ΠΌΠ°ΠΏΡƒ Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ map.put(firstEvenNotUsed, 1); ans++; even++; odd--; } } } if (even != odd) out.println("KEK"); out.println(ans); for (int i = 0; i < n; i++) { out.print(a[i] + " "); } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
2fee02dc8d3cc035ffdf0814f954f035
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.*; import java.util.*; public class A558 { static BufferedReader in = null; static PrintWriter out = null; static StringTokenizer st = new StringTokenizer(""); public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); } } public static String readString() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public static int readInt() { return Integer.parseInt(readString()); } public static long readLong() { return Long.parseLong(readString()); } private static long binPow(long value, long pow) { if (pow == 0) return 1; if (pow == 1) return value; if (pow % 2 == 0) { long temp = binPow(value, pow / 2); return temp * temp; } return value * binPow(value, pow - 1); } private static void solve() throws IOException { /*long s = readInt(); long x1 = readInt(); long x2 = readInt(); long t1 = readInt(); long t2 = readInt(); long p = readInt(); long dirTrain = readInt(); long ans = (x2 - x1) * t1; // Ρ‚ΡƒΠΏΠΎ пСшком long dirIgor = x2 > x1 ? 1 : -1; long time = 0; double posIgor = x1; while (posIgor != x2) { time++; posIgor += ((1.0/t2)); }*/ int n = readInt(); int m = readInt(); int[] a = new int[n]; HashMap<Integer, Integer> map = new HashMap<>(); HashMap<Integer, List<Integer>> positions = new HashMap<>(); int odd = 0; int even = 0; for (int i = 0; i < n; i++) { a[i] = readInt(); if (a[i] % 2 == 0) even++; else odd++; int count = 1; if (map.containsKey(a[i])) { count += map.get(a[i]); map.put(a[i], count); List<Integer> pos = positions.get(a[i]); pos.add(i); positions.put(a[i], pos); } else { List<Integer> pos = new ArrayList<>(); pos.add(i); map.put(a[i], 1); positions.put(a[i], pos); } } int ans = 0; int firstEvenNotUsed = 2; int firstOddNotUsed = 1; for (int i = 0; i < n; i++) { int cur = a[i]; int count = map.get(cur); if (count > 1) { List<Integer> pos = positions.get(cur); for (int j = 1; j < pos.size(); j++) { if (even > odd || odd == even && cur % 2 != 0) { for (; firstOddNotUsed <= m; firstOddNotUsed += 2) { if (!map.containsKey(firstOddNotUsed)) { break; } } if (firstOddNotUsed > m) { out.print(-1); return; } a[pos.get(j)] = firstOddNotUsed; // Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ Π΅Ρ‰Π΅ Π² ΠΌΠ°ΠΏΡƒ Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ map.put(firstOddNotUsed, 1); ans++; if (cur % 2 == 0) { even--; odd++; } } else { for (; firstEvenNotUsed <= m; firstEvenNotUsed += 2) { if (!map.containsKey(firstEvenNotUsed)) { break; } } if (firstEvenNotUsed > m) { out.print(-1); return; } a[pos.get(j)] = firstEvenNotUsed; // Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ Π΅Ρ‰Π΅ Π² ΠΌΠ°ΠΏΡƒ Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ map.put(firstEvenNotUsed, 1); ans++; if (cur % 2 != 0) { even++; odd--; } } } } } for (int i = 0; i < n; i++) { if (odd == even) { break; } if (even > odd) { if (a[i] % 2 == 0) { for (; firstOddNotUsed <= m; firstOddNotUsed += 2) { if (!map.containsKey(firstOddNotUsed)) { break; } } if (firstOddNotUsed > m) { out.print(-1); return; } a[i] = firstOddNotUsed; // Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ Π΅Ρ‰Π΅ Π² ΠΌΠ°ΠΏΡƒ Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ map.put(firstOddNotUsed, 1); ans++; even--; odd++; } } else { if(a[i] % 2 != 0) { for (; firstEvenNotUsed <= m; firstEvenNotUsed += 2) { if (!map.containsKey(firstEvenNotUsed)) { break; } } if (firstEvenNotUsed > m) { out.print(-1); return; } a[i] = firstEvenNotUsed; // Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ Π΅Ρ‰Π΅ Π² ΠΌΠ°ΠΏΡƒ Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ map.put(firstEvenNotUsed, 1); ans++; even++; odd--; } } } out.println(ans); for (int i = 0; i < n; i++) { out.print(a[i] + " "); } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
0853c3e47965c0bd9c9ef31c28be6336
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Long.parseLong; import static java.util.Arrays.copyOf; import static java.util.Arrays.fill; import static java.util.Arrays.sort; import static java.util.Collections.reverse; import static java.util.Collections.reverseOrder; import static java.util.Collections.sort; public class Main { private FastScanner in; private PrintWriter out; private void solve() throws IOException { long x[] = {2, 1}; int n = in.nextInt(); long m = in.nextLong(); long[] a = new long[n]; HashSet<Long>[] set = new HashSet[]{new HashSet<>(), new HashSet<>()}; ArrayList<Integer> del = new ArrayList<>(); for (int i = 0; i < n; i++) { a[i] = in.nextLong(); if (!set[(int) (a[i] % 2)].contains(a[i])) set[(int) (a[i] % 2)].add(a[i]); else { del.add(i); } } int j = set[0].size() < set[1].size() ? 0 : 1, cnt = 0; for (int i : del) { j = set[0].size() < set[1].size() ? 0 : 1; while (set[j].contains(x[j])) x[j] += 2; if (x[j] > m) { out.print(-1); return; } a[i] = x[j]; set[j].add(x[j]); x[j] += 2; cnt++; } int jj = (j + 1) % 2; int i = 0; while (set[0].size() != set[1].size()) { while ((int) (a[i] % 2) == j) i++; while (set[j].contains(x[j])) x[j] += 2; if (x[j] > m) { out.print(-1); return; } set[jj].remove(a[i]); a[i] = x[j]; x[j] += 2; set[j].add(a[i]); i++; cnt++; } out.println(cnt); for (long ii : a) out.print(ii + " "); } private void solveA() throws IOException { } private void solveB() throws IOException { } private void solveC() throws IOException { } private void solveD() throws IOException { } private void solveE() throws IOException { } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
b7530aa2ace0bef77defbd921973c0a3
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class E_Round_386_Div2 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int m = in.nextInt(); int[] data = new int[n]; for (int i = 0; i < n; i++) { data[i] = in.nextInt(); } HashSet<Integer> odd = new HashSet<>(); HashSet<Integer> even = new HashSet<>(); int o = 0, e = 0; boolean ok = true; LinkedList<Integer> oddNorm = new LinkedList<>(); LinkedList<Integer> oddRep = new LinkedList<>(); LinkedList<Integer> evenRep = new LinkedList<>(); LinkedList<Integer> evenNorm = new LinkedList<>(); for (int i = 0; i < n; i++) { if (data[i] % 2 == 0) { if (!even.contains(data[i])) { even.add(data[i]); evenNorm.add(i); } else { evenRep.add(i); } e++; } else { if (!odd.contains(data[i])) { odd.add(data[i]); oddNorm.add(i); } else { oddRep.add(i); } o++; } } int startOdd = 1; int startEven = 2; int re = 0; // System.out.println(o + " " + e); if (o != e) { if (o > e) { for (int i = 0; i < (o - e) / 2; i++) { int index; if (!oddRep.isEmpty()) { index = oddRep.poll(); } else { index = oddNorm.poll(); } while (even.contains(startEven)) { startEven += 2; } if (startEven > m) { ok = false; break; } // System.out.println(index + " " + startEven); data[index] = startEven; startEven += 2; re++; } } else if (o < e) { for (int i = 0; i < (e - o) / 2; i++) { int index; if (!evenRep.isEmpty()) { index = evenRep.poll(); } else { index = evenNorm.poll(); } while (odd.contains(startOdd)) { startOdd += 2; } if (startOdd > m) { ok = false; break; } data[index] = startOdd; startOdd += 2; re++; } } } while (!oddRep.isEmpty() && ok) { int index = oddRep.poll(); while (odd.contains(startOdd)) { startOdd += 2; } if (startOdd > m) { ok = false; } re++; data[index] = startOdd; startOdd += 2; } while (!evenRep.isEmpty() && ok) { int index = evenRep.poll(); while (even.contains(startEven)) { startEven += 2; } if (startEven > m) { ok = false; } re++; data[index] = startEven; startEven += 2; } if (ok) { out.println(re); for (int i : data) { out.print(i + " "); } } else { out.println(-1); } out.close(); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new // BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new // FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
2147466e1b22b3c6defd91ea1c2ad82d
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.util.*; import java.io.*; public class NumbersExchange { /************************ SOLUTION STARTS HERE ***********************/ private static void solve(FastScanner s1, PrintWriter out){ int N = s1.nextInt(); int M = s1.nextInt(); int arr[] = s1.nextIntArray(N); HashSet<Integer> evens = new HashSet<>(); HashSet<Integer> odds = new HashSet<>(); for(int a : arr) if(a % 2 == 0) evens.add(a); else odds.add(a); if(evens.size() == N / 2 && odds.size() == N / 2) { out.println(0); Arrays.stream(arr).forEach(a -> out.print(a + " ")); } else if(evens.size() >= N / 2) { ArrayList<Integer> toBeReplaced = new ArrayList<>(); HashSet<Integer> blacklist = new HashSet<>(); HashSet<Integer> filter[] = new HashSet[2]; filter[0] = new HashSet<>(); filter[1] = new HashSet<>(); for(int i=0;i<N;i++) { int j = arr[i] % 2; if(filter[j].contains(arr[i]) || filter[j].size() == N / 2) toBeReplaced.add(i); else filter[j].add(arr[i]); if(arr[i] % 2 == 1 && arr[i] <= M) blacklist.add(arr[i]); } int nextOdd = 1; for(int i : toBeReplaced) { while(nextOdd <= M && blacklist.contains(nextOdd)) nextOdd += 2; if(nextOdd > M) { out.println(-1); return; } else arr[i] = nextOdd; nextOdd += 2; } out.println(toBeReplaced.size()); Arrays.stream(arr).forEach(a -> out.print(a + " ")); } else if(odds.size() >= N / 2) { ArrayList<Integer> toBeReplaced = new ArrayList<>(); HashSet<Integer> blacklist = new HashSet<>(); HashSet<Integer> filter[] = new HashSet[2]; filter[0] = new HashSet<>(); filter[1] = new HashSet<>(); for(int i=0;i<N;i++) { int j = arr[i] % 2; if(filter[j].contains(arr[i]) || filter[j].size() == N / 2) toBeReplaced.add(i); else filter[j].add(arr[i]); if(arr[i] % 2 == 0 && arr[i] <= M) blacklist.add(arr[i]); } // out.println("replace " + toBeReplaced); int nextEven = 2; for(int i : toBeReplaced) { while(nextEven <= M && blacklist.contains(nextEven)) nextEven += 2; if(nextEven > M) { out.println(-1); return; } else arr[i] = nextEven; nextEven += 2; } out.println(toBeReplaced.size()); Arrays.stream(arr).forEach(a -> out.print(a + " ")); } else { ArrayList<Integer> toBeReplaced = new ArrayList<>(); HashSet<Integer> oddBlacklist = new HashSet<>(); HashSet<Integer> evenBlacklist = new HashSet<>(); HashSet<Integer> filter = new HashSet<>(); int oddRem = N / 2; for(int i=0;i<N;i++) { if(filter.contains(arr[i])) toBeReplaced.add(i); else { if(arr[i] % 2 == 1) oddRem--; filter.add(arr[i]); } if(arr[i] <= M) { if(arr[i] % 2 == 0) evenBlacklist.add(arr[i]); else oddBlacklist.add(arr[i]); } } int nextOdd = 1 , nextEven = 2; // out.println("replace " + toBeReplaced); for(int i : toBeReplaced) { if(oddRem > 0) { while(nextOdd <= M && oddBlacklist.contains(nextOdd)) nextOdd += 2; if(nextOdd > M) { out.println(-1); return; } else arr[i] = nextOdd; nextOdd += 2; oddRem--; } else { while(nextEven <= M && evenBlacklist.contains(nextEven)) nextEven += 2; if(nextEven > M) { out.println(-1); return; } else arr[i] = nextEven; nextEven += 2; } } out.println(toBeReplaced.size()); Arrays.stream(arr).forEach(a -> out.print(a + " ")); } } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE *********************/ public static void main(String []args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); solve(in, out); in.close(); out.close(); } static class FastScanner{ BufferedReader reader; StringTokenizer st; FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;} String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble(){return Double.parseDouble(next());} char nextChar() {return next().charAt(0);} int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;} long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;} int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;} long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;} void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}} } /************************ TEMPLATE ENDS HERE ************************/ }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
00afd21b2d2bc0126c6e85bffbf63df5
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
//package taz; import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.util.ArrayList; import java.io.InputStream; public class Taz { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { int maxn = 200001; int N; int M; int even; int odd; int mineven = 2; int minodd = 1; int change; int[] a = new int[maxn]; ArrayList<Integer> update = new ArrayList<>(); TreeSet<Integer> vis = new TreeSet<Integer>(); public void solve(int testNumber, InputReader in, OutputWriter out) { N = in.readInt(); M = in.readInt(); for (int i = 0; i < N; ++i) { a[i] = in.readInt(); if (a[i] % 2 == 0) { if (even == N / 2 || vis.contains(a[i])) { update.add(i); } else { even++; } } else { if (odd == N / 2 || vis.contains(a[i])) { update.add(i); } else { odd++; } } vis.add(a[i]); } for (int i = 0; i < update.size(); i++) { if (even < odd) { while (vis.contains(mineven)) { mineven += 2; } if (mineven > M) { out.print(-1); return; } vis.add(mineven); change++; even++; a[update.get(i)] = mineven; } else { while (vis.contains(minodd)) { minodd += 2; } if (minodd > M) { out.print(-1); return; } vis.add(minodd); change++; odd++; a[update.get(i)] = minodd; } } if (change > M || even != N / 2 || odd != N / 2) { out.print(-1); return; } out.printLine(change); for (int i = 0; i < N; i++) { out.print(a[i] + " "); } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void close() { writer.close(); } public void print(int i) { writer.print(i); } public void printLine(int i) { writer.println(i); } } 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 readInt() { 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
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
03f4094c86a0f2b7917a1c490f0187a4
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
// package codeforces.cf3xx.cf386.div2; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Map; public class E { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[n][2]; for (int i = 0; i < n ; i++) { a[i][0] = in.nextInt(); a[i][1] = i; } Arrays.sort(a, (u, v) -> u[0] - v[0]); m = Math.min(m, 400000); int[][] available = new int[2][800000]; int[] an = new int[2]; int li = 1; for (int i = 0 ; i < n ; i++) { int A = a[i][0]; while (li <= m && li < A) { int eo = li%2; available[eo][an[eo]++] = li; li++; } if (li <= m && li == A) { li++; } } while (li <= m) { int eo = li%2; available[eo][an[eo]++] = li; li++; } int[] eocnt = new int[2]; for (int i = 0; i < n; i++) { eocnt[a[i][0]%2]++; } boolean possible = true; int changed = 0; int[] ai = new int[2]; for (int i = 0 ; i < n ; ) { int j = i; while (j < n && a[i][0] == a[j][0]) { j++; } int my = a[i][0]%2; int ot = 1-my; int ef = i+1; while (ef < j) { int want = eocnt[my] <= eocnt[ot] ? my : ot; if (ai[want] < an[want]) { changed++; eocnt[my]--; eocnt[want]++; a[ef][0] = available[want][ai[want]++]; } else { possible = false; } ef++; } i = j; } if (eocnt[0] != eocnt[1]) { int want = eocnt[0] < eocnt[1] ? 0 : 1; int my = 1-want; for (int i = 0; i < n ; i++) { if (a[i][0] % 2 == want) { continue; } if (ai[want] < an[want]) { changed++; eocnt[my]--; eocnt[want]++; a[i][0] = available[want][ai[want]++]; } else { possible = false; } if (eocnt[0] == eocnt[1]) { break; } } } if (!possible) { out.println(-1); } else { Arrays.sort(a, (u, v) -> u[1] - v[1]); StringBuilder line = new StringBuilder(); for (int i = 0; i < n ; i++) { line.append(' ').append(a[i][0]); } out.println(changed); out.println(line.substring(1)); } out.flush(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int[] nextInts(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } private int[][] nextIntTable(int n, int m) { int[][] ret = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ret[i][j] = nextInt(); } } return ret; } private long[] nextLongs(int n) { long[] ret = new long[n]; for (int i = 0; i < n; i++) { ret[i] = nextLong(); } return ret; } private long[][] nextLongTable(int n, int m) { long[][] ret = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ret[i][j] = nextLong(); } } return ret; } private double[] nextDoubles(int n) { double[] ret = new double[n]; for (int i = 0; i < n; i++) { ret[i] = nextDouble(); } return ret; } private int next() { 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 char nextChar() { int c = next(); while (isSpaceChar(c)) c = next(); if ('a' <= c && c <= 'z') { return (char) c; } if ('A' <= c && c <= 'Z') { return (char) c; } throw new InputMismatchException(); } public String nextToken() { int c = next(); while (isSpaceChar(c)) c = next(); StringBuilder res = new StringBuilder(); do { res.append((char) c); c = next(); } while (!isSpaceChar(c)); return res.toString(); } public int nextInt() { int c = next(); while (isSpaceChar(c)) c = next(); int sgn = 1; if (c == '-') { sgn = -1; c = next(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c-'0'; c = next(); } while (!isSpaceChar(c)); return res*sgn; } public long nextLong() { int c = next(); while (isSpaceChar(c)) c = next(); long sgn = 1; if (c == '-') { sgn = -1; c = next(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c-'0'; c = next(); } while (!isSpaceChar(c)); return res*sgn; } public double nextDouble() { return Double.valueOf(nextToken()); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
8f74e6b715c6db234f641b691f9c5091
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
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.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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); if (n % 2 == 1) { out.print(-1); return; } int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = in.nextInt(); HashSet<Integer> st = new HashSet<>(); int res = 0, even = 0, odd = 0; for (int i = 0; i < n; ++i) { if (st.contains(a[i])) { a[i] = -1; ++res; } else { st.add(a[i]); if (a[i] % 2 == 0) ++even; else ++odd; } } int curOdd = 1, curEven = 2; for (int i = 0; i < n; ++i) { if (a[i] > 0) { if (a[i] % 2 == 0 && even > n / 2) { a[i] = -1; ++res; --even; } else if (a[i] % 2 == 1 && odd > n / 2) { a[i] = -1; ++res; --odd; } } } for (int i = 0; i < n; ++i) if (a[i] == -1) { if (even < odd) { while (st.contains(curEven)) curEven += 2; if (curEven > m) { out.print(-1); return; } a[i] = curEven; curEven += 2; ++even; } else { while (st.contains(curOdd)) curOdd += 2; if (curOdd > m) { out.print(-1); return; } a[i] = curOdd; curOdd += 2; ++odd; } } if (odd != even) { out.print(-1); return; } out.println(res); for (int i = 0; i < n; ++i) { if (i > 0) out.print(' '); out.print(a[i]); } out.println(); } } 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
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
e2b4329382863fa218c126f2c61ef988
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; /* public class _746E { } */ public class _746E { public void solve() throws FileNotFoundException { InputStream inputStream = System.in; InputHelper ih = new InputHelper(inputStream); PrintStream out = System.out; // actual solution int n = ih.readInteger(); int m = ih.readInteger(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = ih.readInteger(); } Set<Integer> es = new HashSet<Integer>(); Set<Integer> os = new HashSet<Integer>(); List<Integer> tbci = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { if ((a[i] & 1) == 0) { if (es.contains(a[i])) { tbci.add(i); } else { if (es.size() < n / 2) es.add(a[i]); else { tbci.add(i); } } } else { if (os.contains(a[i])) { tbci.add(i); } else { if (os.size() < n / 2) os.add(a[i]); else { tbci.add(i); } } } } int orn = 1; int ern = 2; int j = 0; for (int i = 0; i < (n / 2 - os.size()); i++) { while (os.contains(orn) && orn <= m) { orn += 2; } if (orn > m) { System.out.println("-1"); return; } a[tbci.get(j++)] = orn; orn += 2; } for (int i = 0; i < (n / 2 - es.size()); i++) { while (es.contains(ern) && ern <= m) { ern += 2; } if (ern > m) { System.out.println("-1"); return; } a[tbci.get(j++)] = ern; ern += 2; } System.out.println(tbci.size()); for (int i = 0; i < n; i++) { System.out.print(a[i] + " "); } // end here } public static void main(String[] args) throws FileNotFoundException { (new _746E()).solve(); } class InputHelper { StringTokenizer tokenizer = null; private BufferedReader bufferedReader; public InputHelper(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader( inputStream); bufferedReader = new BufferedReader(inputStreamReader, 16384); } public String read() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = bufferedReader.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public Integer readInteger() { return Integer.parseInt(read()); } public Long readLong() { return Long.parseLong(read()); } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
e3bd8a0c66bb5f2f34f8a4aadf2bfe7c
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; 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<<26).start(); } public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); if((n & 1) == 1) { w.print("-1"); w.close(); return; } int a[] = new int[n]; HashMap<Integer, Integer> map = new HashMap<>(); int cntodd = 0, cnteven = 0; int uniodd = 0, unieven = 0; ArrayList<Integer> index = new ArrayList<>(); for(int i = 0; i < n; ++i) { a[i] = sc.nextInt(); if(map.get(a[i]) == null) { map.put(a[i], i); if((a[i] & 1) == 0) unieven++; else uniodd++; if(a[i] <= m) { if((a[i] & 1) == 0) cnteven++; else cntodd++; } } else index.add(i); } for(int j : map.keySet()) { if(uniodd > n / 2) { if((j & 1) == 1) { index.add(map.get(j)); uniodd--; } } else if(unieven > n / 2) { if((j & 1) == 0) { index.add(map.get(j)); unieven--; } } else break; } if(uniodd == n / 2) cntodd = 0; if(unieven == n / 2) cnteven = 0; int reqodd = n / 2 - uniodd + cntodd, reqeven = n / 2 - unieven + cnteven; if(2 * reqodd - 1 > m || 2 * reqeven > m) { w.print("-1"); w.close(); return; } reqodd -= cntodd; reqeven -= cnteven; w.println(index.size()); int point = 0; for(int i = 1;;i += 2) { if(reqodd == 0) break; if(map.get(i) == null) { a[index.get(point++)] = i; reqodd--; } } for(int i = 2;;i += 2) { if(reqeven == 0) break; if(map.get(i) == null) { a[index.get(point++)] = i; reqeven--; } } for(int i = 0; i < n; ++i) w.print(a[i] + " "); w.close(); } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
d48e2f11f4976272fc776f6b387c7208
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.util.*; import java.io.*; public class E { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] L = br.readLine().split(" "); int N = Integer.parseInt(L[0]); int M = Integer.parseInt(L[1]); int eS = 2; int oS = 1; int dups = 0; TreeSet<Integer> oHand = new TreeSet<>(); TreeSet<Integer> eHand = new TreeSet<>(); Map<Integer, Integer> loc = new HashMap<>(); L = br.readLine().split(" "); int[] out = new int[N]; int idx = 0; for (String s : L) { int n = Integer.parseInt(s); out[idx] = 0; if (n % 2 == 0) { if (eHand.contains(n)) { dups++; } else { eHand.add(n); out[idx] = n; loc.put(n, idx); } } else { if (oHand.contains(n)) { dups++; } else { oHand.add(n); out[idx] = n; loc.put(n, idx); } } idx++; } idx = 0; if (eHand.size() + dups < N/2) { int add = N/2 - eHand.size() - dups; for (int i = 0; i < add; i++) { dups++; int rem = oHand.last(); oHand.remove(rem); out[loc.get(rem)] = 0; loc.remove(rem); } } else if (oHand.size() + dups < N/2) { int add = N/2 - oHand.size() - dups; for (int i = 0; i < add; i++) { dups++; int rem = eHand.last(); eHand.remove(rem); out[loc.get(rem)] = 0; loc.remove(rem); } } for (int i = 0; i < dups; i++) { if (oHand.size() > eHand.size()) { // insert to even. while(true) { if (eS > M) { System.out.println("-1"); return; } if (!eHand.contains(eS)) { eHand.add(eS); while(out[idx] > 0) { idx++;} out[idx] = eS; idx++; break; } eS += 2; } } else { while(true) { if (oS > M) { System.out.println("-1"); return; } if (!oHand.contains(oS)) { while(out[idx] > 0) { idx++;} out[idx] = oS; idx++; oHand.add(oS); break; } oS += 2; } } } PrintWriter o = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); o.println(dups); StringBuilder sb = new StringBuilder(); for (int i = 0; i < N; i++) { sb.append(out[i]); if (i + 1 < N) sb.append(" "); } o.println(sb); o.flush(); } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
316ed5678cba18db53cb02515a550624
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class c386E { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); Card[] cards = new Card[n]; Card[] sort = new Card[n]; int odd = 0; HashSet<Integer> used = new HashSet<Integer>(); for(int i=0; i<n; i++){ cards[i] = new Card(i, in.nextInt()); sort[i] = cards[i]; used.add(cards[i].val); if(cards[i].val%2==1) odd++; } int even = n-odd; Arrays.sort(sort, new CardCompare()); int nextO = 1; int nextE = 2; int extraEven = Math.max(even-(n/2), 0); int extraOdd = Math.max(odd-(n/2), 0); int change = 0; int prev = sort[0].val; for(int i=1; i<n; i++){ if(sort[i].val == prev){ change++; if(sort[i].val%2==1){ if(extraOdd > 0){ //replace with even while(used.contains(nextE)){ nextE+=2; } if(nextE > m){ System.out.println(-1); return; } sort[i].val = nextE; nextE+=2; extraOdd--; } else{ //replace with odd while(used.contains(nextO)){ nextO+=2; } if(nextO > m){ System.out.println(-1); return; } sort[i].val = nextO; nextO+=2; } } else{ if(extraEven > 0){ //replace with odd while(used.contains(nextO)){ nextO+=2; } if(nextO > m){ System.out.println(-1); return; } sort[i].val = nextO; nextO+=2; extraEven--; } else{ //replace with even while(used.contains(nextE)){ nextE+=2; } if(nextE > m){ System.out.println(-1); return; } sort[i].val = nextE; nextE+=2; } } } else{ prev = sort[i].val; } } change += extraOdd + extraEven; int ind = 0; while(extraEven > 0){ if(sort[ind].val %2 == 0){ while(used.contains(nextO)){ nextO+=2; } if(nextO > m){ System.out.println(-1); return; } sort[ind].val = nextO; nextO+=2; extraEven--; } ind++; } while(extraOdd > 0){ if(sort[ind].val %2 == 1){ while(used.contains(nextE)){ nextE+=2; } if(nextE > m){ System.out.println(-1); return; } sort[ind].val = nextE; nextE+=2; extraOdd--; } ind++; } System.out.println(change); StringBuilder sb = new StringBuilder(); for(int i=0; i<n; i++){ sb.append(cards[i].val); sb.append(' '); } System.out.println(sb.toString()); } private static class Card{ int ind; int val; public Card(int ind, int val){ this.ind = ind; this.val = val; } } private static class CardCompare implements Comparator<Card>{ public int compare(Card c1, Card c2){ if(c1.val < c2.val) return -1; if(c1.val > c2.val) return 1; return 0; } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
f1c6ac2615c046618ec4eb5c6a9d2e35
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.*; import java.util.*; public class E { public static void main(String[] args) throws Exception { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] split = f.readLine().split("\\s+"); int n = Integer.parseInt(split[0]), m = Integer.parseInt(split[1]); int[] a = new int[n]; int print[] = new int[n], res = 0; int nextOdd = 1, nextEven = 2; TreeSet<Integer> contains = new TreeSet<>(), in = new TreeSet<>(); int evenCount = 0, oddCount = 0; split = f.readLine().split("\\s+"); for(int i = 0; i < n; i++) { a[i] = Integer.parseInt(split[i]); in.add(a[i]); if(a[i]%2==0) evenCount++; else oddCount++; } ArrayList<Integer> indices = new ArrayList<>(); // System.out.println(evenCount + " : " + oddCount); boolean bad = false; for(int i = 0; i < n; i++) { if(contains.contains(a[i])) { //duplicate number. if(a[i]%2==0) { //even if(evenCount > oddCount) { //change it to the next available odd number while(in.contains(nextOdd)) nextOdd += 2; if(nextOdd > m) { bad = true; break; } oddCount++; evenCount--; print[i] = nextOdd; indices.add(i); in.add(nextOdd); } else { //change it to the next available even number while(in.contains(nextEven)) nextEven += 2; if(nextEven > m) { bad = true; break; } print[i] = nextEven; indices.add(i); in.add(nextEven); } } else { //odd if(evenCount < oddCount) { //change it to the next available even number while(in.contains(nextEven)) nextEven += 2; if(nextEven > m) { bad = true; break; } evenCount++; oddCount--; print[i] = nextEven; indices.add(i); in.add(nextEven); } else { //change it to the next available odd number while(in.contains(nextOdd)) nextOdd += 2; if(nextOdd > m) { bad = true; break; } print[i] = nextOdd; indices.add(i); in.add(nextOdd); } } } contains.add(a[i]); } // System.out.println(indices.toString() + " " + bad); // System.out.println(evenCount + " " + oddCount); while(!indices.isEmpty() && oddCount != evenCount) { int idx = indices.remove(0); // System.out.println("P " + print[idx]); if(print[idx]%2==0) { //changed to an even number if(evenCount > oddCount) { //change it to an odd number while(in.contains(nextOdd)) nextOdd += 2; if(nextOdd > m) { bad = true; break; } evenCount--; oddCount++; print[idx] = nextOdd; in.add(nextOdd); } } else { //changed to an odd number if(evenCount < oddCount) { //change it to an even number while(in.contains(nextEven)) nextEven += 2; if(nextEven > m) { bad = true; break; } evenCount++; oddCount--; print[idx] = nextEven; in.add(nextEven); } } } for(int i = 0; i < n && evenCount != oddCount; i++) { if(print[i] == 0) { //unchanged element if(a[i]%2==0 && evenCount > oddCount) { while(in.contains(nextOdd)) nextOdd += 2; if(nextOdd > m) { bad = true; break; } oddCount++; evenCount--; print[i] = nextOdd; in.add(nextOdd); } else if(a[i]%2==1 && oddCount > evenCount) { while(in.contains(nextEven)) nextEven += 2; if(nextEven > m) { bad = true; break; } evenCount++; oddCount--; print[i] = nextEven; in.add(nextEven); } } } if(evenCount != oddCount) bad = true; if(bad) { System.out.println(-1); } else { for(int i = 0; i < n; i++) { if(print[i] == 0) print[i] = a[i]; else { res++; } } out.println(res); for(int i = 0; i < n; i++) { out.printf("%d ", print[i]); } out.print("\n"); } out.close(); } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
e55a281b2640a74949a39a0bd427f1db
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.TreeMap; import java.util.TreeSet; public class Q1 { static long MOD = 1000000007; static boolean b[]; public static void main(String[] args) throws IOException { // TODO Auto-generated method stub FasterScanner sc = new FasterScanner(); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); int n = sc.nextInt() , m =sc.nextInt(); int arr[] = sc.nextIntArray(n); int odd = 1, even = 2; HashSet<Integer> hs1 = new HashSet<>(); HashSet<Integer> hs2 = new HashSet<>(); int g = 0, h= 0; for(int i = 0; i<n;i++){ if(arr[i]%2==0){ if(g<n/2) hs1.add(arr[i]); g++; } else if(h<n/2){ hs2.add(arr[i]); h++; } } long ans = 0, x = hs1.size(), y = hs2.size(); long cnt1 = (n/2)-x, cnt2 = ((n/2)-y); TreeSet<Integer> hs = new TreeSet<>(); //System.out.println(cnt1+" "+cnt2); while(cnt1>0 && even<=m){ if(hs1.contains(even)) even+=2; else{ hs.add(even); cnt1--; even+=2; } } while(cnt2>0 && odd<=m){ if(hs2.contains(odd)) odd+=2; else{ hs.add(odd); cnt2--; odd+=2; } } // System.out.println(hs); if(cnt1 == 0&&cnt2==0){ System.out.println(n-x-y); for(int i = 0;i<n;i++){ if(hs1.contains(arr[i])){ hs1.remove(arr[i]); } else if(hs2.contains(arr[i])) hs2.remove(arr[i]); else{ arr[i] = hs.pollFirst(); } System.out.print(arr[i]+" "); } } else System.out.println("-1"); log.close(); } public static void seive(long n){ b = new boolean[(int) (n+1)]; Arrays.fill(b, true); for(int i = 2;i<=n;i++){ if(b[i]){ for(int p = 2*i;p<=n;p++){ b[p] = false; } } } } static long modInverse(long a, long mOD2){ return power(a, mOD2-2, mOD2); } 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; return (y%2 == 0)? p : (x * p) % m; } static long d,x,y; public static void extendedEuclidian(long a, long b){ if(b == 0) { d = a; x = 1; y = 0; } else { extendedEuclidian(b, a%b); int temp = (int) x; x = y; y = temp - (a/b)*y; } } public static long inverseModulo(long n){ return powerModulo(n, MOD-2); } public static long gcd(long n, long m){ if(m!=0) return gcd(m,n%m); else return n; } public static long powerModulo(long x, long y){ long ans = 1; while(y>0){ if(y%2==1){ ans = (ans%MOD*x%MOD)%MOD; y--; } else{ x = (x%MOD*x%MOD)%MOD; y/=2; } } return ans; } static class Pair implements Comparable<Pair> { int u; int v; public Pair(){ } public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31*hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return (u == other.u && v == other.v); } public int compareTo(Pair other) { return Integer.compare(u, other.u) != 0 ? (Integer.compare(u, other.u)) : (Integer.compare(v, other.v)); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { 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 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 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 int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
21a3a411e671cc6ab9deab4b6eb857ff
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.*; import java.util.*; public final class round_386_e { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static Random rnd=new Random(); static ArrayDeque<Node>[] al1,al2; static Map<Integer,Integer> m1=new HashMap<>(); static void put(int idx) { m1.put(idx,1); } static boolean yes(int idx) { return (m1.get(idx)!=null); } @SuppressWarnings("unchecked") public static void main(String args[]) throws Exception { int n=sc.nextInt(),m=sc.nextInt();Node[] a=new Node[n];al1=new ArrayDeque[2];al2=new ArrayDeque[2]; for(int i=0;i<2;i++) { al1[i]=new ArrayDeque<Node>();al2[i]=new ArrayDeque<Node>(); } for(int i=0;i<n;i++) { a[i]=new Node(i,sc.nextInt()); } Arrays.sort(a);int prev=-1; for(int i=0;i<n;i++) { if(a[i].val==prev) { //extra al1[a[i].val%2].add(new Node(a[i].idx,a[i].val)); } else { //non -extra al2[a[i].val%2].add(new Node(a[i].idx,a[i].val)); } prev=a[i].val; } //out.println(al1[0].size()+" "+al2[0].size()+" "+al1[1].size()+" "+al2[1].size()); while(al1[0].size()+al2[0].size()<n/2) { if(al1[1].size()>0) { Node curr=al1[1].removeFirst(); al1[0].add(curr); } else { Node curr=al2[1].removeFirst(); al1[0].add(curr); } } while(al1[1].size()+al2[1].size()<n/2) { if(al1[0].size()>0) { Node curr=al1[0].removeFirst(); al1[1].add(curr); } else { Node curr=al2[0].removeFirst(); al1[1].add(curr); } } //out.println(al1[0].size()+" "+al2[0].size()+" "+al1[1].size()+" "+al2[1].size()); for(int i=0;i<2;i++) { for(Node x:al2[i]) { put(x.val); } } int last=2;int cnt=0;boolean ans=true; while(al1[0].size()>0) { Node curr=al1[0].removeFirst();boolean get=false;cnt++; for(int i=last;i<=m;i+=2) { if(!yes(i)) { get=true;last=i;break; } } if(get) { put(last);al2[0].add(new Node(curr.idx,last));last+=2; } else { ans=false; } } last=1; while(al1[1].size()>0) { Node curr=al1[1].removeFirst();boolean get=false;cnt++; for(int i=last;i<=m;i+=2) { if(!yes(i)) { get=true;last=i;break; } } if(get) { put(last);al2[1].add(new Node(curr.idx,last));last+=2; } else { ans=false; } } if(ans) { int[] res=new int[n]; for(int i=0;i<2;i++) { for(Node x:al2[i]) { res[x.idx]=x.val; } } out.println(cnt); for(int x:res) { out.print(x+" "); } out.println(""); } else { out.println(-1); } out.close(); } } class Node implements Comparable<Node> { int idx,val; public Node(int idx,int val) { this.idx=idx;this.val=val; } public int compareTo(Node x) { return Integer.compare(this.val,x.val); } } 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 String next() throws Exception { return nextToken().toString(); } 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
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
cbbbd9ebb7ba90326437bcd151c407ac
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.io.BufferedWriter; import java.io.IOException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin ([email protected]) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { private int n; private int m; private int[] a; private int oddAt = 1; private int evenAt = 2; private IntSet used = new IntHashSet(); public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.readInt(); m = in.readInt(); a = IOUtils.readIntArray(in, n); Pair<Integer, int[]> solve = solve(); if (solve == null) { out.print(-1); } else { out.printLine(solve.first); out.print(solve.second); } } private Pair<Integer, int[]> solve() { int even = 0, odd = 0; IntList needRemove = new IntArrayList(n); for (int i = 0; i < n; i++) { int elem = a[i]; if (!used.contains(elem)) { used.add(elem); if (elem % 2 == 0) { even++; } else { odd++; } } else { needRemove.add(i); } } int ans = needRemove.size(); for (int remIdx : needRemove) { if (even > odd) { int nextOdd = nextOdd(); if (nextOdd == -1) { return null; } a[remIdx] = nextOdd; odd++; } else { int nextEven = nextEven(); if (nextEven == -1) { return null; } a[remIdx] = nextEven; even++; } } int iterationsLeft = Math.abs(even - odd) / 2; ans += iterationsLeft; int removeMod = even > odd ? 0 : 1; int iters = Math.abs(even - odd) / 2; for (int i = 0, at = 0; i < iters; i++) { while (at < a.length && a[at] % 2 != removeMod) { at++; } int next = removeMod == 0 ? nextOdd() : nextEven(); if (next == -1) { return null; } a[at] = next; } return Pair.makePair(ans, a); } private int nextEven() { while (used.contains(evenAt)) { evenAt += 2; } if (evenAt > m) { return -1; } used.add(evenAt); return evenAt; } private int nextOdd() { while (used.contains(oddAt)) { oddAt += 2; } if (oddAt > m) { return -1; } used.add(oddAt); return oddAt; } } static interface IntSet extends IntCollection { } static interface IntCollection extends IntStream { public int size(); default public void add(int value) { throw new UnsupportedOperationException(); } default public IntCollection addAll(IntStream values) { for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) { add(it.value()); } return this; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void close() { writer.close(); } public void print(int i) { writer.print(i); } public void printLine(int i) { writer.println(i); } } static class IntArrayList extends IntAbstractStream implements IntList { private int size; private int[] data; public IntArrayList() { this(3); } public IntArrayList(int capacity) { data = new int[capacity]; } public IntArrayList(IntCollection c) { this(c.size()); addAll(c); } public IntArrayList(IntStream c) { this(); if (c instanceof IntCollection) { ensureCapacity(((IntCollection) c).size()); } addAll(c); } public IntArrayList(IntArrayList c) { size = c.size(); data = c.data.clone(); } public IntArrayList(int[] arr) { size = arr.length; data = arr.clone(); } public int size() { return size; } public int get(int at) { if (at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size); } return data[at]; } private void ensureCapacity(int capacity) { if (data.length >= capacity) { return; } capacity = Math.max(2 * data.length, capacity); data = Arrays.copyOf(data, capacity); } public void addAt(int index, int value) { ensureCapacity(size + 1); if (index > size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size) { System.arraycopy(data, index, data, index + 1, size - index); } data[index] = value; size++; } public void removeAt(int index) { if (index >= size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size - 1) { System.arraycopy(data, index + 1, data, index, size - index - 1); } size--; } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void addAt(int index, int value); public abstract void removeAt(int index); default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } default public void add(int value) { addAt(size(), value); } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } } static interface IntReversableCollection extends IntCollection { } static class Pair<U, V> implements Comparable<Pair<U, V>> { public final U first; public final V second; public static <U, V> Pair<U, V> makePair(U first, V second) { return new Pair<U, V>(first, second); } private Pair(U first, V second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pair pair = (Pair) o; return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null); } public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } public String toString() { return "(" + first + "," + second + ")"; } @SuppressWarnings({"unchecked"}) public int compareTo(Pair<U, V> o) { int value = ((Comparable<U>) first).compareTo(o.first); if (value != 0) { return value; } return ((Comparable<V>) second).compareTo(o.second); } } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } static class IntHashSet extends IntAbstractStream implements IntSet { private static final Random RND = new Random(); private static final int[] SHIFTS = new int[4]; private static final byte PRESENT_MASK = 1; private static final byte REMOVED_MASK = 2; private int size; private int realSize; private int[] values; private byte[] present; private int step; private int ratio; static { for (int i = 0; i < 4; i++) { SHIFTS[i] = RND.nextInt(31) + 1; } } public IntHashSet() { this(3); } public IntHashSet(int capacity) { capacity = Math.max(capacity, 3); values = new int[capacity]; present = new byte[capacity]; ratio = 2; initStep(capacity); } public IntHashSet(IntCollection c) { this(c.size()); addAll(c); } public IntHashSet(int[] arr) { this(new IntArray(arr)); } private void initStep(int capacity) { step = RND.nextInt(capacity - 2) + 1; while (IntegerUtils.gcd(step, capacity) != 1) { step++; } } public IntIterator intIterator() { return new IntIterator() { private int position = size == 0 ? values.length : -1; public int value() throws NoSuchElementException { if (position == -1) { advance(); } if (position >= values.length) { throw new NoSuchElementException(); } if ((present[position] & PRESENT_MASK) == 0) { throw new IllegalStateException(); } return values[position]; } public boolean advance() throws NoSuchElementException { if (position >= values.length) { throw new NoSuchElementException(); } position++; while (position < values.length && (present[position] & PRESENT_MASK) == 0) { position++; } return isValid(); } public boolean isValid() { return position < values.length; } public void remove() { if ((present[position] & PRESENT_MASK) == 0) { throw new IllegalStateException(); } present[position] = REMOVED_MASK; } }; } public int size() { return size; } public void add(int value) { ensureCapacity((realSize + 1) * ratio + 2); int current = getHash(value); while (present[current] != 0) { if ((present[current] & PRESENT_MASK) != 0 && values[current] == value) { return; } current += step; if (current >= values.length) { current -= values.length; } } while ((present[current] & PRESENT_MASK) != 0) { current += step; if (current >= values.length) { current -= values.length; } } if (present[current] == 0) { realSize++; } present[current] = PRESENT_MASK; values[current] = value; size++; } private int getHash(int value) { int hash = IntHash.hash(value); int result = hash; for (int i : SHIFTS) { result ^= hash >> i; } result %= values.length; if (result < 0) { result += values.length; } return result; } private void ensureCapacity(int capacity) { if (values.length < capacity) { capacity = Math.max(capacity * 2, values.length); rebuild(capacity); } } private void rebuild(int capacity) { initStep(capacity); int[] oldValues = values; byte[] oldPresent = present; values = new int[capacity]; present = new byte[capacity]; size = 0; realSize = 0; for (int i = 0; i < oldValues.length; i++) { if ((oldPresent[i] & PRESENT_MASK) == PRESENT_MASK) { add(oldValues[i]); } } } public boolean contains(int value) { int current = getHash(value); while (present[current] != 0) { if (values[current] == value && (present[current] & PRESENT_MASK) != 0) { return true; } current += step; if (current >= values.length) { current -= values.length; } } return false; } } static class IntHash { private IntHash() { } public static int hash(int c) { return c; } } static class IntegerUtils { public static int gcd(int a, int b) { a = Math.abs(a); b = Math.abs(b); while (b != 0) { int temp = a % b; a = b; b = temp; } return a; } } 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 readInt() { 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); } } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } default public boolean contains(int value) { for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (it.value() == value) { return true; } } return false; } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
34d48ff88dbb21cc0cc670849fd81dc2
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin ([email protected]) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { int maxn = 200001; int N; int M; int even; int odd; int mineven = 2; int minodd = 1; int change; int[] a = new int[maxn]; ArrayList<Integer> update = new ArrayList<>(); TreeSet<Integer> vis = new TreeSet<Integer>(); public void solve(int testNumber, InputReader in, OutputWriter out) { N = in.readInt(); M = in.readInt(); for (int i = 0; i < N; ++i) { a[i] = in.readInt(); if (a[i] % 2 == 0) { if (even == N / 2 || vis.contains(a[i])) { update.add(i); } else { even++; } } else { if (odd == N / 2 || vis.contains(a[i])) { update.add(i); } else { odd++; } } vis.add(a[i]); } for (int i = 0; i < update.size(); i++) { if (even < odd) { while (vis.contains(mineven)) { mineven += 2; } if (mineven > M) { out.print(-1); return; } vis.add(mineven); change++; even++; a[update.get(i)] = mineven; } else { while (vis.contains(minodd)) { minodd += 2; } if (minodd > M) { out.print(-1); return; } vis.add(minodd); change++; odd++; a[update.get(i)] = minodd; } } if (change > M || even != N / 2 || odd != N / 2) { out.print(-1); return; } out.printLine(change); for (int i = 0; i < N; i++) { out.print(a[i] + " "); } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void close() { writer.close(); } public void print(int i) { writer.print(i); } public void printLine(int i) { writer.println(i); } } 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 readInt() { 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
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
46b3937fb30f2a0a3eec5bf1c59a6570
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.*; import java.util.*; public class c{ static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int n = ni(); int m = ni(); TreeSet<Integer> set = new TreeSet<>(); int odd = 0, even = 0; int[] a = new int[n]; for(int i = 0; i < n; ++i) { a[i]=ni(); if(set.contains(a[i])) a[i] = -1; else if(a[i] % 2 == 0){ if(even * 2 == n) a[i] = -1; else ++even; set.add(a[i]); } else { if(odd * 2 == n) a[i] = -1; else ++odd; set.add(a[i]); } } int ans = 0, curEven = 2, curOdd = 1; for(int i = 0; i < n; ++i) if(a[i] == -1) { if(even * 2 < n) { ++even; while(curEven <= m && set.contains(curEven)) curEven += 2; if(curEven > m) { ans = -1; break; } set.add(a[i] = curEven); } else { ++odd; while(curOdd <= m && set.contains(curOdd)) curOdd += 2; if(curOdd > m) { ans = -1; break; } set.add(a[i] = curOdd); } ++ans; } out.println(ans); if(ans != -1) for(int x: a) out.print(x + " "); out.flush(); } static long mod = 1000000007; static void fact(long a[]){ a[0]=1; for(int i=1;i<a.length;i++) a[i] = (i*a[i-1])%mod; } static long gcd(long a,long b){ if(b%a==0) return a; return gcd(b%a,a); } static long pow(long a,long b,long mod){ long ans=1; while(b>0){ if(b%2==1) ans = (ans*a)%mod; b=b/2; a=(a*a)%mod; } 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
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
c5beb5612d0e957a24065238219172eb
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashSet; import java.util.StringTokenizer; public class Div2_386E { public static void main(String[] args) throws IOException { new Div2_386E().execute(); } void execute() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringTokenizer inputData = new StringTokenizer(reader.readLine()); int numE = Integer.parseInt(inputData.nextToken()); int numS = Integer.parseInt(inputData.nextToken()); HashSet<Integer> used = new HashSet<Integer>(); int[] elements = new int[numE]; inputData = new StringTokenizer(reader.readLine()); reader.close(); ArrayList<Integer> unmarked = new ArrayList<Integer>(); ArrayList<Integer> eIndex = new ArrayList<Integer>(); ArrayList<Integer> oIndex = new ArrayList<Integer>(); int oCount = 0; for (int i = 0; i < numE; i++) { int next = Integer.parseInt(inputData.nextToken()); if (!used.contains(next)) { elements[i] = next; used.add(next); oCount += (next & 1); if ((next & 1) == 0) { eIndex.add(i); } else { oIndex.add(i); } } else { unmarked.add(i); } } ArrayDeque<Integer> odd = new ArrayDeque<Integer>(); ArrayDeque<Integer> even = new ArrayDeque<Integer>(); for (int i = 1; i <= Math.min(3 * numE, numS); i++) { if (!used.contains(i)) { if ((i & 1) == 0) { even.add(i); } else { odd.add(i); } } } int swapped = 0; for (int i : unmarked) { if (oCount < numE / 2) { if (odd.isEmpty()) { System.out.println(-1); return; } elements[i] = odd.removeLast(); oCount++; } else { if (even.isEmpty()) { System.out.println(-1); return; } elements[i] = even.removeLast(); } swapped++; } for (int i : eIndex) { if (oCount < numE / 2) { if ((elements[i] & 1) == 0) { if (odd.isEmpty()) { System.out.println(-1); return; } elements[i] = odd.removeLast(); swapped++; oCount++; } } else { break; } } for (int i : oIndex) { if (oCount > numE / 2) { if ((elements[i] & 1) == 1) { if (even.isEmpty()) { System.out.println(-1); return; } elements[i] = even.removeLast(); swapped++; oCount--; } } else { break; } } if (oCount != numE / 2) { System.out.println(-1); return; } printer.println(swapped); for (int i : elements) { printer.print(i + " "); } printer.println(); printer.close(); } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
805d2f761271b7c7299af74ad2272c44
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; /** * Created by nitin.s on 18/12/16. */ public class NumbersExchange { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); int n = in.nextInt(), m = in.nextInt(); int[] arr = new int[n]; int[] cnt = new int[2]; Set<Integer> myset = new HashSet<>(); Stack<Integer> st = new Stack<>(); for(int i = 0; i < n; ++i) { arr[i] = in.nextInt(); if(myset.contains(arr[i])) { st.push(i); } else { if(cnt[arr[i] % 2] >= n / 2) { st.push(i); } cnt[arr[i] % 2]++; myset.add(arr[i]); } } int answer = st.size(); for(int i = 1; i <= m && !st.isEmpty(); ++i) { if(!myset.contains(i) && cnt[i%2] < n / 2) { arr[st.pop()] = i; cnt[i%2]++; } } if(!st.isEmpty()) { System.out.println(-1); } else { System.out.println(answer); for(int i = 0; i < n; ++i) { System.out.print(arr[i] + " "); } } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream input) { br = new BufferedReader(new InputStreamReader(input)); st = new StringTokenizer(""); } public String next() throws IOException { if(st.hasMoreTokens()) { return st.nextToken(); } else { st = new StringTokenizer(br.readLine()); return next(); } } public int nextInt() throws IOException { return Integer.parseInt(next()); } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
38c5627b99e85debbf184e38aacdc08a
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.io.*; import java.util.*; /** * Created by user on 18.02.2017. */ public class Task746E { private int m; private List<Card> initCards =new ArrayList<>(); private int n; private Set<Integer> uniqueNumbers=new HashSet<>(); private int oddCount=0; private int evenCount=0; public static void main(String[] arg) { new Task746E().run(); } private void run() { FastScanner in =new FastScanner(); n = in.nextInt(); m = in.nextInt(); for (int i=0;i<n;i++){ int number=in.nextInt(); if (uniqueNumbers.add(number)){ initCards.add(new Card(i,number)); if (number%2==0){ oddCount++; }else{ evenCount++; } }else{ initCards.add(new Card(i,-1)); } } String changesCount=solve(); try (PrintWriter out = new PrintWriter(System.out)) { out.println(changesCount); if (!"-1".equals(changesCount)) { initCards.sort((Card c1, Card c2) -> Integer.compare(c1.getIndex(), c2.getIndex())); StringBuilder cards = new StringBuilder(); for (Card c : initCards) { cards.append(c.getNumber()).append(" "); } out.println(cards.toString().trim()); } } } private String solve(){ initCards.sort((Card c1,Card c2)-> Integer.compare(c1.getNumber(),c2.getNumber())); int changeCount=0; int currentEvenM=1; int currentOddM=2; for (Card card:initCards){ if (!card.isNullCard()){ if (evenCount < n/2 &&card.isEven()){ continue; } if (oddCount<n/2 && !card.isEven()){ continue; } } if (evenCount<n/2){ currentEvenM=getNextEven(card,currentEvenM); if (currentEvenM>m){ return "-1"; } changeCount++; continue; } if (oddCount<n/2){ currentOddM=getNextOdd(card,currentOddM); if (currentOddM>m){ return "-1"; } changeCount++; continue; } } return String.valueOf(changeCount); } private int getNextOdd(Card card, int currentOddM) { int i=currentOddM; while (uniqueNumbers.contains(i)){ i+=2; } if (!card.isNullCard()&&card.isEven()){ evenCount--; } card.setNumber(i); uniqueNumbers.add(i); oddCount++; return i; } private int getNextEven(Card card,int currentEvenM) { int i=currentEvenM; while (uniqueNumbers.contains(i)){ i+=2; } if (!card.isNullCard()&&!card.isEven()){ oddCount--; } card.setNumber(i); uniqueNumbers.add(i); evenCount++; return i; } private class Card{ private final int index; private int number; Card(int index,int number){ this.index = index; this.number = number; } public int getIndex() { return index; } public int getNumber() { return number; } public void setNumber(int number){ this.number=number; } public boolean isNullCard(){ return number==-1; } public boolean isEven(){ return number%2==1; } } private class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(String fileName) { try { File file = new File(fileName); br = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } @SuppressWarnings("unused") FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { //what can i do? } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } @SuppressWarnings("unused") long nextLong() { return Long.parseLong(nextToken()); } @SuppressWarnings("unused") double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
e7a9c0c72177e542f372d191194689f0
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; import java.text.DecimalFormat; import java.math.BigInteger; public class Main{ //static int d=20; static long mod=1000000007 ; static HashMap<String,Double> hm=new HashMap<>(); static ArrayList<ArrayList<Integer>> arr; static long[] dp1,dp2; static int[] a; static int[] vis,num; static long max; static int flag; public static void main(String[] args) throws IOException { boolean online =false; String fileName = "C-large-practice"; PrintWriter out; if (online) { s.init(new FileInputStream(new File(fileName + ".in"))); out= new PrintWriter(new FileWriter(fileName + "out.txt")); } else { s.init(System.in); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); } int n,m; n=s.ni(); m=s.ni(); int[] a=new int[n]; name[] b=new name[n]; for(int i=0;i<n;i++){ a[i]=s.ni(); b[i]=new name(i,a[i]); } Arrays.sort(b); int odd,even; odd=even=0; HashSet<Integer> hs=new HashSet<>(); int p1,p2; p1=1; p2=2; int k=0; for(int i=b.length-1;i>=0;i--){ int z=b[i].val; if(!hs.contains(z)){ { if(z%2==0 && even==n/2){ k++; //hs.remove(z); for(;p1<=m;p1+=2){ if(!hs.contains(p1)){ b[i].val=p1; hs.add(p1); odd++; break; } } if(b[i].val%2==0){ k=-1; break; } } else if(z%2==1 && odd==n/2){ k++; //hs.remove(z); for(;p2<=m;p2+=2){ if(!hs.contains(p2)){ b[i].val=p2; hs.add(p2); even++; break; } } if(b[i].val%2==1){ k=-1; break; } } else{ hs.add(z); if(z%2==0) even++; else odd++; } } } else{ if(even>=odd){ k++; for(;p1<=m;p1+=2){ if(!hs.contains(p1)){ b[i].val=p1; hs.add(p1); odd++; break; } } } else { k++; for(;p2<=m;p2+=2){ if(!hs.contains(p2)){ b[i].val=p2; hs.add(p2); even++; break; } } } if(b[i].val==z){ k=-1; break; } //out.println(z+" "+b[i].val); } } out.println(k); int[] c=new int[n]; for(int i=0;i<n;i++){ c[b[i].id]=b[i].val; } if(k!=-1){ for(int zz:c) out.print(zz+" "); } out.close(); } public static long find(long n,long k){ if(n==2){ if(k==1 || k==3) return 1; else return 2; } long t=pow2(2,n)-1; long z=(t+1)/2; if(k==z) return n; if(k<z) return find(n-1,k); else return find(n-1,k-z); } public static long pow2(long a,long b){ long ans=1; while(b>0){ if(b%2==1) ans=(a*ans); a=(a*a); b/=2; } return ans; } public static double pow3(double a,long b){ double ans=1; while(b>0){ if(b%2==1) ans=(a*ans); a=(a*a); b/=2; } return ans; } static class name implements Comparable<name> { int id,val; public name(int x,int y){ id=x; val=y; } public int compareTo(name o){ return id-o.id; } } public static class s { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String ns() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int ni() throws IOException { return Integer.parseInt( ns() ); } static double nd() throws IOException { return Double.parseDouble( ns() ); } static long nl() throws IOException { return Long.parseLong( ns() ); } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
2548f7aa40d1e3591ec4401c05da8c19
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
/* * Code Author: Akshay Miterani * DA-IICT */ import java.io.*; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.*; public class Main { static double eps=(double)1e-6; static long mod=(int)1e9+7; private static final long INF = 1000000000_000000L; public static void main(String args[]) throws FileNotFoundException{ InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); //----------My Code---------- int n=in.nextInt(); int m=in.nextInt(); TreeSet<Integer> even=new TreeSet<>(); TreeSet<Integer> odd=new TreeSet<>(); HashMap<Integer,Integer> original=new HashMap<>(); for(int i=0;i<n;i++){ int x=in.nextInt(); if(x%2==0){ even.add(x); } else{ odd.add(x); } original.put(x,i); } if(n%2==1){ out.println("-1"); } else{ int o=1,e=2; while(odd.size()>n/2){ odd.remove(odd.first()); } while(even.size()>n/2){ even.remove(even.first()); } while(o<=m && odd.size()<n/2){ odd.add(o); o+=2; } while(e<=m && even.size()<n/2){ even.add(e); e+=2; } if(odd.size()==even.size() && even.size()==n/2){ int count=0; for(int x:odd) if(!original.containsKey(x)) count++; for(int x:even) if(!original.containsKey(x)) count++; out.println(count); int ans[]=new int[n+5]; for(int x:odd) if(original.containsKey(x)) ans[original.get(x)]=x; for(int x:even) if(original.containsKey(x)) ans[original.get(x)]=x; int ptr=0; for(int x:odd){ while(ans[ptr]!=0) ptr++; if(!original.containsKey(x)){ ans[ptr]=x; } } for(int x:even){ while(ans[ptr]!=0) ptr++; if(!original.containsKey(x)){ ans[ptr]=x; } } for(int i=0;i<n;i++){ out.print(ans[i]+" "); } out.println(); } else{ out.println("-1"); } } out.close(); //---------------The End------------------ } static long modulo(long a,long b,long c) { long x=1; long y=a; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine(){ String fullLine=null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine=reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } 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 long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
38fc20706afb5ce1a5415f6feb85e868
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
/* * Code Author: Akshay Miterani * DA-IICT */ import java.io.*; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.*; public class Main { static double eps=(double)1e-6; static long mod=(int)1e9+7; private static final long INF = 1000000000_000000L; public static void main(String args[]) throws FileNotFoundException{ InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); //----------My Code---------- int n=in.nextInt(); int m=in.nextInt(); TreeSet<Integer> even=new TreeSet<>(); TreeSet<Integer> odd=new TreeSet<>(); HashMap<Integer,Integer> original=new HashMap<>(); for(int i=0;i<n;i++){ int x=in.nextInt(); if(x%2==0){ even.add(x); } else{ odd.add(x); } original.put(x,i); } if(n%2==1){ out.println("-1"); } else{ int o=1,e=2; while(odd.size()>n/2){ odd.remove(odd.first()); } while(even.size()>n/2){ even.remove(even.first()); } while(o<=m && odd.size()<n/2){ odd.add(o); o+=2; } while(e<=m && even.size()<n/2){ even.add(e); e+=2; } if(odd.size()==even.size() && even.size()==n/2){ int count=0; for(int x:odd) if(!original.containsKey(x)) count++; for(int x:even) if(!original.containsKey(x)) count++; out.println(count); int ans[]=new int[n+5]; for(int x:odd) if(original.containsKey(x)) ans[original.get(x)]=x; for(int x:even) if(original.containsKey(x)) ans[original.get(x)]=x; int ptr=0; for(int x:odd){ while(ans[ptr]!=0) ptr++; if(!original.containsKey(x)){ ans[ptr]=x; } } for(int x:even){ while(ans[ptr]!=0) ptr++; if(!original.containsKey(x)){ ans[ptr]=x; } } for(int i=0;i<n;i++){ out.print(ans[i]+" "); } out.println(); } else{ out.println("-1"); } } out.close(); //---------------The End------------------ } static long modulo(long a,long b,long c) { long x=1; long y=a; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine(){ String fullLine=null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine=reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } 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 long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
158aa9cfbfc04dd4d6fe9d2feb69e326
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } void work() { int n=in.nextInt(); if(n%2==1) { out.println(-1); return; } int m=in.nextInt(); HashSet<Integer> odd=new HashSet<>(); HashSet<Integer> even=new HashSet<>(); HashSet<Integer> set1=new HashSet<>(); HashSet<Integer> set2=new HashSet<>(); for(int i=1;i<=Math.min(m, n);i++) { if(i%2==1) { set1.add(i); }else { set2.add(i); } } int[] A=new int[n]; for(int i=0;i<n;i++) { int a=in.nextInt(); if(a%2==1&&odd.size()<n/2&&!odd.contains(a)) { A[i]=a; odd.add(a); set1.remove(a); } if(a%2==0&&even.size()<n/2&&!even.contains(a)) { A[i]=a; even.add(a); set2.remove(a); } } int r1=n/2-odd.size(); int r2=n/2-even.size(); if(r1>set1.size()||r2>set2.size()) { out.println(-1); return; } LinkedList<Integer> queue1=new LinkedList<>(set1); LinkedList<Integer> queue2=new LinkedList<>(set2); for(int i=0,p=0;i<n&&p<r1;i++) { if(A[i]==0) { A[i]=queue1.poll(); p++; } } for(int i=0,p=0;i<n&&p<r2;i++) { if(A[i]==0) { A[i]=queue2.poll(); p++; } } out.println(r1+r2); for(int i=0;i<n;i++) { out.print(A[i]+" "); } } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(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()); } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
d718c074ea907c140786e4876b74ec43
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } void work() { int n=in.nextInt(); if(n%2==1) { out.println(-1); return; } int m=in.nextInt(); HashSet<Integer> odd=new HashSet<>(); HashSet<Integer> even=new HashSet<>(); HashSet<Integer> set1=new HashSet<>(); HashSet<Integer> set2=new HashSet<>(); for(int i=1;i<=Math.min(m, n);i++) { if(i%2==1) { set1.add(i); }else { set2.add(i); } } int[] A=new int[n]; int[] B=new int[n]; for(int i=0;i<n;i++) {//ε…ˆε­˜ε€§δΊŽm int a=in.nextInt(); B[i]=a; if(a>m) { if(a%2==1&&odd.size()<n/2&&!odd.contains(a)) { A[i]=a; odd.add(a); } if(a%2==0&&even.size()<n/2&&!even.contains(a)) { A[i]=a; even.add(a); } } } for(int i=0;i<n;i++) { int a=B[i]; if(a<=m) { if(a%2==1&&odd.size()<n/2&&!odd.contains(a)) { A[i]=a; odd.add(a); set1.remove(a); } if(a%2==0&&even.size()<n/2&&!even.contains(a)) { A[i]=a; even.add(a); set2.remove(a); } } } int r1=n/2-odd.size(); int r2=n/2-even.size(); if(r1>set1.size()||r2>set2.size()) { out.println(-1); return; } LinkedList<Integer> queue1=new LinkedList<>(set1); LinkedList<Integer> queue2=new LinkedList<>(set2); for(int i=0,p=0;i<n&&p<r1;i++) { if(A[i]==0) { A[i]=queue1.poll(); p++; } } for(int i=0,p=0;i<n&&p<r2;i++) { if(A[i]==0) { A[i]=queue2.poll(); p++; } } out.println(r1+r2); for(int i=0;i<n;i++) { out.print(A[i]+" "); } } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(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()); } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
6541423a485d4107fc9f358abf6e720d
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] pts = br.readLine().split(" "); int n = Integer.parseInt(pts[0]); int m = Integer.parseInt(pts[1]); pts = br.readLine().split(" "); int[] arr = new int[n]; if (n % 2 != 0) { System.out.println("-1"); System.exit(0); } int lim = Math.min(4 * n, m); SegmentTree st = new SegmentTree(lim + 1); st.update(0, INF); int eve = 0, odd = 0; for (int i = 0; i < n; i ++) { arr[i] = Integer.parseInt(pts[i]); if (arr[i] <= lim) st.update(arr[i], 1); if (arr[i] % 2 == 0) { eve ++; } else { odd ++; } } int[] brr = new int[n]; int cnt = 0; Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < arr.length; i ++) { if (set.contains(arr[i])) { cnt ++; if (arr[i] % 2 == 0) { if (eve > odd) { int x = st.queryAll().odd; if (x == INF) { System.out.println("-1"); System.exit(0); } st.update(x, 1); brr[i] = x; eve --; odd ++; } else { int x = st.queryAll().eve; if (x == INF) { System.out.println("-1"); System.exit(0); } st.update(x, 1); brr[i] = x; } } else { if (odd > eve) { int x = st.queryAll().eve; if (x == INF) { System.out.println("-1"); System.exit(0); } st.update(x, 1); brr[i] = x; odd --; eve ++; } else { int x = st.queryAll().odd; if (x == INF) { System.out.println("-1"); System.exit(0); } st.update(x, 1); brr[i] = x; } } set.add(brr[i]); } else { set.add(arr[i]); brr[i] = arr[i]; } } for (int i = 0; i < brr.length; i ++) { if (odd > eve) { if (brr[i] % 2 == 1) { int x = st.queryAll().eve; if (x == INF) { System.out.println("-1"); System.exit(0); } brr[i] = x; st.update(x, 1); odd --; eve ++; cnt ++; } } else if (eve > odd) { if (brr[i] % 2 == 0) { int x = st.queryAll().odd; if (x == INF) { System.out.println("-1"); System.exit(0); } st.update(x, 1); brr[i] = x; eve --; cnt ++; odd ++; } } } System.out.println(cnt); for (int i: brr) { System.out.print(i + " "); } System.out.println(); } static int INF = 100000000; } class Node { static int INF = 100000000; int cnt = 0; int eve = INF; int odd = INF; } class SegmentTree { static int INF = 100000000; private int[] leafInd; private int N; private Node[] tree; public SegmentTree(int length) { this.N = length; leafInd = new int[N]; tree = new Node[(N<<2) + 1]; build(1, 0, N - 1); } private void build(int index, int start, int end) { if(start > end) return; if(start == end) { tree[index] = new Node(); tree[index].cnt = 0; int actual = start; if (actual % 2 == 0) { tree[index].eve = actual; } else { tree[index].odd = actual; } leafInd[start] = index; } else if(start < end) { int mid = (start + end) / 2; build(2 * index, start, mid); build(2 * index + 1, mid + 1, end); tree[index] = merge(tree[2 * index], tree[2 * index + 1]); } } public void update(int ind, int data) { if(ind <0 || ind >= N) throw new IllegalArgumentException("Index not present in array"); int index = leafInd[ind]; tree[index].cnt += data; if (ind % 2 == 0) { if (data > 0) { tree[index].eve = INF; } else { tree[index].eve = ind; } } else { if (data > 0) { tree[index].odd = INF; } else { tree[index].odd = ind; } } index /= 2; while(index >= 1) { tree[index] = merge(tree[2 * index], tree[2 * index + 1]); index /= 2; } } public Node query(int i, int j) { return query(1, 0, N - 1, i, j); } public Node queryAll() { return tree[1]; } private Node query(int index, int start, int end, int i, int j) { if(start > end) return null; else if(start >= i && end <= j) return tree[index]; int mid = (start + end) / 2; if(j <= mid) return query(2 * index, start, mid, i, j); else if(i > mid) return query(2 * index + 1, mid + 1, end, i, j); else { Node left = query(2 * index, start, mid, i, j); Node right = query(2 * index + 1, mid + 1, end, i, j); return merge(left, right); } } public Node merge(Node left, Node right) { Node ans = new Node(); ans.eve = Math.min(left.eve, right.eve); ans.odd = Math.min(left.odd, right.odd); return ans; } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
c20462f6ca7c4754c30939e44589c303
train_000.jsonl
1482057300
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] pts = br.readLine().split(" "); int n = Integer.parseInt(pts[0]); int m = Integer.parseInt(pts[1]); pts = br.readLine().split(" "); int[] arr = new int[n]; if (n % 2 != 0) { System.out.println("-1"); System.exit(0); } int lim = Math.min(10 * n, m); SegmentTree st = new SegmentTree(lim + 1); st.update(0, INF); int eve = 0, odd = 0; for (int i = 0; i < n; i ++) { arr[i] = Integer.parseInt(pts[i]); if (arr[i] <= lim) st.update(arr[i], 1); if (arr[i] % 2 == 0) { eve ++; } else { odd ++; } } int[] brr = new int[n]; int cnt = 0; Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < arr.length; i ++) { if (set.contains(arr[i])) { cnt ++; if (arr[i] % 2 == 0) { if (eve > odd) { int x = st.queryAll().odd; if (x == INF) { System.out.println("-1"); System.exit(0); } if (arr[i] <= lim) st.update(arr[i], -1); st.update(x, 1); brr[i] = x; eve --; odd ++; } else { int x = st.queryAll().eve; if (x == INF) { System.out.println("-1"); System.exit(0); } st.update(x, 1); if (arr[i] <= lim) st.update(arr[i], -1); brr[i] = x; } } else { if (odd > eve) { int x = st.queryAll().eve; if (x == INF) { System.out.println("-1"); System.exit(0); } st.update(x, 1); if (arr[i] <= lim) { st.update(arr[i], -1); } brr[i] = x; odd --; eve ++; } else { int x = st.queryAll().odd; if (x == INF) { System.out.println("-1"); System.exit(0); } st.update(x, 1); if (arr[i] <= lim) { st.update(arr[i], -1); } brr[i] = x; } } set.add(brr[i]); } else { set.add(arr[i]); brr[i] = arr[i]; } } for (int i = 0; i < brr.length; i ++) { if (odd > eve) { if (brr[i] % 2 == 1) { int x = st.queryAll().eve; if (x == INF) { System.out.println("-1"); System.exit(0); } brr[i] = x; st.update(x, 1); odd --; eve ++; cnt ++; } } else if (eve > odd) { if (brr[i] % 2 == 0) { int x = st.queryAll().odd; if (x == INF) { System.out.println("-1"); System.exit(0); } st.update(x, 1); brr[i] = x; eve --; cnt ++; odd ++; } } } System.out.println(cnt); for (int i: brr) { System.out.print(i + " "); } System.out.println(); } static int INF = 100000000; } class Node { static int INF = 100000000; int cnt = 0; int eve = INF; int odd = INF; } class SegmentTree { static int INF = 100000000; private int[] leafInd; private int N; private Node[] tree; public SegmentTree(int length) { this.N = length; leafInd = new int[N]; tree = new Node[(N<<2) + 1]; build(1, 0, N - 1); } private void build(int index, int start, int end) { if(start > end) return; if(start == end) { tree[index] = new Node(); tree[index].cnt = 0; int actual = start; if (actual % 2 == 0) { tree[index].eve = actual; } else { tree[index].odd = actual; } leafInd[start] = index; } else if(start < end) { int mid = (start + end) / 2; build(2 * index, start, mid); build(2 * index + 1, mid + 1, end); tree[index] = merge(tree[2 * index], tree[2 * index + 1]); } } public void update(int ind, int data) { if(ind <0 || ind >= N) throw new IllegalArgumentException("Index not present in array"); int index = leafInd[ind]; tree[index].cnt += data; data = tree[index].cnt; if (ind % 2 == 0) { if (data > 0) { tree[index].eve = INF; } else { tree[index].eve = ind; } } else { if (data > 0) { tree[index].odd = INF; } else { tree[index].odd = ind; } } index /= 2; while(index >= 1) { tree[index] = merge(tree[2 * index], tree[2 * index + 1]); index /= 2; } } public Node query(int i, int j) { return query(1, 0, N - 1, i, j); } public Node queryAll() { return tree[1]; } private Node query(int index, int start, int end, int i, int j) { if(start > end) return null; else if(start >= i && end <= j) return tree[index]; int mid = (start + end) / 2; if(j <= mid) return query(2 * index, start, mid, i, j); else if(i > mid) return query(2 * index + 1, mid + 1, end, i, j); else { Node left = query(2 * index, start, mid, i, j); Node right = query(2 * index + 1, mid + 1, end, i, j); return merge(left, right); } } public Node merge(Node left, Node right) { Node ans = new Node(); ans.eve = Math.min(left.eve, right.eve); ans.odd = Math.min(left.odd, right.odd); return ans; } }
Java
["6 2\n5 6 7 9 4 5", "8 6\n7 7 7 7 8 8 8 8", "4 1\n4 2 1 10"]
1 second
["1\n5 6 7 9 4 2", "6\n7 2 4 6 8 1 3 5", "-1"]
null
Java 8
standard input
[ "implementation", "greedy", "math" ]
86bf9688b92ced5238009eefd051387d
The first line contains two integers n and m (2 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 109)Β β€” the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the numbers on Eugeny's cards.
1,900
If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integersΒ β€” Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.
standard output
PASSED
cf42093e45d008beb55949ba9ab37270
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Scanner; public class aa { public static void main(String[] args)throws NumberFormatException, IOException { //Scanner in=new Scanner(System.in); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); StringBuilder q=new StringBuilder(""); String u=in.readLine(); String yy[]=u.split(" "); int n=Integer.parseInt(yy[0]); int m=Integer.parseInt(yy[1]); long a[]=new long[n]; String y=in.readLine(); String yyy[]=y.split(" "); for (int i = 0; i < a.length; i++) { a[i]=Integer.parseInt(yyy[i]); } long ans[]=new long[10000000]; int count=0; long trans=0; for (int i = 0; i < m; i++) { String t=in.readLine(); String tt[]=t.split(" "); int type=Integer.parseInt(tt[0]); if(type==3){ ans[count++]=a[Integer.parseInt(tt[1])-1]+trans; } else if(type==1){ int one=Integer.parseInt(tt[1]); int two=Integer.parseInt(tt[2]); a[one-1]=two-trans; } else{ int re=Integer.parseInt(tt[1]); trans+=re; } } for (int i = 0; i < count; i++) { q.append(ans[i]+"\n"); } out.print(q); out.close(); // int count=n; // for (int i = 0; i < n; i++) { // int a=in.nextInt(); // int b=in.nextInt(); // if(a!=b){ // count--; // } // } // System.out.println(count); } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
4d49b73a340484c906520c26598cbfaa
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; public class SerejaAndArray { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); OutputStream out = new BufferedOutputStream(System.out); String[] l = br.readLine().split("\\s+"); int m = Integer.parseInt(l[1]); String[] num = br.readLine().split("\\s+"); int indec = 0; for (int i=0;i<m;i++){ String[] c = br.readLine().split("\\s+"); if (c[0].equals("1")){ int ind = Integer.parseInt(c[1])-1; num[ind] = (Integer.parseInt(c[2]) - indec)+""; } else if (c[0].equals("2")){ indec += Integer.parseInt(c[1]); } else{ int ind = Integer.parseInt(c[1]) -1; int res = Integer.parseInt(num[ind]); res += indec; out.write((res+"\n").getBytes()); } } out.flush(); br.close(); } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
af2fada83af1e6cbb319c34fbc30e392
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.*; public class Main { public static void main(String args[]) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String line = stdin.readLine(); String[] prms = line.split(" "); int n = Integer.parseInt(prms[0]); int m = Integer.parseInt(prms[1]); long[] a = new long[n + 1]; long[] b = new long[m + 1]; int[] c = new int[n + 1]; line = stdin.readLine(); prms = line.split(" "); for(int i = 1; i <= n; i++){ a[i] = Long.parseLong(prms[i - 1]); } for (int i = 1; i <= m; i++) { b[i] = b[i - 1]; line = stdin.readLine(); prms = line.split(" "); int t = Integer.parseInt(prms[0]); if (t == 1) { int v = Integer.parseInt(prms[1]); int x = Integer.parseInt(prms[2]); a[v] = x; c[v] = i; } else if (t == 2) { int y = Integer.parseInt(prms[1]); b[i] = b[i - 1] + y; } else { int q = Integer.parseInt(prms[1]); long d = a[q] + b[i] - b[c[q]]; System.out.println(d); } } } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
21877dd65ffd8d526faafcb3e81e0c87
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.math.BigInteger; 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 { public void solve(int testNumber, InputReader in, PrintWriter out) { int N=in.readInt(); int M=in.readInt(); long A[]=new long[N+1]; for (int i=1;i<=N;i++) A[i]=in.readInt(); long add=0; for (int i=0;i<M;i++){ int operation=in.readInt(); switch (operation){ case 1: int v=in.readInt(); int x=in.readInt(); A[v]=x-add; break; case 2: add+=in.readInt(); break; case 3: out.println(A[in.readInt()]+add); break; } } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private 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 readInt() { 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
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
71a38f07d1786360f0a218df676d9fff
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; import java.io.*; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, BufferedReader in, PrintWriter out) throws Exception{ StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); long[] a = new long[n + 1]; st = new StringTokenizer(in.readLine()); for(int i = 1; i <= n; i++) a[i] = Integer.parseInt(st.nextToken()); int add = 0; for(int i = 0; i < m; i++) { st = new StringTokenizer(in.readLine()); int op = Integer.parseInt(st.nextToken()); if(op == 1) { int v = Integer.parseInt(st.nextToken()); int x = Integer.parseInt(st.nextToken()); a[v] = x - add; } else if(op == 2) { int y = Integer.parseInt(st.nextToken()); add += y; } else { int q = Integer.parseInt(st.nextToken()); out.println(a[q] + add); } } out.close(); } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
6c5688d2723083e299636e7a103d63dc
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; public class B { public static void main(String[] args)throws IOException { StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); st.nextToken(); int n =(int)st.nval; st.nextToken(); int m=(int)st.nval; int [] a = new int [n+1]; int [] ans = new int [m+1]; int k=0,w=0; int v,x,y,q; for (int i = 1; i <=n; i++) { st.nextToken(); a[i]=(int)st.nval; } for (int i = 1; i <=m; i++) { st.nextToken(); int t=(int)st.nval; if(t==1){ st.nextToken(); v=(int)st.nval; st.nextToken(); x=(int)st.nval; a[v]=x; a[v]-=w; } if(t==2){ st.nextToken(); y=(int)st.nval; w+=y; } if(t==3){ st.nextToken(); q=(int)st.nval; k++; ans[k] = a[q]+w; } } for (int i = 1; i <=k; i++) { System.out.println(ans[i]); } } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
feee5d8956de69cd9bfd3added691376
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; public class B { public static void main(String[] args) throws Exception{ InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); long[] arr = new long[n]; for(int i = 0; i < n ;i++){ arr[i] = in.nextLong(); } long sum = 0; for(int i = 0 ;i < m; i++){ int type = in.nextInt(); if(type == 1){ arr[in.nextInt()-1] = in.nextLong()-sum; }else if(type == 2){ sum += in.nextLong(); }else{ out.println(arr[in.nextInt()-1] + sum); } } out.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private 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 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 String nextToken() { 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 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
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
0be4cdc7b1c98f69702c405341131b9d
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nguyen Trung Hieu - [email protected] */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int count = in.readInt(); int queryCount = in.readInt(); int[] A = IOUtils.readIntArray(in, count); int[] minusValue = new int[count]; int totalAdd = 0; for (int i = 0; i < queryCount; i++) { int queryType = in.readInt(); if (queryType == 1) { int idx = in.readInt() - 1; int value = in.readInt(); A[idx] = value; minusValue[idx] = totalAdd; } else if (queryType == 2) totalAdd += in.readInt(); else { int idx = in.readInt() - 1; out.printLine(A[idx] + totalAdd - minusValue[idx]); } } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private 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 readInt() { 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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
726da2bf29cbfc1aea7b9cda84d2ea72
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.util.*; import java.io.*; public class B { Scanner sc = new Scanner(System.in); void doIt() { int n = Integer.parseInt(sc.next()); int m = Integer.parseInt(sc.next()); long [] a = new long[n+1]; int [] w = new int[n+1]; for(int i = 1; i <= n; i++) { a[i] = Long.parseLong(sc.next()); w[i] = 0; } int old = 0; long cur_v = 0; long [] sum = new long[m+1]; Arrays.fill(sum, 0L); for(int i = 1; i <= m; i++) { int t = Integer.parseInt(sc.next()); switch(t) { case 1: int v = Integer.parseInt(sc.next()); long x = Long.parseLong(sc.next()); a[v] = x; w[v] = i; sum[i] = cur_v; break; case 2: long y = Long.parseLong(sc.next()); cur_v = sum[i] = sum[old] + y; old = i; break; case 3: int q = Integer.parseInt(sc.next()); long ans = a[q]; //System.out.println(ans + " " + cur_v + " " + w[q] + " " + sum[w[q]]); ans += cur_v; ans -= sum[w[q]]; System.out.println(ans); break; } } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new B().doIt(); } // thanks to wata class Scanner { InputStream in; byte[] buf = new byte[1 << 10]; int p, n; boolean[] isSpace = new boolean[128]; Scanner(InputStream in) { this.in = in; isSpace[' '] = isSpace['\n'] = isSpace['\r'] = isSpace['\t'] = true; } int read() { if (n == -1) return -1; if (p >= n) { p = 0; try { n = in.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (n <= 0) return -1; } return buf[p++]; } boolean hasNext() { int c = read(); while (c >= 0 && isSpace[c]) c = read(); if (c == -1) return false; p--; return true; } String next() { if (!hasNext()) throw new InputMismatchException(); StringBuilder sb = new StringBuilder(); int c = read(); while (c >= 0 && !isSpace[c]) { sb.append((char)c); c = read(); } return sb.toString(); } int nextInt() { if (!hasNext()) throw new InputMismatchException(); int 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 (c >= 0 && !isSpace[c]); return res * sgn; } long nextLong() { if (!hasNext()) throw new InputMismatchException(); int 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 (c >= 0 && !isSpace[c]); return res * sgn; } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
112efb76cb47256d2c03921974a5044f
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.util.*; import java.io.*; public class B { Scanner sc = new Scanner(System.in); void doIt() { int n = sc.nextInt(); int m = sc.nextInt(); long [] a = new long[n+1]; int [] w = new int[n+1]; for(int i = 1; i <= n; i++) { a[i] = sc.nextLong(); w[i] = 0; } int old = 0; long cur_v = 0; long [] sum = new long[m+1]; Arrays.fill(sum, 0L); for(int i = 1; i <= m; i++) { int t = sc.nextInt(); switch(t) { case 1: int v = sc.nextInt(); long x = sc.nextLong(); a[v] = x; w[v] = i; sum[i] = cur_v; break; case 2: long y = sc.nextLong(); cur_v = sum[i] = sum[old] + y; old = i; break; case 3: int q = sc.nextInt(); long ans = a[q]; //System.out.println(ans + " " + cur_v + " " + w[q] + " " + sum[w[q]]); ans += cur_v; ans -= sum[w[q]]; System.out.println(ans); break; } } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new B().doIt(); } // thanks to wata class Scanner { InputStream in; byte[] buf = new byte[1 << 10]; int p, n; boolean[] isSpace = new boolean[128]; Scanner(InputStream in) { this.in = in; isSpace[' '] = isSpace['\n'] = isSpace['\r'] = isSpace['\t'] = true; } int read() { if (n == -1) return -1; if (p >= n) { p = 0; try { n = in.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (n <= 0) return -1; } return buf[p++]; } boolean hasNext() { int c = read(); while (c >= 0 && isSpace[c]) c = read(); if (c == -1) return false; p--; return true; } String next() { if (!hasNext()) throw new InputMismatchException(); StringBuilder sb = new StringBuilder(); int c = read(); while (c >= 0 && !isSpace[c]) { sb.append((char)c); c = read(); } return sb.toString(); } int nextInt() { if (!hasNext()) throw new InputMismatchException(); int 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 (c >= 0 && !isSpace[c]); return res * sgn; } long nextLong() { if (!hasNext()) throw new InputMismatchException(); int 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 (c >= 0 && !isSpace[c]); return res * sgn; } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
1dc361cfe1163f53f74f63018974e99f
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import com.sun.corba.se.spi.orb.OperationFactory; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; /** * * @author Robert Nabil */ public class Array { public static void main(String[] args) throws Exception{ BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); String[] s = sc.readLine().split(" "); int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]); s = sc.readLine().split(" "); int increase = 0; int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(s[i]); } for (int i = 0; i < m; i++) { s = sc.readLine().split(" "); int t = Integer.parseInt(s[0]); if(t == 1){ a[Integer.parseInt(s[1]) - 1] = Integer.parseInt(s[2]) - increase; }else if(t == 2){ increase += Integer.parseInt(s[1]); }else{ System.out.println(a[Integer.parseInt(s[1]) - 1] + increase); } } } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
b5c668b9f46fc650793820031d84d5ae
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class B315 { static FastScanner in; static FastWriter out; public static void main(String[] args) throws IOException { in = new FastScanner(System.in); out = new FastWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = in.nextLong(); long globAdd = 0; for (int i = 0; i < m; i++) { int type = in.nextInt(); if (type == 1) { int index = in.nextInt() - 1; long newVal = in.nextInt(); arr[index] = newVal - globAdd; } else if (type == 2) { globAdd += in.nextInt(); } else { int q = in.nextInt() - 1; out.println(arr[q] + globAdd); } } out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public FastScanner(File f) throws IOException { br = new BufferedReader(new FileReader(f)); st = new StringTokenizer(""); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public String next() throws IOException { if (st.hasMoreTokens()) return st.nextToken(); st = new StringTokenizer(br.readLine()); return next(); } } static class FastWriter extends PrintWriter { public FastWriter(OutputStream out) throws IOException { super(new BufferedWriter(new OutputStreamWriter(out))); } public FastWriter(File f) throws IOException { super(new BufferedWriter(new FileWriter(f))); } } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
e2a933c3fa8d4af4a1a6de8c65099a1a
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.io.BufferedWriter; import java.util.Locale; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Jacob Jiang */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[] a = in.nextIntArray(n); int delta = 0; for (int i = 0; i < m; i++) { int type = in.nextInt(); if (type == 1) { int v = in.nextInt() - 1; int x = in.nextInt(); a[v] = x - delta; } else if (type == 2) { int y = in.nextInt(); delta += y; } else { int q = in.nextInt() - 1; out.println(a[q] + delta); } } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; 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 & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] nextIntArray(int count) { int[] result = new int[count]; for (int i = 0; i < count; i++) { result[i] = nextInt(); } return result; } } class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(int i) { writer.println(i); } public void close() { writer.close(); } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
5871ad7f0ca1d31de0d63739e5f30443
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package pkg188; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; /** * * @author Alik */ public class F { static String line; static int cur = 0; public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); line = in.readLine(); int n = sp(), m = sp(); long a[] = new long [n + 1]; line = in.readLine(); for (int i = 1; i <= n; i++) a[i] = sp(); long z = 0; for (int i = 0; i < m; i++) { line = in.readLine(); int c = sp(); if (c == 1) { int x = sp(); long y = sp(); a[x] = y - z; } else if (c == 2) { long p = sp(); z += p; } else { int x = sp(); System.out.println(a[x] + z); } } } private static int sp() { int x = 0; while (cur < line.length()) { if (line.charAt(cur) == ' ') break; x = x * 10 + (line.charAt(cur) - 48); cur++; } cur++; if (cur >= line.length()) cur = 0; return x; } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
a0b491ebc88a4231540808ca3ad3df85
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
//import java.util.*; //Scanner; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; //PrintWriter public class R187_Div2_B { public static void main(String[] args) throws IOException { //Scanner in = new Scanner(System.in); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); //Reading 100,000 numbers on a line takes 3 times longer with Scanner //Scanner = 436ms; BufferedReader w/split = 186ms; w/o split = 124ms //For 200,000 numbers on a line: Scanner = 810ms; BR w/split = 280ms. //Thus, use BufferedReader instead of Scanner if time is critical. solve(in, out); out.close(); in.close(); } public static void solve(BufferedReader in, PrintWriter out) throws IOException { String[] s = in.readLine().split(" "); int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]); s = in.readLine().split(" "); long[] a = new long[n+1]; for (int i = 0; i < n; i++) a[i+1] = Long.parseLong(s[i]); //StringBuilder sb = new StringBuilder(); long add = 0; int v, x; for (int i = 0; i < m; i++) { s = in.readLine().split(" "); int t = Integer.parseInt(s[0]); if (t == 1) { v = Integer.parseInt(s[1]); x = Integer.parseInt(s[2]); a[v] = x - add; } else if (t == 2) { int y = Integer.parseInt(s[1]); add += y; } else if (t == 3) { int q = Integer.parseInt(s[1]); //sb.append((a[q]+add)+"\r\n"); out.println(a[q]+add); } } //out.print(sb); } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
d67fc7addca9a7fdc9c31c53c786b171
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
//import java.util.*; //Scanner; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; //PrintWriter public class R187_Div2_B { public static void main(String[] args) throws IOException { //Scanner in = new Scanner(System.in); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); //Reading 100,000 numbers on a line takes 3 times longer with Scanner //Scanner = 436ms; BufferedReader w/split = 186ms; w/o split = 124ms //For 200,000 numbers on a line: Scanner = 810ms; BR w/split = 280ms. //Thus, use BufferedReader instead of Scanner if time is critical. solve(in, out); out.close(); in.close(); } public static void solve(BufferedReader in, PrintWriter out) throws IOException { String[] s = in.readLine().split(" "); int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]); s = in.readLine().split(" "); long[] a = new long[n+1]; for (int i = 0; i < n; i++) a[i+1] = Long.parseLong(s[i]); StringBuilder sb = new StringBuilder(); long add = 0; int v, x; for (int i = 0; i < m; i++) { s = in.readLine().split(" "); int t = Integer.parseInt(s[0]); if (t == 1) { v = Integer.parseInt(s[1]); x = Integer.parseInt(s[2]); a[v] = x - add; } else if (t == 2) { int y = Integer.parseInt(s[1]); add += y; } else if (t == 3) { int q = Integer.parseInt(s[1]); sb.append((a[q]+add)+"\r\n"); } } out.print(sb); } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
04257769bc638372de3c9da04102385e
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; public class R187_Div2_B_fr { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); long[] a = new long[n+1]; for (int i = 0; i < n; i++) a[i+1] = in.nextLong(); StringBuilder sb = new StringBuilder(); long add = 0; int v, x; for (int i = 0; i < m; i++) { int t = in.nextInt(); if (t == 1) { v = in.nextInt(); x = in.nextInt(); a[v] = x - add; } else if (t == 2) { int y = in.nextInt(); add += y; } else if (t == 3) { int q = in.nextInt(); out.println(a[q]+add); } } out.print(sb); } } 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()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
4ae8f3491ddab15d90116840eba0a71a
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.*; //PrintWriter import java.math.*; //BigInteger, BigDecimal import java.util.*; //StringTokenizer, ArrayList public class R187_Div2_B { FastReader in; PrintWriter out; public static void main(String[] args) { new R187_Div2_B().run(); } void run() { in = new FastReader(System.in); out = new PrintWriter(System.out); solve(); out.close(); } void solve() { int n = in.nextInt(); int m = in.nextInt(); long[] a = new long[n+1]; for (int i = 0; i < n; i++) a[i+1] = in.nextLong(); StringBuilder sb = new StringBuilder(); long add = 0; int v, x; for (int i = 0; i < m; i++) { int t = in.nextInt(); if (t == 1) { v = in.nextInt(); x = in.nextInt(); a[v] = x - add; } else if (t == 2) { int y = in.nextInt(); add += y; } else if (t == 3) { int q = in.nextInt(); sb.append((a[q]+add)+"\r\n"); } } out.print(sb); } //----------------------------------------------------- void runWithFiles() { in = new FastReader(new File("input.txt")); try { out = new PrintWriter(new File("output.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } solve(); out.close(); } class FastReader { BufferedReader br; StringTokenizer tokenizer; public FastReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public FastReader(File f) { try { br = new BufferedReader(new FileReader(f)); tokenizer = null; } catch (FileNotFoundException e) { e.printStackTrace(); } } private String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return tokenizer.nextToken(); } public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } BigInteger nextBigInteger() { return new BigInteger(next()); } BigDecimal nextBigDecimal() { return new BigDecimal(next()); } } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
7b9b7d7f9c286c024c61ddc170fce438
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; public class Main { public static void main(String[] args) { //Scanner sc=new Scanner(System.in); BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); String[] nm={"0","0"}; try{nm =(bf.readLine()).split(" ");}catch(Exception e){}; long n=Long.parseLong(nm[0]),m=Long.parseLong(nm[1]); long[] a= new long[(int) (n+1)]; String[] tt={}; try{tt=bf.readLine().split(" ");}catch(Exception e){}; for(int i=1;i<=n;i++){//if(!(tt[i-1].isEmpty())) a[i]=Long.parseLong(tt[i-1]);} long all=0; for(int i=1;i<=m;i++){ String[] ll={}; try{ll=bf.readLine().split(" ");}catch(Exception e){}; int t= Integer.parseInt(ll[0]); if(t==1){ int v=Integer.parseInt(ll[1]),x=Integer.parseInt(ll[2]); a[v]=x-all; }else if (t==2){ int y=Integer.parseInt(ll[1]); all+=y; }else {//if(t==3) int q=Integer.parseInt(ll[1]); System.out.println(a[q]+all); } } } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
0d8fc3afa22220cbad8c479999c61fd1
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String line = input.readLine(); int n = Integer.parseInt(line.split(" ")[0]) , m = Integer.parseInt(line.split(" ")[1]); String[] arr = input.readLine().split(" "); int[] arrInt = new int[n]; for( int i = 0; i < n; i++ ) { arrInt[i] = Integer.parseInt(arr[i]); } int aux1, aux2, aux3 = 0; int aumento = 0; for( int i = 0; i < m; i++) { arr = input.readLine().split(" "); if ( arr.length == 3 ) { aux3 = Integer.parseInt(arr[2]); } aux1 = Integer.parseInt(arr[0]); aux2 = Integer.parseInt(arr[1]); if( aux1 == 1 ) { arrInt[aux2-1] = aux3 - aumento; } else if( aux1 == 2 ) { aumento += aux2; } else { System.out.println(arrInt[ aux2 -1 ]+aumento); } } } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
507ecce1feb304e53ea5a279bd9fa6ea
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class B { private static StringTokenizer tokenizer; private static BufferedReader bf; private static PrintWriter out; private static long[] a; private static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } @SuppressWarnings("unused") private static long nextLong() throws IOException { return Long.parseLong(nextToken()); } private static String nextToken() throws IOException { while(tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(bf.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) throws IOException { bf = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int m = nextInt(); a = new long[n+1]; for(int i = 1; i <= n; i++) a[i] = nextInt(); long add = 0; for(int i = 0; i < m; i++) { int t = nextInt(); if(t == 1) { int v = nextInt(); int x = nextInt(); a[v] = x - add; } else if(t == 2) { int y = nextInt(); add += y; } else { int q = nextInt(); out.println(a[q]+add); } } out.close(); } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
d4e3f1a0d1238de7538b0b79d0bc9672
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class B { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine().trim()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); int[] array = new int[N]; int[] sums = new int[N + 1]; st = new StringTokenizer(br.readLine().trim()); for (int i = 0; i < N; i++) { array[i] = Integer.parseInt(st.nextToken()); } for (int i = 0; i < M; i++) { st = new StringTokenizer(br.readLine().trim()); int V = Integer.parseInt(st.nextToken()); if (V == 1) { int X = Integer.parseInt(st.nextToken()); int Y = Integer.parseInt(st.nextToken()); array[X - 1] = Y; sums[X - 1] = sums[N]; } else if (V == 2) { int X = Integer.parseInt(st.nextToken()); sums[N] += X; } else { int X = Integer.parseInt(st.nextToken()); out.println(array[X - 1] + sums[N] - sums[X - 1]); } } br.close(); out.close(); } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output
PASSED
495e7591338b34f3924c5fe47043f6ef
train_000.jsonl
1370619000
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader( System.in )); //Scanner sn = new Scanner(System.in); String[] in = null; try { in = br.readLine().split(" "); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } int[] s = new int[in.length]; for(int i = 0; i < in.length; i++) s[i] = Integer.parseInt(in[i]); int n = s[0], m = s[1]; in = null; try { in = br.readLine().split(" "); } catch (IOException e) { e.printStackTrace(); } int[] a = new int[in.length]; for(int i = 0; i < in.length; i++) a[i] = Integer.parseInt(in[i]); int x,y,z; long sum = 0; for(int i = 0; i < m; i++) { in = null; try { in = br.readLine().split(" "); } catch (IOException e) { e.printStackTrace(); } x = Integer.parseInt(in[0]); switch(x) { case 1: y = Integer.parseInt(in[1]); z = Integer.parseInt(in[2]); a[y - 1] = z - ((int)sum); break; case 2: sum += Long.parseLong(in[1]); break; case 3: y = Integer.parseInt(in[1]); System.out.println(a[y - 1] + sum); break; } } } }
Java
["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"]
1 second
["2\n9\n11\n20\n30\n40\n39"]
null
Java 7
standard input
[ "implementation" ]
48f3ff32a11770f3b168d6e15c0df813
The first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).
1,200
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
standard output