exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
d5c35e51e422f69184cbb37f99f19c84
train_002.jsonl
1374913800
Gerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases: At least one of the chips at least once fell to the banned cell. At least once two chips were on the same cell. At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row). In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Diego Huerfano ( diego.link ) */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { final int n=in.readInt(), m=in.readInt(); boolean failRow[]=new boolean[n]; boolean failCol[]=new boolean[n]; failCol[0]=failCol[n-1]=true; failRow[0]=failRow[n-1]=true; for (int i = 0; i < m; i++) { int x=in.readInt()-1; int y=in.readInt()-1; failRow[x]=true; failCol[y]=true; } int counter1=0, counter2=0; for( int r=0; r<n; r++ ) { if( !failRow[r] ) counter1++; if( !failRow[r] && (failCol[r] || failCol[n-r-1] || n%2==0 || r!=n/2 ) ) counter2++; } for( int c=0; c<n; c++ ) { if( !failCol[c] ) counter2++; if( !failCol[c] && (failRow[c] || failRow[n-c-1] || n%2==0 || c!=n/2 ) ) counter1++; } out.printLine( Math.max( counter1, counter2 ) ); } } 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); } } 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(); } }
Java
["3 1\n2 2", "3 0", "4 3\n3 1\n3 2\n3 3"]
1 second
["0", "1", "1"]
NoteIn the first test the answer equals zero as we can't put chips into the corner cells.In the second sample we can place one chip into either cell (1, 2), or cell (3, 2), or cell (2, 1), or cell (2, 3). We cannot place two chips.In the third sample we can only place one chip into either cell (2, 1), or cell (2, 4).
Java 7
standard input
[ "two pointers", "implementation", "greedy" ]
a26a97586d4efb5855aa3b930e9effa7
The first line contains two space-separated integers n and m (2 ≤ n ≤ 1000, 0 ≤ m ≤ 105) — the size of the field and the number of banned cells. Next m lines each contain two space-separated integers. Specifically, the i-th of these lines contains numbers xi and yi (1 ≤ xi, yi ≤ n) — the coordinates of the i-th banned cell. All given cells are distinct. Consider the field rows numbered from top to bottom from 1 to n, and the columns — from left to right from 1 to n.
1,800
Print a single integer — the maximum points Gerald can earn in this game.
standard output
PASSED
9c52e6ab715a129ab4e781a6b904d19b
train_002.jsonl
1374913800
Gerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases: At least one of the chips at least once fell to the banned cell. At least once two chips were on the same cell. At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row). In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class my_class { public static void main(String[] args) throws Exception{ int n = nextInt(), m = nextInt(); int arrX[] = new int[n]; int arrY[] = new int[n]; arrX[0] = 1; arrX[n - 1] = 1; arrY[0] = 1; arrY[n - 1] = 1; for(int i = 0; i < m; i++){ arrX[nextInt() - 1] = 1; arrY[nextInt() - 1] = 1; } for(int i = 0; i < n; i++){ if((arrX[i] == 0) && (arrY[i] == 0)){ arrY[i] = 2; for(int k = 0; k < n; k++){ if((arrX[n - k - 1] == 0) && (arrY[k] == 2)){ arrX[n - k - 1] = 2; } } } } for(int i = 0; i < n; i++){ if((arrX[i] == arrY[i]) && (arrX[i] != 1)){ arrX[i] = 1; } } int max = 0; for(int i = 0; i < n; i++){ if((arrX[i] == 0) || (arrX[i] == 2)){ max++; } if((arrY[i] == 0) || (arrY[i] == 2)){ max++; } } println(max); } private static PrintWriter out = new PrintWriter(System.out); private static BufferedReader inB = new BufferedReader(new InputStreamReader(System.in)); private static StreamTokenizer in = new StreamTokenizer(inB); private static void exit(Object o) throws Exception { out.println(o); out.flush(); System.exit(0); } private static void println(Object o) throws Exception{ out.println(o); out.flush(); } private static void print(Object o) throws Exception{ out.print(o); out.flush(); } private static long nextLong() throws Exception { in.nextToken(); return (long)in.nval; } private static int nextInt() throws Exception { in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception { in.nextToken(); return in.sval; } }
Java
["3 1\n2 2", "3 0", "4 3\n3 1\n3 2\n3 3"]
1 second
["0", "1", "1"]
NoteIn the first test the answer equals zero as we can't put chips into the corner cells.In the second sample we can place one chip into either cell (1, 2), or cell (3, 2), or cell (2, 1), or cell (2, 3). We cannot place two chips.In the third sample we can only place one chip into either cell (2, 1), or cell (2, 4).
Java 7
standard input
[ "two pointers", "implementation", "greedy" ]
a26a97586d4efb5855aa3b930e9effa7
The first line contains two space-separated integers n and m (2 ≤ n ≤ 1000, 0 ≤ m ≤ 105) — the size of the field and the number of banned cells. Next m lines each contain two space-separated integers. Specifically, the i-th of these lines contains numbers xi and yi (1 ≤ xi, yi ≤ n) — the coordinates of the i-th banned cell. All given cells are distinct. Consider the field rows numbered from top to bottom from 1 to n, and the columns — from left to right from 1 to n.
1,800
Print a single integer — the maximum points Gerald can earn in this game.
standard output
PASSED
1e518c70cbba0e08a09a51241d16a12f
train_002.jsonl
1374913800
Gerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases: At least one of the chips at least once fell to the banned cell. At least once two chips were on the same cell. At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row). In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.
256 megabytes
import java.io.*; import java.util.HashMap; import java.util.StringTokenizer; public class Main { static void goCharizard() throws IOException { int n = nextInt(); int m = nextInt(); int[][] arr = new int[n][n]; int[] row = new int[n]; int[] col = new int[n]; for(int i=0;i<m;i++) { int a = nextInt() - 1; int b = nextInt() - 1; arr[a][0] = -1; arr[0][b] = -1; } for(int i=1;i<n-1;i++) row[i] = row[i-1] + (arr[i][0] == -1 ? 0 : 1); for(int j=1;j<n-1;j++) col[j] = col[j-1] + (arr[0][j] == -1 ? 0 : 1); int count = 0; for(int i=1;i<n-1;i++) count = Math.max(count, row[i] + col[n-2]-col[i] + (i <= (n-2)/2 ? row[n-2] - row[n-2-i] + col[i] : 0)); for(int i=1;i<n-1;i++) count = Math.max(count, col[i] + row[n-2]-row[i] + (i <= (n-2)/2 ? col[n-2] - col[n-2-i] + row[i] : 0)); out.println(count); } static BufferedReader br; static StringTokenizer st; static PrintWriter out; public static void main(String[] args) throws IOException { InputStream input = System.in; OutputStream output = System.out; br = new BufferedReader(new InputStreamReader(input)); out = new PrintWriter(output); goCharizard(); out.close(); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } }
Java
["3 1\n2 2", "3 0", "4 3\n3 1\n3 2\n3 3"]
1 second
["0", "1", "1"]
NoteIn the first test the answer equals zero as we can't put chips into the corner cells.In the second sample we can place one chip into either cell (1, 2), or cell (3, 2), or cell (2, 1), or cell (2, 3). We cannot place two chips.In the third sample we can only place one chip into either cell (2, 1), or cell (2, 4).
Java 7
standard input
[ "two pointers", "implementation", "greedy" ]
a26a97586d4efb5855aa3b930e9effa7
The first line contains two space-separated integers n and m (2 ≤ n ≤ 1000, 0 ≤ m ≤ 105) — the size of the field and the number of banned cells. Next m lines each contain two space-separated integers. Specifically, the i-th of these lines contains numbers xi and yi (1 ≤ xi, yi ≤ n) — the coordinates of the i-th banned cell. All given cells are distinct. Consider the field rows numbered from top to bottom from 1 to n, and the columns — from left to right from 1 to n.
1,800
Print a single integer — the maximum points Gerald can earn in this game.
standard output
PASSED
3fda84c2fc2ab67d0791233d46c1ba32
train_002.jsonl
1374913800
Gerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases: At least one of the chips at least once fell to the banned cell. At least once two chips were on the same cell. At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row). In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.StringTokenizer; public class Main { public static void main(String arg[]) throws IOException { // BufferedReader r=new BufferedReader(new FileReader("testcase.txt")); BufferedReader r=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer str=new StringTokenizer(r.readLine()); int n=Integer.parseInt(str.nextToken()); int m=Integer.parseInt(str.nextToken()); int x[]=new int[n+1]; int y[]=new int[n+1]; while(m-->0) { str=new StringTokenizer(r.readLine()); int a=Integer.parseInt(str.nextToken()); int b=Integer.parseInt(str.nextToken()); x[a]=1; y[b]=1; } HashSet s=new HashSet(); int count=0; for(int i=2;i<n;i++) { if(x[i]==0&&y[i]==0) { if(n%2==1) { if(i!=n/2+1) count+=2; else count++; } else if(n%2==0) count+=2; } else if(x[i]==0||y[i]==0) count++; } System.out.println(count); } }
Java
["3 1\n2 2", "3 0", "4 3\n3 1\n3 2\n3 3"]
1 second
["0", "1", "1"]
NoteIn the first test the answer equals zero as we can't put chips into the corner cells.In the second sample we can place one chip into either cell (1, 2), or cell (3, 2), or cell (2, 1), or cell (2, 3). We cannot place two chips.In the third sample we can only place one chip into either cell (2, 1), or cell (2, 4).
Java 7
standard input
[ "two pointers", "implementation", "greedy" ]
a26a97586d4efb5855aa3b930e9effa7
The first line contains two space-separated integers n and m (2 ≤ n ≤ 1000, 0 ≤ m ≤ 105) — the size of the field and the number of banned cells. Next m lines each contain two space-separated integers. Specifically, the i-th of these lines contains numbers xi and yi (1 ≤ xi, yi ≤ n) — the coordinates of the i-th banned cell. All given cells are distinct. Consider the field rows numbered from top to bottom from 1 to n, and the columns — from left to right from 1 to n.
1,800
Print a single integer — the maximum points Gerald can earn in this game.
standard output
PASSED
ade14cf1f493fc7129678c43e69b8876
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; 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.math.BigInteger; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.StringTokenizer; public class Solution{ /////////////////////////////////////////////////////////////////////////// static class FastScanner{ BufferedReader s; StringTokenizer st; public FastScanner(InputStream InputStream){ st = new StringTokenizer(""); s = new BufferedReader(new InputStreamReader(InputStream)); } public FastScanner(File f) throws FileNotFoundException{ st = new StringTokenizer(""); s = new BufferedReader (new FileReader(f)); } public int nextInt() throws IOException{ if(st.hasMoreTokens()) return Integer.parseInt(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextInt(); } } public BigInteger big() throws IOException{ if(st.hasMoreTokens()) return new BigInteger(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return big(); } } public double nextDouble() throws IOException{ if(st.hasMoreTokens()) return Double.parseDouble(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextDouble(); } } public long nextLong() throws IOException{ if(st.hasMoreTokens()) return Long.parseLong(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextLong(); } } public String nextString() throws IOException{ if(st.hasMoreTokens()) return st.nextToken(); else{ st = new StringTokenizer(s.readLine()); return nextString(); } } public String readLine() throws IOException{ return s.readLine(); } public void close() throws IOException{ s.close(); } } //////////////////////////////////////////////////////////////////// // Number Theory long pow(long a,long b,long mod){ long x = 1; long y = a; while(b > 0){ if(b % 2 == 1){ x = (x*y); x %= mod; } y = (y*y); y %= mod; b /= 2; } return x; } int divisor(long x,long[] a){ long limit = x; int numberOfDivisors = 0; for (int i=1; i < limit; ++i) { if (x % i == 0) { limit = x / i; if (limit != i) { numberOfDivisors++; } numberOfDivisors++; } } return numberOfDivisors; } void findSubsets(int array[]){ long numOfSubsets = 1 << array.length; for(int i = 0; i < numOfSubsets; i++){ @SuppressWarnings("unused") int pos = array.length - 1; int bitmask = i; while(bitmask > 0){ if((bitmask & 1) == 1) // ww.print(array[pos]+" "); bitmask >>= 1; pos--; } // ww.println(); } } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b,a%b); } public static long lcm(int a,int b, int c){ return lcm(lcm(a,b),c); } public static long lcm(long a, long b){ return (a*b/gcd(a,b)); } public static long invl(long a, long mod) { long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } return p < 0 ? p + mod : p; } //////////////////////////////////////////////////////////////////// // FastScanner s = new FastScanner(new File("input.txt")); // PrintWriter ww = new PrintWriter(new FileWriter("output.txt")); static InputStream inputStream = System.in; static FastScanner s = new FastScanner(inputStream); static OutputStream outputStream = System.out; static PrintWriter ww = new PrintWriter(new OutputStreamWriter(outputStream)); // private static Scanner s = new Scanner(System.in); @SuppressWarnings("unused") private static int[][] states = { {-1,0} , {1,0} , {0,-1} , {0,1} }; //////////////////////////////////////////////////////////////////// public static void main(String[] args) throws IOException{ new Solution().solve(); s.close(); ww.close(); } //////////////////////////////////////////////////////////////////// void solve() throws IOException{ int n=s.nextInt(); int [][]arr=new int[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ arr[i][j]=s.nextInt(); } } int ans=0; for(int i=0;i<n;i++) ans+=arr[i][i]; int q=s.nextInt(); for(int i=0;i<q;i++){ int ch=s.nextInt(); if(ch==1||ch==2){ int row=s.nextInt(); row--; if(arr[row][row]==0){ ans++; arr[row][row]=1; } else{ ans--; arr[row][row]=0; } } else{ ww.print(ans%2); } } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
29d25e8d27333af06530840475a27202
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.text.*; public class A { public A () { int N = sc.nextInt(); Integer [][] A = sc.nextInts(N); int res = 0; for (int i : rep(N)) res += A[i][i]; res %= 2; StringBuilder b = new StringBuilder(); for (@SuppressWarnings("unused") int q : rep(sc.nextInt())) if (sc.nextInt() == 3) b.append(res); else { sc.nextInt(); ++res; res %= 2; } exit(b); } private static long ceil (long p, long q) { if (q < 0) return ceil(-p, -q); else if (p < 0) return -floor(-p, q); else return (p+q-1) / q; } private static long floor(long p, long q) { if (q < 0) return floor(-p, -q); else if (p < 0) return -ceil(-p, q); else return p / q; } private static int [] rep(int N) { return rep(0, N); } private static int [] rep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } //////////////////////////////////////////////////////////////////////////////////// private final static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static void print (Object o, Object ...a) { IOUtils.print(o, a); } private static void exit (Object o, Object ...a) { print(o, a); exit(); } private static void exit() { IOUtils.exit(); } private static class IOUtils { public static class MyScanner { public String next() { newLine(); return line[index++]; } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() { line = null; return readLine(); } public String [] nextStrings() { return split(nextLine()); } public Integer [] nextInts() { String [] L = nextStrings(); Integer [] res = new Integer [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } public Integer [][] nextInts (int N) { Integer [][] res = new Integer [N][]; for (int i = 0; i < N; ++i) res[i] = nextInts(); return res; } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final java.io.BufferedReader r; private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); } private MyScanner (java.io.BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = split(readLine()); index = 0; } } private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build(Object o, Object... a) { return buildDelim(" ", o, a); } private static String buildDelim(String delim, Object o, Object... a) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : a) append(b, p, delim); return b.substring(delim.length()); } ////////////////////////////////////////////////////////////////////////////////// private static void start() { if (t == 0) t = millis(); } private static void append(StringBuilder b, Object o, String delim) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) append(b, java.lang.reflect.Array.get(o, i), delim); } else if (o instanceof Iterable<?>) for (Object p : (Iterable<?>) o) append(b, p, delim); else { if (o instanceof Double) o = new DecimalFormat("#.############").format(o); b.append(delim).append(o); } } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void print(Object o, Object ...a) { pw.println(build(o, a)); } private static void err(Object o, Object ...a) { System.err.println(build(o, a)); } private static void exit() { IOUtils.pw.close(); System.out.flush(); err("------------------"); err(IOUtils.time()); System.exit(0); } private static long t; private static long millis() { return System.currentTimeMillis(); } private static String time() { return "Time: " + (millis() - t) / 1000.0; } } public static void main (String[] args) { new A(); exit(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
829955b33add9f55a5dee0fd40ac6770
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.IOException; import java.util.InputMismatchException; import java.io.PrintStream; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author karan173 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { int n; long dots[]; long sumRow[], sumCol[]; public void solve(int testNumber, FastReader in, PrintWriter out) { n = in.ni (); int a[][] = new int[n][]; for (int i = 0; i < n; i++) { a[i] = in.iArr (n); } // out.println (Arrays.deepToString (a)); dots = new long[n]; sumCol = new long[n]; sumRow = new long[n]; long curAns = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int x1 = a[i][j]; int x2 = a[j][i]; dots[i] += x1 * x2; sumRow[i] += x1; sumCol[j] += x1; } curAns += dots[i]; } int q = in.ni (); for (int i = 0; i < q; i++) { int t = in.ni (); if (t == 3) { out.print (curAns % 2); continue; } else if (t == 1) //flip row { int r = in.ni () - 1; long oldDots = dots[r]; dots[r] = n - sumRow[r] - sumCol[r] + oldDots; curAns =curAns - 2 * oldDots + 2 * dots[r]+a[r][r]; sumRow[r] = n - sumRow[r]; sumCol[r] -= (a[r][r] == 1 ? 1 : 0); a[r][r] = 1 - a[r][r]; curAns -= a[r][r]; } else { int r = in.ni () - 1; long oldDots = dots[r]; dots[r] = n - sumRow[r] - sumCol[r] + oldDots; curAns = curAns- 2 * oldDots + 2 * dots[r]+a[r][r]; sumCol[r] = n - sumCol[r]; sumRow[r] -= (a[r][r] == 1 ? 1 : 0); a[r][r] = 1 - a[r][r]; curAns -= a[r][r]; } // out.println ("--"+curAns); } out.println (); } } class FastReader { public InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException (); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read (buf); } catch (IOException e) { throw new InputMismatchException (); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int ni() { 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 int[] iArr(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni (); } return a; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
227485fbdc23b127652d0451f96552b5
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.util.*; public class cf405c { static FastIO in = new FastIO(), out = in; public static void main(String[] args) { int n = in.nextInt(); int ret = 0; for(int i=0; i<n; i++) for(int j=0; j<n; j++) { if(i == j) ret ^= in.nextInt(); else in.nextInt(); } int q = in.nextInt(); for(int i=0; i<q; i++) { int type = in.nextInt(); if(type != 3) { ret ^= 1; in.nextInt(); } else out.print(ret); } out.close(); } static class FastIO extends PrintWriter { BufferedReader br; StringTokenizer st; public FastIO() { this(System.in, System.out); } public FastIO(InputStream in, OutputStream out) { super(new BufferedWriter(new OutputStreamWriter(out))); br = new BufferedReader(new InputStreamReader(in)); scanLine(); } public void scanLine() { try { st = new StringTokenizer(br.readLine().trim()); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } public int numTokens() { if (!st.hasMoreTokens()) { scanLine(); return numTokens(); } return st.countTokens(); } public String next() { if (!st.hasMoreTokens()) { scanLine(); return next(); } return st.nextToken(); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
42bd3a15372a01d6424ddc915fb98b8f
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.InputMismatchException; import java.io.PrintStream; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nipuna Samarasekara */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { ///////////////////////////////////////////////////////////// public void solve(int testNumber, FastScanner in, FastPrinter out) { int n=in.nextInt(); int[] rowc= new int[n]; int[] colc= new int[n]; int[][] A= new int[n][n]; for (int i = 0; i < n; i++) { A[i]=in.readIntArray(n); } int ans=0; for (int i = 0; i < n; i++) { for (int j = 0; j <n; j++) { ans+=A[i][j]*A[j][i]; } } ans%=2; int q=in.nextInt(); for (int i = 0; i < q; i++) { int t=in.nextInt(); if(t<3){ans=1-ans; in.next(); } else out.print(ans); } out.println(); } } class FastScanner extends BufferedReader { public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); // if (isEOF && ret < 0) { // throw new InputMismatchException(); // } // isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } public String next() { StringBuilder sb = new StringBuilder(); int c = read(); while (isWhiteSpace(c)) { c = read(); } if (c < 0) { return null; } while (c >= 0 && !isWhiteSpace(c)) { sb.appendCodePoint(c); c = read(); } return sb.toString(); } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } public String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } public int[] readIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
219c77aff284625f7d6b01cb09125dc5
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class Main { BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); public static void main(String[] args) throws IOException { new Main().run(); } void run() throws IOException { // in = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter("output.txt"); if (new File("input.txt").exists()) in = new BufferedReader(new FileReader("input.txt")); else in = new BufferedReader(new InputStreamReader(System.in)); if (new File("output.txt").exists()) out = new PrintWriter("output.txt"); else out = new PrintWriter(System.out); solve(); in.close(); out.close(); } int n; void solve() throws IOException { n = nextInt(); int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int a = nextInt(); if (i == j) ans = (ans + a) % 2; } } int q = nextInt(); for (int i = 0; i < q; i++) { int t = nextInt(); switch (t) { case 1: case 2: nextInt(); ans = 1 - ans; break; case 3: out.print(ans); break; } } } String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.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()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
fe13510d04876091b4945fc162da02a6
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.BitSet; import java.util.Random; public class A { public static void main(String[] args) { long t = System.currentTimeMillis(); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tc = 0; while (true) { String line = br.readLine(); if (line == null) break; System.err.println("--------------TEST CASE " + ++tc + "---------------"); System.err.println("INPUT"); System.err.println(line); int n = Integer.parseInt(line); boolean[][] a = new boolean[n][n]; for (int i = 0; i < n; i++) { line = br.readLine(); boolean[] ai = a[i]; for (int j = 0; j < n; j++) { if (line.charAt(j << 1) == '1') ai[j] = true; } } boolean u = false; for (int i = 0; i < n; i++) { u ^= a[i][i]; } StringBuilder sb = new StringBuilder(); line = br.readLine(); System.err.println(line); int q = Integer.parseInt(line); for (int i = 0; i < q; i++) { line = br.readLine(); int v = line.charAt(0) - '0'; if (v == 1 || v == 2) { u = !u; } else if (v == 3) { sb.append(u ? 1 : 0); } } System.err.println("\nOUTPUT"); System.out.println(sb); System.err.println("T=" + (System.currentTimeMillis() - t)); } } catch (IOException io) { io.printStackTrace(); } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
d89e5930eea18328afe045b0420994c9
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
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 AA { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int[][]a = new int[n+1][n+1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { a[i][j] = nextInt(); } } int sum = 0; for (int i = 1; i <= n; i++) { sum += a[i][i]; } sum %= 2; int q = nextInt(); while (q-->0) { int t = nextInt(); if (t <= 2) { int x = nextInt(); sum -= a[x][x]; if (sum < 0) sum += 2; a[x][x] = 1-a[x][x]; sum += a[x][x]; if (sum >= 2) sum -= 2; } else { pw.print(sum); } } pw.close(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
2c61b82184ae695650e4f945ea0cf116
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.BitSet; import java.util.StringTokenizer; /** * * @author Aditya Joshi */ public class Main { public static void main(String[] args) { MyScanner sc = new MyScanner(); int n = sc.nextInt(); int[][] grid = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { grid[i][j] = sc.nextInt(); } } Collection[] Set = new Collection[n]; int total_ones = 0; for(int i = 0; i < n; i++) { Set[i] = new Collection(grid[i][i]); int acc = 0; for(int j = 0; j < n; j++) { acc += (grid[i][j] * grid[j][i]); if(i != j) { int one = grid[i][j]; int two = grid[j][i]; if(one == 1 && two == 0) Set[i].mask[0] += 1; else if(one == 0 && two == 0) Set[i].mask[1] += 1; else if(one == 1 && two == 1) Set[i].mask[2] += 1; else Set[i].mask[3] += 1; } } acc = (acc % 2); if(acc == 1) total_ones += 1; } long q = sc.nextLong(); StringBuilder answer = new StringBuilder(); for(long x = 0; x < q; x++) { int option = sc.nextInt(); if(option == 3) { if(total_ones % 2 == 0) answer.append(0); else answer.append(1); } else if(option == 2) { int which_one = sc.nextInt(); int before = Set[which_one - 1].count(); Set[which_one - 1].col_flip(); if(Set[which_one - 1].count() == 1 && before == 0) total_ones += 1; else if(Set[which_one - 1].count() == 0 && before == 1) total_ones -= 1; } else { int which_one = sc.nextInt(); int before = Set[which_one - 1].count(); Set[which_one - 1].row_flip(); if(Set[which_one - 1].count() == 1 && before == 0) total_ones += 1; else if(Set[which_one - 1].count() == 0 && before == 1) total_ones -= 1; } } System.out.println(answer.toString()); } public static class Collection { int[] mask; int special; public Collection(int s) { mask = new int[4]; this.special = s; } public void row_flip() { if(special == 0) special = 1; else special = 0; for(int i = 0; i < 4; i++) { if(i == 0) { mask[0] -= 1; mask[1] += 1; } else if(i == 1) { mask[1] -= 1; mask[0] += 1; } else if(i == 2) { mask[2] -= 1; mask[3] += 1; } else { mask[3] -= 1; mask[2] += 1; } } } public void col_flip() { if(special == 0) special = 1; else special = 0; for(int i = 0; i < 4; i++) { if(i == 0) { mask[0] -= 1; mask[2] += 1; } else if(i == 1) { mask[1] -= 1; mask[3] += 1; } else if(i == 2) { mask[2] -= 1; mask[0] += 1; } else { mask[3] -= 1; mask[1] += 1; } } } public int count() { int cnt = mask[2]; if(special == 1) cnt += 1; return cnt%2; } } 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; } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
1f3e4be49adb0f3a5b01ab8c2ff66cc3
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.util.*; import java.io.*; public class Unusual { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder output = new StringBuilder(); int n = Integer.parseInt(br.readLine()); int[] diag = new int[n]; int count = 0; for (int i = 0; i < n; ++i) { String[] line = (br.readLine()).split(" "); for (int j = 0; j < n; ++j) { if (i == j) { diag[i] = Integer.parseInt(line[j]); count += diag[i]; } } } int q = Integer.parseInt(br.readLine()); while (q-->0) { String[] line = (br.readLine()).split(" "); int type = Integer.parseInt(line[0]); if (type < 3) { int idx = Integer.parseInt(line[1]); --idx; diag[idx] = 1 - diag[idx]; ++count; } else { output.append(count & 1); } } System.out.println(output); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
e0eb6f73f02b5b0b8cc3fc73cd1a68f6
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws Exception{ int n = readInt(); StringBuilder sb = new StringBuilder(); int[][] matrix = new int[n][n]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ matrix[i][j] = readInt(); } } int usq = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(matrix[i][j] == 1 && matrix[j][i] == 1){ usq++; usq %=2; } } } int q = readInt(); for(int i = 0; i < q; i++){ int t = readInt(); if(t == 3){ sb.append(usq); } else{ readInt(); usq++; usq%=2; } } System.out.println(sb); } static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(" "); static String readString() throws Exception{ while(!st.hasMoreTokens()){ st = new StringTokenizer(stdin.readLine()); } return st.nextToken(); } static int readInt() throws Exception { return Integer.parseInt(readString()); } static long readLong() throws Exception { return Long.parseLong(readString()); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
e350a11bf40b6aba43ac49d52e36d1d2
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.util.*; import java.io.*; public class A { public static long time = 0; public static void main(String[] args) throws Exception { time = System.currentTimeMillis(); IN = System.in; OUT = System.out; in = new BufferedReader(new InputStreamReader(IN)); out = new PrintWriter(OUT, FLUSH); solveOne(); out.flush(); } public static void solveOne() throws Exception { int n1= ni(); int count = 0; for (int i = 0 ; i < n1 ; i++){ for (int j =0; j < n1; j++){ int cur = ni(); if (i == j){ count += cur; } } } int q1 = ni(); StringBuilder fin= new StringBuilder(); for (int i =0; i < q1; i++){ int type = ni(); if (type != 3){ ni(); count++; } else { fin.append(count & 1); } } pn(fin); } public static void solveTwo() throws Exception { } public static void solveThree() throws Exception { } public static BufferedReader in; public static StringTokenizer st; public static InputStream IN; public static OutputStream OUT; public static String nx() throws Exception { for (; st == null || !st.hasMoreTokens();) { String k1 = in.readLine(); if (k1 == null) return null; st = new StringTokenizer(k1); } return st.nextToken(); } public static int ni() throws Exception { return Integer.parseInt(nx()); } public static long nl() throws Exception { return Long.parseLong(nx()); } public static double nd() throws Exception { return Double.parseDouble(nx()); } public static void px(Object... l1) { System.out.println(Arrays.deepToString(l1)); } public static boolean FLUSH = false; public static PrintWriter out; public static void p(Object... l1) { for (int i = 0; i < l1.length; i++) { if (i != 0) out.print(' '); out.print(l1[i].toString()); } } public static void pn(Object... l1) { for (int i = 0; i < l1.length; i++) { if (i != 0) out.print(' '); out.print(l1[i].toString()); } out.println(); } public static void pn(Collection l1) { boolean first = true; for (Object e : l1) { if (first) first = false; else out.print(' '); out.print(e.toString()); } out.println(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
a522b95ee1b601fd59f982ef346456ed
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; 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(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[][] a = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = in.nextInt(); } } int cur = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cur ^= a[i][j] & a[j][i]; } } int q = in.nextInt(); for (int i = 0; i < q; i++) { int t = in.nextInt(); if (t == 3) out.print(cur); else { in.nextInt(); cur ^= 1; } } } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } 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
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
ea641da2b6e5ca17335c0af24bdddfa3
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.util.*; public class R238qAUnusualProduct { public static void main(String args[]) throws Exception{ InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = in.nextInt(); int a[][] = new int[n][n]; for(int i=0;i<n;i++) for(int j=0;j<n;j++) a[i][j] = in.nextInt(); int ans = 0; for(int i=0;i<n;i++) ans += a[i][i]; ans %= 2; int Q = in.nextInt(); for(int q=0;q<Q;q++){ int type = in.nextInt(); if(type == 1){ int row = in.nextInt() - 1; if(a[row][row] == 1){ a[row][row] = 0; ans -= 1; } else{ a[row][row] = 1; ans += 1; } if(ans == -1) ans = 1; if(ans == 2) ans = 0; } else if(type == 2){ int col = in.nextInt() - 1; if(a[col][col] == 1){ a[col][col] = 0; ans -= 1; } else{ a[col][col] = 1; ans += 1; } if(ans == -1) ans = 1; if(ans == 2) ans = 0; } else{ w.print(ans); } } w.close(); } static public class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } 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); } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
e2d502fad3c4394f179028b1cceed1b0
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; 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 Egor Kulikov (egor@egork.net) */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int size = in.readInt(); int[][] matrix = IOUtils.readIntTable(in, size, size); int answer = 0; for (int i = 0; i < size; i++) answer += matrix[i][i]; int count = in.readInt(); for (int i = 0; i < count; i++) { int type = in.readInt(); if (type == 3) { out.print(answer & 1); } else { int at = in.readInt() - 1; answer -= matrix[at][at]; matrix[at][at] = 1 - matrix[at][at]; answer += matrix[at][at]; } } out.printLine(); } } 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); } } 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 printLine() { writer.println(); } public void close() { writer.close(); } public void print(int i) { writer.print(i); } } 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; } public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) { int[][] table = new int[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readIntArray(in, columnCount); return table; } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
0ac7fb1f5a121b3926980a7bda17ec58
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.util.Scanner; public class CF { public static void main(String[] args) throws Exception { FasterScanner sc = new FasterScanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); int sum = 0; for(int a=0;a<N;a++){ for(int b=0;b<N;b++){ if(sc.next().equals("1")&&a==b)sum++; } } int Q = sc.nextInt(); while(Q-->0){ int O = sc.nextInt(); if(O==3){ out.print(sum&1); } else{ sc.nextInt(); sum++; } } out.close(); } static class FasterScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FasterScanner() { stream = System.in; // stream = new FileInputStream(new File("dec.in")); } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } 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(); } String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
97009409882db6f3b62c15a2589d4cb4
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.ListIterator; import java.util.PriorityQueue; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; public class CopyOfCopyOfSolution { private static Integer val = 40; /** * #235 Div2 Problem D * #href: http://codeforces.com/contest/401/problem/D * * @param args * @throws NumberFormatException * @throws IOException */ public static void main(final String[] args) throws NumberFormatException, IOException { final InputStream inputStream = System.in; final OutputStream outputStream = System.out; final InputReader in = new InputReader(inputStream); final PrintWriter out = new PrintWriter(outputStream); int v = 0; final int n = in.nextInt(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { final int x = in.nextInt(); if (i == j) { v ^= x; } } } final int q = in.nextInt(); for (int i = 0; i < q; i++) { if (in.nextInt() == 3) { out.print(v); } else { in.nextInt(); v ^= 1; } } out.println(); out.close(); } private static Tree construct(final long[] a, final int from, final int to) { final Tree tree = new Tree(); tree.from = 0; tree.to = a.length; if ((to - from) == 1) { tree.sum = a[from]; } else { tree.left = construct(a, from, (from + to) / 2); tree.right = construct(a, (from + to) / 2, to); tree.sum = tree.left.sum + tree.right.sum; } return tree; } private static class Tree { int from; int to; long sum; Tree left; Tree right; public void update(final int index, final long diff) { if (diff == 0) { return; } if ((index >= this.from) && (index < this.to)) { this.sum += diff; if ((this.right != null)) { this.right.update(index, diff); } if ((this.left != null)) { this.left.update(index, diff); } } } } private static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(final InputStream stream) { this.reader = new BufferedReader(new InputStreamReader(stream)); this.tokenizer = null; } public String next() { while ((this.tokenizer == null) || !this.tokenizer.hasMoreTokens()) { try { this.tokenizer = new StringTokenizer(this.reader.readLine()); } catch (final IOException e) { throw new RuntimeException(e); } } return this.tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(this.next()); } public long nextLong() { return Long.parseLong(this.next()); } public double nextDouble() { return Double.parseDouble(this.next()); } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
661c826b5b05dd43ea51193d5f69e625
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
//Author: net12k44 import java.io.*; import java.util.*; //public class Main{//} private void solve() { int n = in.nextInt(); int a[][] = new int[n][n]; for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) a[i][j] = in.nextInt(); int kq = 0; for(int i = 0; i < n; ++i) kq ^= a[i][i]; int m = in.nextInt(); while (m-- > 0){ int type = in.nextInt(); if (type == 3) out.print(kq); else{ int i = in.nextInt(); kq ^= 1; } } } public static void main (String[] args) throws java.lang.Exception { long startTime = System.currentTimeMillis(); out = new PrintWriter(System.out); new Main().solve(); //out.println((String.format("%.2f",(double)(System.currentTimeMillis()-startTime)/1000))); out.close(); } static PrintWriter out; static class in { static BufferedReader reader = new BufferedReader( new InputStreamReader(System.in) ) ; static StringTokenizer tokenizer = new StringTokenizer(""); static String next() { while ( !tokenizer.hasMoreTokens() ) try { tokenizer = new StringTokenizer( reader.readLine() ); } catch (IOException e){ throw new RuntimeException(e); } return tokenizer.nextToken(); } static int nextInt() { return Integer.parseInt( next() ); } static double nextDouble(){ return Double.parseDouble( next() ); } } ////////////////////////////////////////////////// }//
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
138ce07c85a4ebc007646bb16564604e
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Round238_Div1_A { public void solve() throws Exception { InputReader in = new InputReader(); int n = in.nextInt(); byte res = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (in.nextInt() == 1 && i == j) res ^= 1; int q = in.nextInt(); StringBuffer ans = new StringBuffer(); for (int i = 0; i < q; i++) if (in.nextInt() == 3) ans.append(res); else { in.next(); res ^= 1; } System.out.println(ans); } public static void main(String[] args) throws Exception { new Round238_Div1_A().solve(); } static class InputReader { BufferedReader in; StringTokenizer st; public InputReader() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(in.readLine()); } public String next() throws IOException { while (!st.hasMoreElements()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
000decaf4eb05131d3364c8c8f69c6f0
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.regex.Pattern; public class A { public static void main(String[] args) throws IOException { Pattern pattern = Pattern.compile("\\s+"); BufferedReader bi = new BufferedReader(new InputStreamReader(System.in)); String ns = bi.readLine(); int n = Integer.parseInt(ns); int count = 0; for (int i = 0; i < n; i++) { if (pattern.split(bi.readLine())[i].equals("1")) count = 1 - count; } int q = Integer.parseInt(bi.readLine()); StringBuilder result = new StringBuilder(); for (int i = 0; i < q; i++) { String s = bi.readLine() ; switch (s.charAt(0)) { case '1': case '2': count = 1 - count; break; case '3': result.append(count); break; } } System.out.println(result); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
17fe5401ffe03dcfd4c7fdf5c24407c0
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * @author Vadim Semenov */ 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(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int counter = in.nextInt(); boolean answer = false; for (int i = 0; i < counter; i++) { for (int j = 0; j < counter; j++) { int foo = in.nextInt(); if (i == j) { answer ^= 1 == foo; } } } int queries = in.nextInt(); for (int q = 0; q < queries; q++) { int type = in.nextInt(); if (type == 1 || type == 2) { in.nextInt(); answer ^= true; } else if (type == 3) { out.print(answer ? 1 : 0); } else { throw new RuntimeException(); } } } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
2b298606abb237d3ee7e1796e3092c8b
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.IOException; public class Main{ public static void main(String[] args) throws IOException{ BufferedReader bi = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bo = new BufferedWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(bi.readLine()); int[][] matrix = new int[n][n]; for(int i = 0; i < n; ++i){ String l = bi.readLine(); int j = 0; for(String num : l.split("\\s")){ matrix[i][j] = Integer.parseInt(num); ++j; } } int result = 0; for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j){ result += matrix[i][j]*matrix[j][i]; result &= 1; } } int q = Integer.parseInt(bi.readLine()); for(int i = 0; i < q; ++i){ String l = bi.readLine(); switch(l.charAt(0)){ case '1': case '2': result = 1-result; break; case '3': bo.write(result+'0'); break; } } bo.newLine(); bo.flush(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
4c2952da17f18b1e893d1ede77cde082
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; public class Main { InputReader in; PrintWriter out; void run(){ /*try { out = new PrintWriter(new FileOutputStream("output.txt")); in = new InputReader(new FileInputStream("input.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); }*/ out = new PrintWriter(new OutputStreamWriter(System.out)); in = new InputReader(System.in); solve(); out.flush(); } public static void main(String[] args){ new Main().run(); } void solve() { int n = in.ni(); int[][] m = new int[n][n]; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) m[i][j] = in.ni(); int[] a = new int[n]; int sum = 0; for(int i = 0; i < n; i++) { a[i] = m[i][i]; sum += a[i]; } int q = in.ni(); while(q-- > 0) { int op = in.ni(); if(op == 1 || op == 2) { int idx = in.ni() - 1; sum -= a[idx]; sum += 1 - a[idx]; a[idx] = 1 - a[idx]; } else { int res = (2002 + sum) % 2; out.print(res); } } out.println(); } class InputReader { private boolean finished = false; 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 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 int ni() { 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 nl() { 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 ns() { 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 boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(ns()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { 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, ni()); 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, ni()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean eof() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } public String next() { return ns(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
2680c15ddf96001a4229eea4a16b899b
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException{ InputStream inputStream = System.in; OutputStream outputStream = System.out; //InputStream inputStream = new FileInputStream("input.txt"); //OutputStream outputStream = new FileOutputStream("output.txt"); InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(in, out); out.close(); } } class TaskA { public void solve(InputReader in, OutputWriter out) { int n = in.nextInt(); int[][] a = new int[n][n]; for(int i=0; i<n; i++) a[i] = in.nextIntArray(n); int ans=0; for(int i=0; i<n; i++) if(a[i][i]==1) ans^=1; int q = in.nextInt(); for(int i=0; i<q; i++){ int type = in.nextInt(); if(type==3){ out.write(ans); }else{ int ind = in.nextInt()-1; ans^=1; } } } } class InputReader{ BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream){ tokenizer = null; reader = new BufferedReader(new InputStreamReader(stream)); } public String next(){ while(tokenizer==null || !tokenizer.hasMoreTokens()){ try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(); } } return tokenizer.nextToken(); } public String nextLine(){ tokenizer = null; try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(); } } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public int[] nextIntArray(int n){ int[] res = new int[n]; for(int i=0; i<n; i++) res[i] = nextInt(); return res; } } class OutputWriter{ PrintWriter out; public OutputWriter(OutputStream stream){ out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(stream))); } public void write(Object ...o){ for(Object cur : o) out.print(cur); } public void writeln(Object ...o){ write(o); out.println(); } public void flush(){ out.flush(); } public void close(){ out.close(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
45ce8a0149a49f68ec953409e4532af8
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Scanner; /** * Created by hama_du on 2014/03/23. */ public class ProblemA { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int N = in.nextInt(); int[][] A = new int[N][N]; for (int i = 0 ; i < N ; i++) { for (int j = 0 ; j < N ; j++) { A[i][j] = in.nextInt(); } } int sum = 0; for (int i = 0 ; i < N ; i++) { for (int j = 0 ; j < N ; j++) { sum += A[i][j] * A[j][i]; } } sum %= 2; int q = in.nextInt(); while (--q >= 0) { int type = in.nextInt(); if (type == 1 || type == 2) { in.nextInt(); sum = 1 - sum; } else { out.print(sum); } } out.println(); out.flush(); } public static void debug(Object... obj) { System.err.println(Arrays.toString(obj)); } 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 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 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 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); } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
80df3ddfcd0f33fe18ff3efd3ee4c029
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.util.*; public class A_238 { static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(""); public static void main(String[] args) throws Exception { int n = readInt(); boolean[][] t = new boolean[n][n]; for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) t[i][j] = readInt() == 1; int sum = 0; for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) sum += t[i][j] && t[j][i] ? 1 : 0; sum = sum%2; int q = readInt(); StringBuilder s = new StringBuilder(); for(int i = 0; i < q; ++i) { int op = readInt(); if(op == 3) s.append(sum); else if(op== 2 || op == 1) { readInt(); sum = (sum+1)%2; } } System.out.println(s); } static String readString() throws Exception { while(!st.hasMoreTokens()) st = new StringTokenizer(stdin.readLine()); return st.nextToken(); } static int readInt() throws Exception { return Integer.parseInt(readString()); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
712a9fcf4dda229bdc513e28623bdfbd
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class A { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String tempX = br.readLine(); int n = Integer.parseInt(tempX); boolean[][] t = new boolean[n][n]; for (int i = 0; i < n; i++) { String[] temp = br.readLine().split(" "); for (int j = 0; j < n; j++) { t[i][j] = temp[j].charAt(0) == '1'; } } tempX = br.readLine(); int m = Integer.parseInt(tempX); StringBuilder sb = new StringBuilder(); boolean rez = false; for (int i = 0; i < n; i++) { if (t[i][i]) rez = !rez; } for (int i = 0; i < m; i++) { String[] temp = br.readLine().split(" "); switch (temp[0].charAt(0)) { case '1': case '2': rez = !rez; break; case '3': { sb.append(rez ? '1' : '0'); } } } System.out.println(sb); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
92e5f4c08cb7112c6fa02f83731082de
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { final boolean isFileIO = false; BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); String delim = " "; public static void main(String[] args) { new Thread(null, new Main(), "", 268435456).start(); } public void run() { try { initIO(); solve(); out.close(); } catch(Exception e) { e.printStackTrace(System.err); System.exit(-1); } } public void initIO() throws IOException { if(!isFileIO) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String nextToken() throws IOException { if(!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(delim); } String readLine() throws IOException { return in.readLine(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } void solve() throws IOException { int n = nextInt(); int[][] a = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i][j] = nextInt(); } } int[] diag = new int[n]; for(int i = 0; i < n; i++) { diag[i] = a[i][i]; } int cnt = 0; for(int i = 0; i < n; i++) cnt += diag[i]; int q = nextInt(); StringBuilder sb = new StringBuilder(); for(int i = 0; i < q; i++) { int t = nextInt(); if(t == 1 || t == 2) { int j = nextInt(); if(diag[j - 1] == 1) { cnt--; } else { cnt++; } diag[j - 1] = 1 - diag[j - 1]; } if(t == 3) { sb.append(cnt % 2); } } out.println(sb); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
d6424f92d43a5bca89051dd0e90456b0
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
//package round238; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[][] map = new int[n][n]; for(int i = 0;i < n;i++){ for(int j = 0;j < n;j++){ map[i][j] = ni(); } } int Q = ni(); int x = 0; for(int i = 0;i < n;i++){ x ^= map[i][i]; } for(int i = 0;i < Q;i++){ int t = ni(); if(t == 3){ out.print(x); }else{ ni(); x ^= 1; } } out.println(); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
1d4624debe530d276ecbe3c362920f60
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Mahmoud Aladdin <aladdin3> */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader jin, OutputWriter jout) { int n = jin.int32(); int sum = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { int x = jin.int32(); if(i == j) sum += x; } } int q = jin.int32(); while(q-- > 0) { int type = jin.int32(); if(type == 3) { jout.write(sum % 2); } else { jin.int32(); sum += 1; } } jout.writeLine(); } } class InputReader { private static final int bufferMaxLength = 1024; private InputStream in; private byte[] buffer; private int currentBufferSize; private int currentBufferTop; private static final String tokenizers = " \t\r\f\n"; public InputReader(InputStream stream) { this.in = stream; buffer = new byte[bufferMaxLength]; currentBufferSize = 0; currentBufferTop = 0; } private boolean refill() { try { this.currentBufferSize = this.in.read(this.buffer); this.currentBufferTop = 0; } catch(Exception e) {} return this.currentBufferSize > 0; } private Byte readChar() { if(currentBufferTop < currentBufferSize) { return this.buffer[this.currentBufferTop++]; } else { if(!this.refill()) { return null; } else { return readChar(); } } } public String token() { StringBuffer tok = new StringBuffer(); Byte first; while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) != -1)); if(first == null) return null; tok.append((char)first.byteValue()); while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) == -1)) { tok.append((char)first.byteValue()); } return tok.toString(); } public Integer int32() throws NumberFormatException { String tok = token(); return tok == null? null : Integer.parseInt(tok); } } class OutputWriter { private final int bufferMaxOut = 1024; private PrintWriter out; private StringBuilder output; private boolean forceFlush = false; public OutputWriter(OutputStream outStream) { out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outStream))); output = new StringBuilder(2 * bufferMaxOut); } public OutputWriter(Writer writer) { forceFlush = true; out = new PrintWriter(writer); output = new StringBuilder(2 * bufferMaxOut); } private void autoFlush() { if(forceFlush || output.length() >= bufferMaxOut) { flush(); } } public void write(Object... tokens) { for(int i = 0; i < tokens.length; i++) { if(i != 0) output.append(' '); output.append(tokens[i]); } autoFlush(); } public void writeLine(Object... tokens) { write(tokens); output.append('\n'); autoFlush(); } public void flush() { out.print(output); output.setLength(0); } public void close() { flush(); out.close(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
539b8bab3313f048da2aba45af99a068
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; public class Program { public static void main(String[] args) throws IOException { boolean isDebugMode = Arrays.asList(args).contains("DEBUG_MODE"); InputStream inputStream; OutputStream outputStream; if (isDebugMode) { inputStream = new FileInputStream().open(); // outputStream = new FileOutputStream().open(); outputStream = new ConsoleOutputStream().open(); } else { inputStream = new ConsoleInputStream().open(); outputStream = new ConsoleOutputStream().open(); } new Program().run(inputStream, outputStream, isDebugMode); outputStream.close(); inputStream.close(); } private InputStream in; private OutputStream out; private boolean isDebugMode; private Timer timer = new Timer(); private void printTimer(String mark) { out.println(mark + " " + timer.getMillisAndReset()); } private void run(InputStream in, OutputStream out, boolean isDebugMode) throws IOException { this.in = in; this.out = out; this.isDebugMode = isDebugMode; // int t = in.nextInt(); // for (int i = 0; i < t; i++) { solve(); // out.flush(); // } } private void solve() throws IOException { int n = in.nextInt(); int s = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int c = in.nextInt(); if (i == j) { s += c; } } } int q = in.nextInt(); for (int i = 0; i < q; i++) { int z = in.nextInt(); if (z < 3) { in.nextInt(); s++; } else { out.print(s % 2); } } } // template beginning // Author: Andrey Siunov // Date: 29.08.2013 // Note: all classes are inner, because some testing servers do not run code with several classes private static class SegmentTree { public static interface MergeFunction { long calcValue(long first, long second); } private MergeFunction mergeFunction; private int n; private long[] values; public SegmentTree(ArrayList<Long> collection, MergeFunction mergeFunction) { this.mergeFunction = mergeFunction; n = collection.size(); values = new long[n * 4]; build(collection, 1, 0, n - 1); } private void build(ArrayList<Long> collection, int v, int tl, int tr) { if (tl == tr) { values[v] = collection.get(tl); } else { int tm = (tl + tr) >> 1; build(collection, v << 1, tl, tm); build(collection, (v << 1) + 1, tm + 1, tr); values[v] = mergeFunction.calcValue(values[v << 1], values[(v << 1) + 1]); } } public long getValue(int index) { return getValue(index, index); } public long getValue(int l, int r) { return getValue(1, 0, n - 1, l, r); } private Long getValue(int v, int tl, int tr, int l, int r) { if (l > r) { return null; } if (l == tl && r == tr) { return values[v]; } int tm = (tl + tr) >> 1; Long leftValue = getValue(v << 1, tl, tm, l, Math.min(r, tm)); Long rightValue = getValue((v << 1) + 1, tm + 1, tr, Math.max(l, tm + 1), r); return leftValue == null ? rightValue : (rightValue == null ? leftValue : mergeFunction.calcValue(leftValue, rightValue)); } } private static class Pair<K, V> { private K key; private V value; Pair(K key, V value) { this.key = key; this.value = value; } K getKey() { return key; } V getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (key != null ? !key.equals(pair.key) : pair.key != null) return false; if (value != null ? !value.equals(pair.value) : pair.value != null) return false; return true; } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); return result; } @Override public String toString() { return "Pair{" + "key=" + key + ", value=" + value + '}'; } } private static class Timer { private long lastTime = 0; private Timer() { lastTime = System.currentTimeMillis(); } public void reset() { lastTime = System.currentTimeMillis(); } public long getMillisAndReset() { long current = System.currentTimeMillis(); long result = current - lastTime; lastTime = current; return result; } } // IO template { private static class FileInputStream extends InputStream { private String inputFileName; public FileInputStream() throws IOException { this("input.txt"); } public FileInputStream(String inputFileName) throws IOException { this.inputFileName = inputFileName; } @Override protected Reader getReader() throws IOException { return new FileReader(inputFileName); } } private static class ConsoleInputStream extends InputStream { @Override protected Reader getReader() throws IOException { return new InputStreamReader(System.in); } } private static abstract class InputStream { private static String DELIMITERS = " \t\n\r\f"; private BufferedReader in; public InputStream open() throws IOException { in = new BufferedReader(getReader()); return this; } private class Line { private Line(String inputLine) { this.inputLine = inputLine; stringTokenizer = new StringTokenizer(this.inputLine, DELIMITERS); readCharacters = 0; } private int readCharacters; private String inputLine = null; private StringTokenizer stringTokenizer = null; public String nextToken() { String result = stringTokenizer.nextToken(); readCharacters += result.length(); return result; } boolean hasNextToken() { return stringTokenizer.hasMoreTokens(); } String getLineRest() { int position = 0; for (int remain = readCharacters; remain > 0; position++) { if (DELIMITERS.indexOf(inputLine.charAt(position)) < 0) { remain--; } } return inputLine.substring(position); } } private Line currentLine = null; abstract protected Reader getReader() throws IOException; /** * Note: may be incorrect behavior if use this method with hasNextToken method */ public String nextLine() throws IOException { setInputLine(); if (currentLine == null) { return null; } String result = currentLine.getLineRest(); currentLine = null; return result; } public boolean hasNextLine() throws IOException { setInputLine(); return currentLine != null; } public String nextToken() throws IOException { return hasNextToken() ? currentLine.nextToken() : null; } /** * Note: may be incorrect behavior if use this method with nextLine method */ public boolean hasNextToken() throws IOException { while (true) { setInputLine(); if (currentLine == null || currentLine.hasNextToken()) { break; } else { currentLine = null; } } return currentLine != null; } public int nextInt() throws IOException { return new Integer(this.nextToken()); } public long nextLong() throws IOException { return new Long(this.nextToken()); } public double nextDouble() throws IOException { return new Double(this.nextToken()); } public BigInteger nextBigInteger() throws IOException { return new BigInteger(this.nextToken()); } public String[] nextTokensArray(int n) throws IOException { String[] result = new String[n]; for (int i = 0; i < n; i++) { result[i] = this.nextToken(); } return result; } public int[] nextIntArray(int n) throws IOException { int[] result = new int[n]; for (int i = 0; i < n; i++) { result[i] = this.nextInt(); } return result; } public long[] nextLongArray(int n) throws IOException { long[] result = new long[n]; for (int i = 0; i < n; i++) { result[i] = this.nextLong(); } return result; } public void close() throws IOException { currentLine = null; in.close(); } private void setInputLine() throws IOException { if (currentLine == null) { String line = in.readLine(); if (line != null) { currentLine = new Line(line); } } } } private static class FileOutputStream extends OutputStream { private String outputFileName; public FileOutputStream() throws IOException { this("output.txt"); } public FileOutputStream(String outputFileName) throws IOException { this.outputFileName = outputFileName; } @Override protected Writer getWriter() throws IOException { return new FileWriter(outputFileName); } } private static class ConsoleOutputStream extends OutputStream { @Override protected Writer getWriter() throws IOException { return new OutputStreamWriter(System.out); } } private static abstract class OutputStream { private PrintWriter out; public OutputStream open() throws IOException { out = new PrintWriter(getWriter()); return this; } abstract protected Writer getWriter() throws IOException; public void print(Object... s) { for (Object token : s) { out.print(token); } } public void println(Object... s) { print(s); out.println(); } public void println() { out.println(); } public void flush() throws IOException { out.flush(); } public void close() throws IOException { out.flush(); out.close(); } } // } IO template }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
5a8f3e7419e4a18d5aa6b4cab289852c
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.util.*; public class Solution { // TODO: do not forget private static final int DEBUG = 0; private static void run(InputReader in, PrintWriter out) { int n = in.nextInt(); int cnt = 0; for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) { char c = in.nextCharacter(); if(i == j) cnt ^= (c == '1' ? 1 : 0); } int q = in.nextInt(); for(int i = 0; i < q; ++i) { char a = in.nextCharacter(); if(a < '3') { cnt = 1 - cnt; a = in.nextCharacter(); } else { out.print(cnt); } } } public static void main(String[] args) { Solution solution = new Solution(); InputReader in; if(DEBUG == 1) { try { in = solution.new InputReader(new FileInputStream("input.txt")); } catch (IOException e) { throw new RuntimeException(e); } } else { in = solution.new InputReader(System.in); } PrintWriter out = new PrintWriter(System.out); run(in, out); out.flush(); out.close(); } private class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } 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()); } public double nextDouble() { return Double.parseDouble(next()); } public char nextCharacter() { return next().charAt(0); } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
38b821b3001caaa8b7c8b3c6e97bdf97
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.util.*; public class Solution { // TODO: do not forget private static final int DEBUG = 0; private static void run(InputReader in, PrintWriter out) { int n = in.nextInt(); int cnt = 0; for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) { int c = in.nextInt(); if(i == j) cnt ^= c; } int q = in.nextInt(); for(int i = 0; i < q; ++i) { int a = in.nextInt(); if(a < 3) { cnt = 1 - cnt; a = in.nextInt(); } else { out.print(cnt); } } } public static void main(String[] args) { Solution solution = new Solution(); InputReader in; if(DEBUG == 1) { try { in = solution.new InputReader(new FileInputStream("input.txt")); } catch (IOException e) { throw new RuntimeException(e); } } else { in = solution.new InputReader(System.in); } PrintWriter out = new PrintWriter(System.out); run(in, out); out.flush(); out.close(); } private class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } 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()); } public double nextDouble() { return Double.parseDouble(next()); } public char nextCharacter() { return next().charAt(0); } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
801a671cb6c9dd57d1877a44d4f947ba
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.util.*; public class A { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; int val = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int x = nextInt(); if (i == j) { a[i] = x; val ^= x; } } } int q = nextInt(); while (q-- > 0) { int type = nextInt(); if (type <= 2) { int ind = nextInt(); val ^= 1; } else { out.print(val); } } } A() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new A(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
0f20e43c889249ce17448062ee2626a4
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { static BufferedReader br; static PrintWriter out; static StringTokenizer tokenizer; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); tokenizer = new StringTokenizer(br.readLine()); int n = Integer.parseInt(tokenizer.nextToken()); int[]a = new int[n]; int c=0; for(int i=0;i<n;i++){ tokenizer = new StringTokenizer(br.readLine()); for(int j=0;j<n;j++){ c = Integer.parseInt(tokenizer.nextToken()); if(i==j)a[i] = c; } } int currentres = 0; for(int i=0;i<n;i++) currentres+=a[i]; currentres%=2; tokenizer = new StringTokenizer(br.readLine()); int q = Integer.parseInt(tokenizer.nextToken()); for(int i=0;i<q;i++){ tokenizer = new StringTokenizer(br.readLine()); c = Integer.parseInt(tokenizer.nextToken()); if(c==3){ if(currentres==1)out.append('1'); else out.append('0'); }else{ currentres++; currentres%=2; } } out.flush(); out.close(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
f1a374800da8f14f114b0d18aafdc88b
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.util.*; import java.io.*; import java.awt.Point; import java.math.BigDecimal; import java.math.BigInteger; import static java.lang.Math.*; // Solution is at the bottom of code public class A implements Runnable{ final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; OutputWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new A(), "", 128 * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeBegin = System.currentTimeMillis(); Locale.setDefault(Locale.US); init(); solve(); out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// String delim = " "; String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(delim); } String readLine() throws IOException{ return in.readLine(); } ///////////////////////////////////////////////////////////////// final char NOT_A_SYMBOL = '\0'; char readChar() throws IOException{ int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } char[] readCharArray() throws IOException{ return readLine().toCharArray(); } ///////////////////////////////////////////////////////////////// int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } int[] readIntArrayWithDecrease(int size) throws IOException { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// long readLong() throws IOException{ return Long.parseLong(readString()); } long[] readLongArray(int size) throws IOException{ long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// double readDouble() throws IOException{ return Double.parseDouble(readString()); } double[] readDoubleArray(int size) throws IOException{ double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// BigInteger readBigInteger() throws IOException { return new BigInteger(readString()); } BigDecimal readBigDecimal() throws IOException { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// Point readPoint() throws IOException{ int x = readInt(); int y = readInt(); return new Point(x, y); } Point[] readPointArray(int size) throws IOException{ Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// List<Integer>[] readGraph(int vertexNumber, int edgeNumber) throws IOException{ @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<Integer>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } ///////////////////////////////////////////////////////////////////// static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<A.IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<A.IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; int value, index; public IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } public int getRealIndex() { return index + 1; } } IntIndexPair[] readIntIndexArray(int size) throws IOException { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// static class OutputWriter extends PrintWriter{ final int DEFAULT_PRECISION = 12; int precision; String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } public OutputWriter(OutputStream out) { super(out); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public int getPrecision() { return precision; } public void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } private String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } public void printWithSpace(double d){ printf(formatWithSpace, d); } public void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @Override public void println(double d){ printlnAll(d); } public void printlnAll(double... d){ printAll(d); println(); } } ///////////////////////////////////////////////////////////////////// int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; boolean check(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// boolean checkBit(int mask, int bit){ return (mask & (1 << bit)) != 0; } ///////////////////////////////////////////////////////////////////// void solve() throws IOException { int n = readInt(); int[][] a = new int[n][]; for (int i = 0; i < n; ++i) { a[i] = readIntArray(n); } // int[] rows = new int[n]; // int[] columns = new int[n]; // int[] sums = new int[n]; boolean square = false; for (int i = 0; i < n; ++i) { // for (int j = 0; j < n; ++j) { // if (j == i) { // totalSum += a[i][j]; // } else { // sums[i] += a[i][j] * a[j][i]; // rows[i] += a[i][j]; // columns[j] += a[i][j]; // } // } square ^= (a[i][i] == 1); } // for (int sum: sums) { // totalSum += sum; // } int q = readInt(); for (int i = 0; i < q; ++i) { int type = readInt(); if (type == 3) { out.print(square? 1: 0); } else { readInt(); square ^= true; } } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
d183de6e5f69f5fb8d57eedacebacf80
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author George Marcus */ 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(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int[][] A = new int[N][N]; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { A[i][j] = in.nextInt(); } } int S = 0; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) if((A[i][j] & A[j][i]) > 0) S = 1 - S; } int Q = in.nextInt(); StringBuilder stringBuilder = new StringBuilder(); for(int i = 0; i < Q; i++) { int t = in.nextInt(); if(t == 3) stringBuilder.append(S); else { int x = in.nextInt(); S = 1 - S; } } out.println(stringBuilder.toString()); } } 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 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() { return Integer.parseInt(nextString()); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
1ff84194fdbdf04e4a8d1d3818c76877
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import static java.lang.Math.*; import java.io.*; import java.util.*; public class Template { BufferedReader in; PrintWriter out; StringTokenizer st; String next() { while (st==null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (Exception e) {} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[][] a; int n,m; Tree[] t; class Tree { int[] le, ri; long[] s; boolean[] all; public Tree(int n) { // a = new int[4 * n]; le = new int[4 * n]; ri = new int[4 * n]; s = new long[4 * n]; all = new boolean[4 * n]; } public void update(int p, int v) { update(1, 1, n, p, v); } public void update(int v, int l, int r, int p, int val) { if (l > p || r < p) return; if (l == r) { //a[v] = val; if (val == 1) le[v] = 1; else le[v] = 0; if (val == 1) ri[v] = 1; else ri[v] = 0; if (val == 1) s[v] = 1; else s[v] = 0; if (val == 1) all[v] = true; else all[v] = false; return; } int m = (l+r) / 2; update(v*2, l, m, p, val); update(v*2+1, m+1, r, p, val); long sl = s[v*2] - ri[v*2]*(ri[v*2] + 1L)/2; long sr = s[v*2+1] - le[v*2+1]*(le[v*2+1] + 1L)/2; long mid = ri[v*2] + le[v*2+1]; mid = mid * (mid + 1L) / 2; s[v] = sl + sr + mid; all[v] = all[v*2] & all[v*2+1]; ri[v] = ri[v*2+1] + (all[v*2+1] ? ri[v*2] : 0); le[v] = le[v*2] + (all[v*2] ? le[v*2+1] : 0); } } int bit(int x, int p) { if ((x & (1 << p)) > 0) return 1; else return 0; } int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } boolean[] was; int cur; void dfs(int v) { if (cur != v) was[v] = true; for (int j=0; j<n; j++) if (a[v][j] > 0) { if (j==cur) { was[cur] = true; continue; } if (!was[j]) dfs(j); } } public void run() throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); Long start = System.currentTimeMillis(); n = nextInt(); a = new int[n][n]; cur = 0; for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { a[i][j] = nextInt(); if (i==j) cur+=a[i][j]; } } int m = nextInt(); for (int i=0; i<m; i++) { int type = nextInt(); if (type < 3) { int r = nextInt() - 1; if (a[r][r] == 0) { cur++; a[r][r] = 1; } else { cur--; a[r][r] = 0; } } else { out.print(cur % 2); } } Long end = System.currentTimeMillis(); //System.out.println((end - start) / 1000.0); out.close(); } public static void main(String[] args) throws Exception { new Template().run(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
78ebf2233ad3906f53794277c0cb5a7f
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.util.*; public class ProblemA { FastScanner in; PrintWriter out; public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); Locale.setDefault(Locale.US); int n = in.nextInt(); boolean matr[][] = new boolean[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) matr[i][j] = (in.nextToken().equals("1")); boolean sum = false; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) sum ^= matr[i][j] && matr[j][i]; int m = in.nextInt(); for (int i = 0; i < m; i++) { int op = in.nextInt(); if (op == 3) out.print(sum ? "1" : "0"); else { sum ^= true; in.nextToken(); } } out.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new ProblemA().run(); } class FastScanner { BufferedReader reader; StringTokenizer tokenizer; FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in)); } FastScanner(String filename) throws FileNotFoundException { reader = new BufferedReader(new FileReader(filename)); } String nextToken() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
78db0e10fd1952e4f78dcea7c044baba
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class A { static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(""); static String readString() throws Exception { while(!st.hasMoreTokens()) st = new StringTokenizer(stdin.readLine()); return st.nextToken(); } static int readInt() throws Exception { return Integer.parseInt(readString()); } public static void main(String[] args) throws Exception{ int n = readInt(); int A[][] = new int [n][n]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ A[i][j] = readInt(); } } int unus = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ unus += A[i][j]*A[j][i]; } } unus = unus%2; StringBuilder ss = new StringBuilder(); int q = readInt(); for(int i = 0; i < q; i++){ int type = readInt(); if(type == 3){ ss.append(unus); } else{ readInt(); unus = unus+1; unus = unus%2; } } System.out.println(ss); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
759f9fd4a828898f8aeb694b902d657e
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); boolean[][] G = new boolean[n][n]; for(int r=0; r<n; r++) { String[] R = in.readLine().split(" "); for(int c=0; c<n; c++) { G[r][c] = Integer.parseInt(R[c])==1; } } BitSet diag = new BitSet(n); for(int r=0; r<n; r++) if(G[r][r]) diag.flip(r); int q = Integer.parseInt(in.readLine()); StringBuilder out = new StringBuilder(); for(int i=0; i<q; i++) { String[] cmd = in.readLine().split(" "); if(cmd[0].equals("1")) { int row = Integer.parseInt(cmd[1])-1; diag.flip(row); } else if(cmd[0].equals("2")) { int col = Integer.parseInt(cmd[1])-1; diag.flip(col); } else { out.append(diag.cardinality()%2); } } System.out.println(out); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
c934f6079eb41247a8c8bbad6a82e7ba
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Scanner; public class A { public static void main(String[] args) { try { new A(); } catch (Exception e) { } } private BufferedReader in; private BufferedWriter out; public A() throws Exception { in = new BufferedReader(new InputStreamReader(System.in )); out = new BufferedWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(in.readLine()); int counter = 0; for (int i = 0; i < n; i++) { String line = in.readLine(); //System.out.println(line); if (line.charAt(2*i) == '1') counter++; } int amount = Integer.parseInt(in.readLine()); boolean square = false; if (counter % 2 == 1) square = true; for (int k = 0; k < amount; k++) { //System.out.println("hello"); int task = Integer.parseInt(""+in.readLine().charAt(0)); if (task == 1) { square = !square; } else if (task == 2) { square = !square; } else { if (square) out.write('1'); else out.write('0'); } } out.newLine(); out.flush(); out.close(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
fe66a4e2fb69fd067a2f2ea985ec8ec1
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.util.*; import java.util.Map.Entry; public class A { void run() throws IOException { int n = ni(); boolean[][] matrix = new boolean[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i][j] = ni() == 1; } } boolean ans = false; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { ans ^= matrix[i][j] & matrix[j][i]; } } int m = ni(); while (--m >= 0) { if (ni() == 3) { pw.print(ans ? '1' : '0'); } else { ni(); ans ^= true; } } } void stress() { Random rnd = new Random(); while (true) { int n = 7 + rnd.nextInt(2); boolean a = false; boolean[][] matrix = new boolean[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i][j] = rnd.nextBoolean(); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a ^= matrix[i][j] & matrix[j][i]; } } int k = rnd.nextInt(n); for (int i = 0; i < n; i++) { matrix[i][k] ^= true; } boolean b = false; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { b ^= matrix[i][j] & matrix[j][i]; } } if (a == b) { System.err.println(a + " " + b); for (int i = 0; i < n; i++) { matrix[i][k] ^= true; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.err.print(matrix[i][j] ? '1' : '0'); } System.err.println(); } System.err.println(); System.err.println(k); for (int i = 0; i < n; i++) { matrix[i][k] ^= true; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.err.print(matrix[i][j] ? '1' : '0'); } System.err.println(); } return; } } } int[][] nm(int a_len, int a_hei) throws IOException { int[][] _a = new int[a_len][a_hei]; for (int i = 0; i < a_len; i++) for (int j = 0; j < a_hei; j++) _a[i][j] = ni(); return _a; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return false; } st = new StringTokenizer(line); } return true; } int[] na(int a_len) throws IOException { int[] _a = new int[a_len]; for (int i = 0; i < a_len; i++) _a[i] = ni(); return _a; } int ni() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } String nl() throws IOException { return br.readLine(); } void tr(String debug) { if (!OJ) pw.println(" " + debug); } static PrintWriter pw; static BufferedReader br; static StringTokenizer st; static boolean OJ; public static void main(String[] args) throws IOException { long timeout = System.currentTimeMillis(); OJ = System.getProperty("ONLINE_JUDGE") != null; pw = new PrintWriter(System.out); br = new BufferedReader(OJ ? new InputStreamReader(System.in) : new FileReader(new File("A.txt"))); while (br.ready()) new A().run(); if (!OJ) { pw.println(); pw.println("----------------------------------"); pw.println(System.currentTimeMillis() - timeout); } //new A().stress(); br.close(); pw.close(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
b498678e5cd5de29a2e7444824b5df1a
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.InputMismatchException; public class Main { static class InputReader { final private int BUFFER_SIZE = 1 << 17; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public InputReader(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public byte next() { try { return read(); } catch (Exception e) { throw new InputMismatchException(); } } public String nextString() { StringBuilder sb = new StringBuilder(""); byte c = next(); while (c <= ' ') { c = next(); } do { sb.append((char) c); c = next(); } while (c > ' '); return sb.toString(); } public int nextInt() { int ret = 0; byte c = next(); while (c <= ' ') { c = next(); } boolean neg = c == '-'; if (neg) { c = next(); } do { ret = (ret << 3) + (ret << 1) + c - '0'; c = next(); } while (c > ' '); if (neg) { return -ret; } return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); } catch (IOException e) { throw new InputMismatchException(); } if (bytesRead == -1) { buffer[0] = -1; } } private byte read() { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } } static int cc=0; public static void main(String[] args) throws NumberFormatException, IOException { // BufferedReader r=new BufferedReader(new FileReader("Case.txt")); InputReader r=new InputReader(System.in); PrintWriter pr=new PrintWriter(System.out); int n=r.nextInt(); int matrix[][]=new int[n][n]; int row[]=new int[n*n]; int col[]=new int[n*n]; int count=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { int x=r.nextInt(); matrix[i][j]=x; } } int res=0; for(int i=0;i<n;i++) { res+=matrix[i][i]*matrix[i][i]; } int m=r.nextInt(); for(int i=0;i<m;i++) { int t=r.nextInt(); if(t==1||t==2) { int ind=r.nextInt(); ind--; res=res-(matrix[ind][ind]*matrix[ind][ind]); matrix[ind][ind]=Math.abs(matrix[ind][ind]-1); res=res+(matrix[ind][ind]*matrix[ind][ind]); } else { pr.print(res%2); } } pr.flush(); pr.close(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
fee18be20bbe265244a6408e62685438
train_002.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
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 A { private static BufferedReader in; private static StringTokenizer st; private static PrintWriter out; public static void main(String[] args) throws NumberFormatException, IOException { in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int a[][] = new int[n+1][n+1]; boolean A[] = new boolean [n+1]; boolean ans = false; for (int i = 1; i <=n; i++) { for (int j = 1; j <=n; j++) { a[i][j] = nextInt(); } A[i] = (a[i][i] == 1); ans = ans ^ A[i]; } int q = nextInt(); for (int i = 0; i < q; i++) { int k = nextInt(); if(k == 1){ int x = nextInt(); ans = !ans; } if(k==2){ int x = nextInt(); ans = !ans; } if(k == 3){ if(ans){ out.print(1); }else{ out.print(0); } } } out.close(); } private static double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } private static long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } private static int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } private static String next() throws IOException { while(!st.hasMoreTokens()){ st = new StringTokenizer(in.readLine()); } return st.nextToken(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
e9e514667473180387ce14abfd3cf0c8
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.util.*; import java.io.*; public class Main { BufferedReader in; PrintWriter out; StringTokenizer str; private String next() throws Exception { if (str == null || !str.hasMoreElements()) str = new StringTokenizer(in.readLine()); return str.nextToken(); } private int nextInt() throws Exception { return Integer.parseInt(next()); } private long nextLong() throws Exception { return Long.parseLong(next()); } Map<Long, Long> map; public void run() throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int Q = nextInt(); map = new HashMap<>(); while(Q-->0) { int kindOf = nextInt(); long v = nextLong(), u = nextLong(); if (kindOf == 1) { long cost = nextLong(); long lca = lca(u, v); // System.out.println("lca (" + u + ", " + v + ") = " + lca); update(u, lca, cost); update(v, lca, cost); // if (map.containsKey(lca)) { // map.put(lca, map.get(lca) + cost); // } else { // map.put(lca, cost); // } } else { long lca = lca(u, v); // System.out.println("lca (" + u + ", " + v + ") = " + lca); long cost = getCost(u, lca); cost += getCost(v, lca); out.println(cost); } } out.close(); } private long getCost(long v, long lca) { long ret = 0; while(v > lca) { if (map.containsKey(v)) { ret += map.get(v); } // System.out.println(v + " " + ret); v /= 2; } return ret; } private void update(long v, long lca, long cost) { // System.out.println("query = " + v + " " + lca); while(v > lca) { if (map.containsKey(v)) { map.put(v, map.get(v) + cost); } else { map.put(v, cost); } // System.out.println(v + " " + cost); v /= 2; } } private long lca(long v, long u) { if (u == v) return v; if (v > u) return lca(u, v); Set<Long> set = new HashSet<Long>(); while(v > 0) { set.add(v); v /= 2; } while(u > 0) { if (set.contains(u)) { return u; } u /= 2; } throw new RuntimeException("Bad thing happened!"); } public static void main(String args[]) throws Exception { new Main().run(); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
da9ca923883b537db2d7e25aadf89654
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
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.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class A { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int q = nextInt(); Map<Long, Long> map = new TreeMap<Long, Long>(); while (q-->0) { int t = nextInt(); long u = nextLong(); long v = nextLong(); if (t==2) { long ans = 0; long lca = get_lca(u, v); long s = u; while (s != lca) { if (map.containsKey(s)) ans += map.get(s); s >>= 1; } s = v; while (s != lca) { if (map.containsKey(s)) ans += map.get(s); s >>= 1; } pw.println(ans); } else { long w = nextLong(); long lca = get_lca(u, v); long s = u; while (s != lca) { if (!map.containsKey(s)) { map.put(s, w); } else map.put(s, map.get(s) + w); s >>= 1; } s = v; while (s != lca) { if (!map.containsKey(s)) { map.put(s, w); } else map.put(s, map.get(s) + w); s >>= 1; } } } pw.close(); } private static long get_lca(long u, long v) { long lca = 0; Set<Long> set = new TreeSet<>(); long s = u; while (s > 0) { set.add(s); s >>= 1; } s = v; while (s > 0) { if (set.contains(s)) { lca = s; break; } s >>= 1; } return lca; } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
ade0410a9b53a4e6ec608ae923510f20
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Main{ public static void main(String[] args)throws IOException{ Scanner sc=new Scanner(System.in); int q=sc.nextInt(); long ans=0; HashMap<Long,Long> out=new HashMap<Long,Long>(); for(int i=0;i<q;i++) { ans=0; int e=sc.nextInt(); long v=sc.nextLong(); long u=sc.nextLong(); long w=e==1?sc.nextLong():-1; if(e==1) { while(v!=u) { long z=Math.max(v,u); long val=out.containsKey(z)?out.get(z):0; out.put(z,w+val); if(u>v) u/=2; else v/=2; } } else { while(v!=u) { long z=Math.max(v,u); ans+=out.containsKey(z)?out.get(z):0; if(u>v) u/=2; else v/=2; } System.out.println(ans); } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
00f33d226c31738997a483774958ae9b
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class CF696A { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int q = Integer.parseInt(br.readLine()); HashMap<Long, Long> map = new HashMap<>(); PrintWriter pw = new PrintWriter(System.out); while (q-- > 0) { StringTokenizer st = new StringTokenizer(br.readLine()); int t = Integer.parseInt(st.nextToken()); long u = Long.parseLong(st.nextToken()); long v = Long.parseLong(st.nextToken()); if (t == 1) { long w = Long.parseLong(st.nextToken()); while (u != v) if (u < v) { map.put(v, map.getOrDefault(v, 0L) + w); v /= 2; } else { map.put(u, map.getOrDefault(u, 0L) + w); u /= 2; } } else { long w = 0; while (u != v) if (u < v) { w += map.getOrDefault(v, 0L); v /= 2; } else { w += map.getOrDefault(u, 0L); u /= 2; } pw.println(w); } } pw.close(); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
12833bc68dea05ce07d1cefe7a4b4c21
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.util.Scanner; import java.util.TreeMap; public class Main { private static TreeMap<Long, Long> treeMap = new TreeMap<>(); public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int Q = scanner.nextInt(); for (int i = 0; i < Q; i++) { int t = scanner.nextInt(); if (t == 1){ long u = scanner.nextLong(); long v = scanner.nextLong(); long w = scanner.nextLong(); change(u, v, w); } else{ long u = scanner.nextLong(); long v = scanner.nextLong(); System.out.println(change(u, v, 0)); } } } private static long query(long u){ Object obj = treeMap.get(u); if (obj == null) return 0; else return (long)obj; } private static void update(long u, long w){ treeMap.put(u, query(u) + w); } private static long change(long u, long v, long w){ long answer = 0; while (u != v){ if (u > v){ answer += query(u); update(u, w); u /= 2; } else{ answer += query(v); update(v, w); v /= 2; } } return answer; } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
9373e6b87be33af17d493c6f1e511623
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class A { BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; public void solve() throws IOException { int Q = nextInt(); HashMap<Long, Long> cost = new HashMap<Long, Long>(); for (int q = 0; q < Q; q++) { int T = nextInt(); long V = nextLong(); long U = nextLong(); HashSet<Long> paths = new HashSet<Long>(); while (U != V) { if (U > V) { paths.add(U); U /= 2; } else { paths.add(V); V /= 2; } } // for (long v: paths) { // out.print(v + ", "); // } // out.println(); if (T == 1) { long W = nextLong(); for (long v: paths) { if (!cost.containsKey(v)) { cost.put(v, 0L); } cost.put(v, cost.get(v) + W); } } else { long ans = 0; for (long v: paths) { if (cost.containsKey(v)) { ans += cost.get(v); } } out.println(ans); } } } /** * @param args */ public static void main(String[] args) { new A().run(); } public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; out = new PrintWriter(System.out); solve(); reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
fa06fcbaede2249ec1b955edcd8ee38f
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.util.*; public class A696 { TreeMap<Pair, Long> costs = new TreeMap<Pair, Long>(new Comparator<Pair>() { @Override public int compare(Pair s1, Pair s2) { if(s1.second < s2.second) return -1; if(s1.second > s2.second) return 1; return 0; } }); void add(long v, long u, long w) { while(true) { if(v<u) { long tmp = u; u = v; v = tmp; } if(v == 1) break; if(v == u) break; Long cost = costs.get(new Pair(v/2, v)); if(cost == null) cost = 0L; cost += w; //System.out.println(v/2 + " " + v + " " + w); costs.put(new Pair(v/2, v), cost); v/=2; } /*System.out.println("print all"); for(Pair p : costs.keySet()) { System.out.println(p.first + " " + p.second); }*/ } long getCost(long v, long u) { long totalCost = 0; long da = v, a= u; while(true) { if(da<a) { long tmp = da; da = a; a = tmp; } if(da == 1) break; if(da == a) break; //System.out.println(da/2 + " x " + da); Long cost = costs.get(new Pair(da/2, da)); if(cost == null) cost = 0L; totalCost += cost; da /= 2; } return totalCost; } static public void main(String args[]) { Scanner reader = new Scanner(System.in); A696 solver = new A696(); int n = reader.nextInt(); for(int i=0;i<n;i++) { int op; long v, u, w; op = reader.nextInt(); v = reader.nextLong(); u = reader.nextLong(); if(op == 1) { w = reader.nextLong(); solver.add(u, v, w); } else { System.out.println(solver.getCost(u, v)); } } } } class Pair { long first; long second; public Pair(long f, long s) { first = f; second = s; } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
8d61d862065ad3c5fb523a178a68a401
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class R362qA { static HashMap<Long, Long> map = new HashMap<Long, Long>(); public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int q = in.nextInt(); while (q-- > 0) { int t = in.nextInt(); if (t == 1) { long u = in.nextLong(); long v = in.nextLong(); int c = in.nextInt(); int ud = Long.toBinaryString(u).length(); int vd = Long.toBinaryString(v).length(); while (ud > vd) { ud--; add(u, c); u >>= 1; } while (vd > ud) { vd--; add(v, c); v >>= 1; } while (u != v) { add(u, c); add(v, c); u >>= 1; v >>= 1; } } else { long u = in.nextLong(); long v = in.nextLong(); int ud = Long.toBinaryString(u).length(); int vd = Long.toBinaryString(v).length(); long ans = 0; while (ud > vd) { ud--; ans += map.containsKey(u) ? map.get(u) : 0; u >>= 1; } while (vd > ud) { vd--; ans += map.containsKey(v) ? map.get(v) : 0; v >>= 1; } while (u != v) { ans += map.containsKey(u) ? map.get(u) : 0; ans += map.containsKey(v) ? map.get(v) : 0; u >>= 1; v >>= 1; } w.println(ans); } } w.close(); } static void add(long a, long b) { if (!map.containsKey(a)) map.put(a, 0L); map.put(a, map.get(a) + b); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } 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); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
a3f578184c4ed8267f58a9ea1f5d9493
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.util.*; public class Solution696A { HashMap<Long, Long> m = new HashMap<>(); public static void main(String[] args) { Solution696A ss = new Solution696A(); ss.run(); } void run() { Scanner sc = new Scanner(System.in); int q = sc.nextInt(); int query; for (int i = 0; i < q; i++) { query = sc.nextInt(); if (query == 1) do1(sc); else System.out.println(do2(sc)); } } void do1(Scanner sc) { long v = sc.nextLong(), u = sc.nextLong(), w = sc.nextLong(); int hv = height(v), hu = height(u); if (hv < hu) { long temp = v; v = u; u = temp; temp = hv; hv = hu; hu = (int)temp; } while (hv > hu) { if (m.containsKey(v)) m.put(v, m.get(v) + w); else m.put(v, w); v = v/2; hv--; } while (v != u) { if (m.containsKey(v)) m.put(v, m.get(v) + w); else m.put(v, w); if (m.containsKey(u)) m.put(u, m.get(u) + w); else m.put(u, w); v = v/2; u = u/2; } } long do2(Scanner sc) { long price = 0; long v = sc.nextLong(), u = sc.nextLong(); int hv = height(v), hu = height(u); if (hv < hu) { long temp = v; v = u; u = temp; temp = hv; hv = hu; hu = (int)temp; } while (hv > hu) { if (m.containsKey(v)) price += m.get(v); v = v/2; hv--; } while (v != u) { if (m.containsKey(v)) price += m.get(v); if (m.containsKey(u)) price += m.get(u); v = v/2; u = u/2; } return price; } int height(long n) { if (n == 1) return 0; return 1 + height(n/2); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
21284cdb873cddcc7f0a480b3b037300
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class Main { String getStr(long u) { StringBuilder sb = new StringBuilder(); while (u > 0) { sb.append(u % 2); u >>= 1; } return sb.reverse().toString(); } long getLong(String s) { long result = 0; for (int i = 0 ; i < s.length() ; i++) { int bit = s.charAt(i) - '0'; if (bit > 0) { result += 1L << (s.length() - i - 1); } } return result; } long _getLCA(long u, long v) { String us = getStr(u), vs = getStr(v); int pos = Math.min(us.length(), vs.length()); //System.err.println(us + " " + vs); for (int i = 0 ; i < Math.min(us.length(), vs.length()) ; i++) { if (us.charAt(i) != vs.charAt(i)) { pos = i; break; } } String pref = us.substring(0, pos); long res = getLong(pref); //System.err.println("res = " + res); return res; } int leftmostBit(long u) { int res = 0; while ((1L << res) <= u) res ++; return res - 1; } int getBit(long x, int pos) { return (int)((x >> pos) & 1); } long getLCA(long u, long v) { int lu = leftmostBit(u), lv = leftmostBit(v); //System.err.println(u + " -> " + lu + " - " + v + " " + lv); long res = 0; while(lu >= 0 && lv >= 0) { int ub = getBit(u, lu); int vb = getBit(v, lv); if (ub != vb) { break; } res = (res << 1) + ub; lu --; lv --; } return res; } static class Inc { long a, p, val; Inc(long a, long p, long val) { this.a = a; this.p = p; this.val = val; } } public void processInc(long u, long v, long val, ArrayList<Inc> all) { long x = getLCA(u, v); if (u != x) { all.add(new Inc(x, u, val)); } if (v != x) { all.add(new Inc(x, v, val)); } } public long processCuddle(long u, long v, ArrayList<Inc> all) { long a = getLCA(u, v); return processOne(a, u, all) + processOne(a, v, all); } public long processOne(long a, long p, ArrayList<Inc> all) { //System.err.println("processing one: " + a + " " + p ); if (a == p) { return 0; } long result = 0; for (Inc inc : all) { result += inc.val * processPair(a, p, inc.a, inc.p); } //System.err.println("result = " + result ); return result; } public long processPair(long a1, long p1, long a2, long p2) { //System.err.println(a1 + ", " + p1 + " " + a2 + ", " + p2); long la = getLCA(a1, a2); //System.err.println("la = " + la); if (la != a1 && la != a2) { return 0; } long u = la == a1 ? a2 : a1; long v = getLCA(p2, p1); //System.err.println("u, v = " + u + ", " + v); if (getLCA(u, v) != u) return 0; //System.err.println("pair: " + u + " " + v); long res = 0; while (v != u) { v >>= 1; res ++; } return res; } public void solve() throws IOException { int n = nextInt(); ArrayList<Inc> inc = new ArrayList<Inc>(); for (int i = 0 ; i < n ; i ++) { int op = nextInt(); if (op == 1) { long u = nextLong(), v = nextLong(), val = nextLong(); processInc(u, v, val, inc); } else { long u = nextLong(), v = nextLong(); out.println(processCuddle(u, v, inc)); } } } BufferedReader bf; StringTokenizer st; PrintWriter out; public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public Main() throws IOException { bf = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); bf.close(); out.close(); } public static void main(String args[]) throws IOException { new Main(); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
1dc06d383334b039db3f6f58e700cadf
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class Main { InputReader scn; PrintWriter out; String INPUT = ""; HashMap<String, Long> path = new HashMap<>(); void solve() { int q = scn.nextInt(); while (q-- > 0) { int t = scn.nextInt(); long u = scn.nextLong(), v = scn.nextLong(), w = 0; if (t == 1) { w = scn.nextLong(); } long rv = check(u, v, w); if (t == 2) { out.println(rv); } } } long check(long u, long v, long w) { long p = u, q = v, par = 0; int lv1 = Long.toBinaryString(u).length(), lv2 = Long.toBinaryString(v).length(); while (lv1 != lv2) { if (lv1 < lv2) { q /= 2; lv2--; } else { p /= 2; lv1--; } } while (p != q) { p /= 2; q /= 2; } par = p; long rv = 0; while (u != par) { String str = u / 2 + " " + u; u /= 2; if(path.containsKey(str)) { path.put(str, path.get(str) + w); } else { path.put(str, w); } rv += path.get(str); } while (v != par) { String str = v / 2 + " " + v; v /= 2; if(path.containsKey(str)) { path.put(str, path.get(str) + w); } else { path.put(str, w); } rv += path.get(str); } return rv; } void run() throws Exception { boolean onlineJudge = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new InputReader(onlineJudge); long time = System.currentTimeMillis(); solve(); out.flush(); if (!onlineJudge) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) throws Exception { new Main().run(); } class InputReader { InputStream is; public InputReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextArray(int n, boolean isOneInd) { int k = isOneInd ? 1 : 0; int[] a = new int[n + k]; for (int i = k; i < n + k; i++) a[i] = nextInt(); return a; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
bbbeb9299514371ce572399f161882d3
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.StringTokenizer; public class A { static Map<Long, Map<Long, Long>> adj; public static void main(String[] args) { // Scanner sc = new Scanner(System.in); FastScanner sc = new FastScanner(); int q = sc.nextInt(); adj = new HashMap<>(); for (int i = 0; i < q; i++) { int type = sc.nextInt(); long v = sc.nextLong(); long u = sc.nextLong(); long w; if (type == 1) { w = sc.nextLong(); } else { w = 0; } if (v > u) { long tmp = v; v = u; u = tmp; } // v <= u // Get them on the same level long cost = 0; while (Long.highestOneBit(u) > Long.highestOneBit(v)) { cost += link(u, u / 2, w); u /= 2; } while (u != v) { cost += link(u, u / 2, w); u /= 2; cost += link(v, v / 2, w); v /= 2; } if (type == 2) { System.out.println(cost); } } } static void addNode(long node) { if (!adj.containsKey(node)) { adj.put(node, new HashMap<>()); } } static long link(long child, long parent, long w) { addNode(child); addNode(parent); Long curCost = adj.get(child).get(parent); if (curCost == null) { adj.get(child).put(parent, w); } else { adj.get(child).put(parent, curCost + w); } return adj.get(child).get(parent); } static void shuffle(int[] arr) { Random rng = new Random(); int length = arr.length; for (int idx = 0; idx < arr.length; idx++) { int toSwap = idx + rng.nextInt(length - idx); int tmp = arr[idx]; arr[idx] = arr[toSwap]; arr[toSwap] = tmp; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(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 readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
23952d961c297138fa32c97f731080c6
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.TreeMap; import java.util.StringTokenizer; import java.util.Map; import java.io.BufferedReader; 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 q = in.nextInt(); TreeMap<Long, Long> cost = new TreeMap<>(); for (int i = 0; i < q; i++) { int type = in.nextInt(); if (type == 1) { long v = in.nextLong(); long u = in.nextLong(); long w = in.nextLong(); ArrayList<Long> path = shortPath(v, u); for (int j = 1; j < path.size(); j++) { long edge = getEdge(path.get(j - 1), path.get(j)); cost.put(edge, cost.getOrDefault(edge, 0L) + w); } } else { long v = in.nextLong(); long u = in.nextLong(); ArrayList<Long> path = shortPath(v, u); long ans = 0; for (int j = 1; j < path.size(); j++) { long edge = getEdge(path.get(j - 1), path.get(j)); ans += cost.getOrDefault(edge, 0L); } out.println(ans); } } } ArrayList<Long> shortPath(long u, long v) { ArrayList<Long> first = new ArrayList<>(); ArrayList<Long> second = new ArrayList<>(); while (u > 0) { first.add(u); u /= 2; } while (v > 0) { second.add(v); v /= 2; } first.sort(Long::compareTo); second.sort(Long::compareTo); int lastCommon = 0; for (int i = 0; i < first.size() && i < second.size(); i++) { if (first.get(i).equals(second.get(i))) lastCommon = i; else break; } ArrayList<Long> res = new ArrayList<>(); for (int i = first.size() - 1; i > lastCommon; i--) { res.add(first.get(i)); } for (int i = lastCommon; i < second.size(); i++) { res.add(second.get(i)); } return res; } Long getEdge(Long node1, Long node2) { return Math.max(node1, node2); } } static class InputReader { private StringTokenizer tokenizer; private BufferedReader reader; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private void fillTokenizer() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } } public String next() { fillTokenizer(); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
5c5eda1098ed4dd0f3a527978d269bfa
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class Main { private boolean eof; private BufferedReader br; private StringTokenizer st; private PrintWriter out; public static void main(String[] args) throws IOException { new Main().run(); } private String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "-1"; } } return st.nextToken(); } private int nextInt() { return Integer.parseInt(nextToken()); } private long nextLong() { return Long.parseLong(nextToken()); } private double nextDouble() { return Double.parseDouble(nextToken()); } private String nextLine() throws IOException { return br.readLine(); } private void run() throws IOException { InputStream input = System.in; PrintStream output = System.out; try { File f = new File("a.in"); if (f.exists() && f.canRead()) { input = new FileInputStream(f); output = new PrintStream("a.out"); } } catch (Throwable ignored) { } br = new BufferedReader(new InputStreamReader(input)); out = new PrintWriter(new PrintWriter(output)); solve(); br.close(); out.close(); } Map<Pair<Long, Long>, Long> costs = new HashMap<>(); private void addCost(long x, long y, long newCost) { Set<Long> xToRoot = new HashSet<>(); long common = getCommon(x, y); while (x > common) { Pair<Long, Long> p = new Pair<>(x, x / 2); if (costs.containsKey(p)) { costs.put(p, costs.get(p) + newCost); } else { costs.put(p, newCost); } x /= 2; } while (y > common) { Pair<Long, Long> p = new Pair<>(y, y / 2); if (costs.containsKey(p)) { costs.put(p, costs.get(p) + newCost); } else { costs.put(p, newCost); } y /= 2; } } private long getCommon(long x, long y) { Set<Long> xToRoot = new HashSet<>(); while (x > 0) { xToRoot.add(x); x /= 2; } while (y > 0) { if (xToRoot.contains(y)) { return y; } y /= 2; } return 1; } private long getCost(long x, long y) { long ans = 0; long common = getCommon(x, y); while (x > common) { Pair<Long, Long> p = new Pair<>(x, x / 2); if (costs.containsKey(p)) { ans += costs.get(p); } x /= 2; } while (y > common) { Pair<Long, Long> p = new Pair<>(y, y / 2); if (costs.containsKey(p)) { ans += costs.get(p); } y /= 2; } return ans; } private void solve() { int q = nextInt(); for (int i = 0; i < q; i++) { int cmd = nextInt(); if (cmd == 1) { long x = nextLong(); long y = nextLong(); long cost = nextLong(); addCost(x, y, cost); } else { long x = nextLong(); long y = nextLong(); out.println(getCost(x, y)); } } } //Дерево поиска по ключу, балансится за счет случайных приоритетов //Поддерживает сумму(мин,макс) элементов в поддереве и нахождение суммы(мин,макс)на заданном отрезке. // public static class Node { public long key; public int prior; public long sum; public long min; public long max; public int cnt; public Node left, right; Node(long key, int prior) { this.key = key; this.prior = prior; left = right = null; this.sum = key; this.min = key; this.max = key; this.cnt = 1; } } public static long getMin(Node t) { return t == null ? Integer.MAX_VALUE : t.min; } public static long getMax(Node t) { return t == null ? Integer.MIN_VALUE : t.max; } public static long getSum(Node t) { return t == null ? 0 : t.sum; } public static int getCnt(Node t) { return t == null ? 0 : t.cnt; } public static void update(Node t) { if (t != null) { t.sum = t.key + getSum(t.left) + getSum(t.right); t.min = Math.min(t.key, getMin(t.left)); t.max = Math.max(t.key, getMax(t.right)); t.cnt = 1 + getCnt(t.left) + getCnt(t.right); } } public static Pair<Node, Node> split(Node t, long key) { if (t == null) return new Pair<>(null, null); if (key > t.key) { Pair<Node, Node> p = split(t.right, key); t.right = p.first; update(t); return new Pair<>(t, p.second); } else { Pair<Node, Node> p = split(t.left, key); t.left = p.second; update(t); return new Pair<>(p.first, t); } } //SPLIT ПО НЕЯВНОМУ КЛЮЧУ //add for root = 0 public static Pair<Node, Node> split(Node t, long key, int add) { if (t == null) return new Pair<>(null, null); int curKey = add + getCnt(t.left); if (key > curKey) { //идем в правое поддерево Pair<Node, Node> p = split(t.right, key, curKey + 1); t.right = p.first; update(t); return new Pair<>(t, p.second); } else { //идем в левое поддерево Pair<Node, Node> p = split(t.left, key, add); t.left = p.second; update(t); return new Pair<>(p.first, t); } } public static Node merge(Node t1, Node t2) { if (t1 == null) return t2; if (t2 == null) return t1; if (t1.prior > t2.prior) { t1.right = merge(t1.right, t2); update(t1); return t1; } else { t2.left = merge(t1, t2.left); update(t2); return t2; } } // public static Node insert(Node t, Node newNode) { // if (t == null) { // t = newNode; // } else if (newNode.prior > t.prior) { // Pair<Node, Node> p = split(t, newNode.key); // newNode.left = p.first; // newNode.right = p.second; // t = newNode; // } else { // if (newNode.key < t.key) { // t.left = insert(t.left, newNode); // } else { // t.right = insert(t.right, newNode); // } // } // update(t); // return t; // } //Еще один insert, но вроде не такой быстрый public static Node insert(Node t, Node newNode) { if (t == null) { t = newNode; } else { Pair<Node, Node> p = split(t, newNode.key); t = merge(p.first, newNode); t = merge(t, p.second); } update(t); return t; } public static Node remove(Node t, long key) { if (t == null) return null; if (t.key == key) { t = merge(t.left, t.right); } else { if (key < t.key) { t.left = remove(t.left, key); } else { t.right = remove(t.right, key); } } update(t); return t; } public static Node find(Node t, long key) { if (t == null) return null; if (t.key == key) return t; if (t.key < key) { return find(t.right, key); } else { return find(t.left, key); } } /** * Вырезает отрезок от i до j и вставляет в позицию k нового массива * (при k = 0 вставляет вначало) * @param t Корень дерева * @param i Начало отрезка (включительно) * @param j Конец отрезка (включительно) * @param k Позиция вставки * @return Новое дерево */ public static Node replaceSegment(Node t, int i, int j, int k) { //Вырезаем отрезок и склеиваем Pair<Node, Node> split1 = split(t, i, 0); Pair<Node, Node> split2 = split(split1.second, j - i + 1, 0); Node merge1 = merge(split1.first, split2.second); Node removedSegment = split2.first; // out.println("Array without removed:" + getString(merge1)); // out.println("Removed Segment:" + getString(removedSegment)); //разделяем и вставляем Pair<Node, Node> split3 = split(merge1, k, 0); Node merge2 = merge(split3.first, removedSegment); Node merge3 = merge(merge2, split3.second); return merge3; } public static long getSum(Node t, long l, long r) { Pair<Node, Node> p1 = split(t, l); Pair<Node, Node> p2 = split(p1.second, r + 1); long ans = p2.first == null ? 0 : p2.first.sum; t = merge(p1.first, p2.first); t = merge(t, p2.second); return ans; } public static StringBuilder getKeysString(Node t) { if (t == null) return new StringBuilder(); StringBuilder ans = new StringBuilder(); if (t.left != null) ans.append(getKeysString(t.left)); ans.append(t.key); ans.append(" "); if (t.right != null) ans.append(getKeysString(t.right)); return ans; } public static class Pair<F, S> { public F first; public S second; Pair(F first, S second) { this.first = first; this.second = second; } // @Override // public int compareTo(Object o) { // return first.compareTo(((Pair)o).first); // } @Override public boolean equals(Object o) { if (!(o instanceof Main.Pair)) { return false; } Main.Pair<?, ?> p = (Main.Pair<?, ?>) o; return Objects.equals(p.first, first) && Objects.equals(p.second, second); } @Override public int hashCode() { return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
06c83931854db1ab1ae423810a948566
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class ProblemA { static HashMap<Edge, Long> map; static boolean DEBUG = false; public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); map = new HashMap<Edge, Long>(); int query = input.nextInt(); for (int a = 0; a < query; a++) { int first = input.nextInt(); if (first == 1) { // new rule long start = input.nextLong(); long end = input.nextLong(); long cost = input.nextLong(); ArrayList<Long> path = path(start, end); for (int b = 0; b < path.size() - 1; b++) { Edge tmp = new Edge(path.get(b), path.get(b + 1)); if (map.containsKey(tmp)) { map.put(tmp, map.get(tmp) + cost); } else { map.put(tmp, cost); } } if (DEBUG) { System.out.println("DEBUG FOR QUERY TYPE ADD"); System.out.println(path); System.out.println(map + " " + start + " " + end + " " + cost); } } else { // calculate cost long start = input.nextLong(); long end = input.nextLong(); ArrayList<Long> path = path(start, end); long cost = 0; for (int b = 0; b < path.size() - 1; b++) { Edge tmp = new Edge(path.get(b), path.get(b + 1)); if (map.containsKey(tmp)) { cost += map.get(tmp); } } if (DEBUG) { System.out.println(path + " " + start + " " + end); } System.out.println(cost); } } } public static ArrayList<Long> path(long start, long end) { ArrayList<Long> path = new ArrayList<Long>(); ArrayList<Long> path2 = new ArrayList<Long>(); long startTemp = start; long endTemp = end; while (startTemp != 0) { path.add(startTemp); startTemp /= 2; } while (endTemp != 0) { path2.add(endTemp); endTemp /= 2; } long tmp = -1; while (true) { if (path.size() == 0 || path2.size() == 0) { break; } if (path.get(path.size() - 1).equals(path2.get(path2.size() - 1)) == false) { break; } tmp = path.get(path.size() - 1); path.remove(path.size() - 1); path2.remove(path2.size() - 1); } path.add(tmp); for (int a = path2.size() - 1; a >= 0; a--) { path.add(path2.get(a)); } return path; } public static class Edge implements Comparable<Edge> { long start; long end; public Edge(long _start, long _end) { start = Math.min(_start, _end); end = Math.max(_start, _end); } @Override public int hashCode() { return (int) (start * 37 + end + start / 5000001); } @Override public boolean equals(Object o) { Edge e = (Edge) o; return start == e.start && end == e.end; } @Override public int compareTo(Edge arg0) { return (start == arg0.start) ? (int) (end - arg0.end) : (int) (start - arg0.start); } public String toString() { return "(" + start + " " + end + ")"; } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
95734f5646e4927d16afcb10fe09d89e
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
//Date:14-07-16 import java.util.*; public class Nyc{ /*static void swap(Long a,Long b){ Long temp = a; a = b; b = temp; }*/ public static void main(String args[]){ Scanner sc = new Scanner(System.in); HashMap<Long ,Long> map = new HashMap<Long ,Long>(); int q = sc.nextInt(); while(q-->0){ int opt = sc.nextInt(); long u = sc.nextLong(); long v = sc.nextLong(); if(opt==1){ long w = sc.nextLong(); while(u!=v){ if(v>u) { long temp = u; u =v; v =temp; } if(map.containsKey(u)) map.put(u ,map.get(u)+w); else map.put(u ,w); u/=2; } }else{ long tcost =0; while(u!=v){ if(v>u) { long temp = u; u =v; v = temp; } if(map.containsKey(u)) tcost+=map.get(u); u/=2; } System.out.println(tcost); } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
ed81e3c03ac81e3c6ec72582b6265a3e
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
// package Tree_Practice; /** * Created by ankurverma1994 * My code is awesome! */ import java.io.*; import java.util.*; import java.math.*; public class R362DIVqALorenzoVonMatterhorn { HashMap<String, Long> edgeWt = new HashMap<>(); //------------> Solution starts here!! @SuppressWarnings("Main Logic") void solve() { for (int tc = ii(); tc > 0; tc--) { int type = ii(); if (type == 1) { add(); } else { query(); } } } void query() { long u = il(), v = il(); long ans = 0; while (u != v) { if (u > v) { long x = u / 2; String a = x + " " + u; if (edgeWt.containsKey(a)) ans += edgeWt.get(a); u = x; } else { long x = v / 2; String a = x + " " + v; if (edgeWt.containsKey(a)) ans += edgeWt.get(a); v = x; } } out.println(ans); } void add() { long u = il(), v = il(), w = il(); while (u != v) { if (u > v) { long x = u / 2; String a = u + " " + x; String b = x + " " + u; long val = 0; if (edgeWt.containsKey(a)) { val = edgeWt.get(a); } edgeWt.put(a, val + w); edgeWt.put(b, val + w); u = x; } else { long x = v / 2; String a = v + " " + x; String b = x + " " + v; long val = 0; if (edgeWt.containsKey(a)) { val = edgeWt.get(a); } edgeWt.put(a, val + w); edgeWt.put(b, val + w); v = x; } } } //------------> Solution ends here!! InputStream obj; PrintWriter out; String check = ""; public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { new R362DIVqALorenzoVonMatterhorn().main1(); } catch (IOException e) { e.printStackTrace(); } catch (StackOverflowError e) { System.out.println("RTE"); } } }, "1", 1 << 26).start(); } void main1() throws IOException { out = new PrintWriter(System.out); obj = check.isEmpty() ? System.in : new ByteArrayInputStream(check.getBytes()); // obj=check.isEmpty() ? new FileInputStream("/home/ankurverma1994/input.txt") : new ByteArrayInputStream(check.getBytes()); solve(); out.flush(); out.close(); } byte inbuffer[] = new byte[1024]; int lenbuffer = 0, ptrbuffer = 0; int readByte() { if (lenbuffer == -1) throw new InputMismatchException(); if (ptrbuffer >= lenbuffer) { ptrbuffer = 0; try { lenbuffer = obj.read(inbuffer); } catch (IOException e) { throw new InputMismatchException(); } } if (lenbuffer <= 0) return -1; return inbuffer[ptrbuffer++]; } String is() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) // when nextLine, (isSpaceChar(b) && b!=' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ii() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long il() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } float nf() { return Float.parseFloat(is()); } double id() { return Double.parseDouble(is()); } char ic() { return (char) skip(); } int[] iia(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = ii(); return a; } long[] ila(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = il(); return a; } String[] isa(int n) { String a[] = new String[n]; for (int i = 0; i < n; i++) a[i] = is(); return a; } double[][] idm(int n, int m) { double a[][] = new double[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = id(); return a; } int[][] iim(int n, int m) { int a[][] = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = ii(); return a; } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
4aedd61cfc624d7605d53f75b35476cb
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; public class Codeforces696a { static int q; static Map<Long, Long> map = new HashMap<>(); public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); q = scanner.nextInt(); for (int i = 0; i < q; i++) { int testCase = scanner.nextInt(); long a = scanner.nextLong(); long b = scanner.nextLong(); long price; if (testCase == 1) { price = scanner.nextLong(); long parent; if (a > b) { parent = lca(a, b); } else { parent = lca(b, a); } traverse(a, parent, price); traverse(b, parent, price); } else { long parent; long totalPrice = 0; if (a > b) { parent = lca(a, b); } else { parent = lca(b, a); } totalPrice += findPrice(a, parent); totalPrice += findPrice(b, parent); System.out.println(totalPrice); } } // map.forEach((x, y) -> System.out.print(x + " : " + y + ", ")); } static long lca(long a, long b) { long parent = 1; Set<Long> parents = new HashSet<>(); while (a != 0) { // System.out.println(a); a = a / 2; parents.add(a); } while (b != 0) { if (parents.contains(b)) { parent = b; break; } b = b / 2; } return parent; } static void traverse(long from, long to, long price) { while (from != to) { Long cost = map.get(from); if (cost != null) { map.put(from, price + cost); } else { map.put(from, price); } from = from / 2; } } static long findPrice(long from, long to) { long price = 0; while (from != to) { Long cost = map.get(from); if (cost != null) { price += map.get(from); } from = from / 2; } return price; } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
12343dfa600ebd21a7d084631dd92984
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class CFC362CGraph { public static void main(String[] args) { Scanner sc = new Scanner(System.in); HashMap<Long, Long> map = new HashMap<Long,Long>(); int events = sc.nextInt(); for (int i = 0; i < events; i++) { int type = sc.nextInt(); long localcost = 0; if (type == 1) { // gov long a = sc.nextLong(); long b = sc.nextLong(); long cost = sc.nextLong(); while (a != b) { if (b > a) { long temp = a; a = b; b = temp; } if (map.containsKey(a)) { map.put(a, cost+map.get(a)); }else { map.put(a, cost); } a /= 2; } }else { long a = sc.nextLong(); long b = sc.nextLong(); while (a != b) { if (b > a) { long temp = a; a = b; b = temp; } if (map.containsKey(a)) { localcost += map.get(a); } a/=2; } System.out.println(localcost); } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
22f88c20f5f57d0a9be793e6a2878f45
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } String readString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine(), " :"); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() { return Integer.parseInt(readString()); } int[] readIntArray(int size) { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long readLong() { return Long.parseLong(readString()); } double readDouble() { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } class Point implements Comparable<Point> { long f; long t; public Point(long f, long t) { if (f < t) { long te = f; f = t; t = te; } this.f = f; this.t = t; } @Override public int compareTo(Point o) { if (f != o.f) return Long.compare(f, o.f); return Long.compare(t, o.t); } } TreeMap<Point, Long> cost = new TreeMap<>(); void add(Point pt, int add) { cost.put(pt, get(pt) + add); } long get(Point pt) { Long val = cost.get(pt); return val == null ? 0 : val; } ArrayList<Point> path(long x, long y) { ArrayList<Point> pts = new ArrayList<>(); while (x != y) { if (x < y) { long t = x; x = y; y = t; } pts.add(new Point(x, x / 2)); x = x / 2; } return pts; } TreeSet<Point> uniq(List<Point> pts) { TreeSet<Point> res = new TreeSet<>(); for (Point pt : pts) res.add(pt); return res; } void solve() throws IOException { int n = readInt(); for (int i = 0; i < n; i++) { int type = readInt(); long u = readLong(); long v = readLong(); if (type == 1) { int w = readInt(); Set<Point> pts = uniq(path(u, v)); for (Point pt : pts) add(pt, w); } else { ArrayList<Point> list = path(u, v); long ans = 0; for (Point pt : list) ans += get(pt); out.println(ans); } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
2983baed8ba14db1df8a7feacfc5ff19
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class Main { public static void main (String[] args) { Scanner s = new Scanner(System.in); long q = s.nextInt(); IntersectionTree is = new IntersectionTree(); for (int e = 0; e < q; e++) { int t = s.nextInt(); if (t == 1) { long v = s.nextLong(); long u = s.nextLong(); long w = s.nextLong(); is.incrementPath(v, u, w); } else { long v = s.nextLong(); long u = s.nextLong(); System.out.println(is.getCost(v, u)); } } } public static class IntersectionTree { private HashMap<Long, Long> edgeWeights; public IntersectionTree () { this.edgeWeights = new HashMap<>(); } public void incrementPath(long i, long j, long amount) { long min = Math.min(i, j); long max = Math.max(i, j); long minLevel = getLevel(min); long maxLevel = getLevel(max); while (maxLevel > minLevel) { max = incAndJumpUp(max, amount); maxLevel--; } while (min != max) { max = incAndJumpUp(max, amount); min = incAndJumpUp(min, amount); } } public long getCost(long i, long j) { long min = Math.min(i, j); long max = Math.max(i, j); long minLevel = getLevel(min); long maxLevel = getLevel(max); long cost = 0; while (maxLevel > minLevel) { cost += getWeight(max); max = jumpUp(max); maxLevel--; } while (min != max) { cost += getWeight(max); max = jumpUp(max); cost += getWeight(min); min = jumpUp(min); } return cost; } private long incAndJumpUp(long i, long amount) { incWeight(i, amount); return jumpUp(i); } private long jumpUp(long i) { return i / 2; } private long getWeight(long node) { if (edgeWeights.containsKey(node)) { return edgeWeights.get(node); } return 0; } private long getLevel (long i) { long level = 0; while (i > 1) { i = i / 2; level++; } return level; } private void incWeight(long node, long amount) { if (edgeWeights.containsKey(node)) { edgeWeights.put(node, edgeWeights.get(node) + amount); } else { edgeWeights.put(node, amount); } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
c324c8b7a9202a9e7a9e5941df179f22
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.beans.IntrospectionException; import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.lang.*; import static java.lang.Math.*; public class main implements Runnable { static ArrayList<Integer> adj[]; static void Check2(int n) { adj = new ArrayList[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } } static void add(int i, int j) { adj[i].add(j); adj[j].add(i); } public static void main(String[] args) { new Thread(null, new main(), "Check2", 1 << 28).start();// to increse stack size in java } static long mod = (long) (1e9 + 7); public void run() { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int q=in.nextInt(); HashMap <String,Long> map=new HashMap<>(); while (q-->0) { int type=in.nextInt(); if(type==1) { long u=in.nextLong(); long v=in.nextLong(); long dist=in.nextLong(); long ansc=find(u,v); long cur = u / 2l; long prv=u; while (prv!= ansc) { if (!map.containsKey(prv+" "+cur)) { map.put(prv + " " + cur, dist); map.put(cur + " " + prv, dist); } else { map.put(prv + " " + cur, map.get(prv + " " + cur) + dist); map.put(cur + " " + prv, map.get(cur + " " + prv) + dist); } cur /= 2l; prv/=2l; } cur=v/2l; prv=v; while (prv!= ansc) { if (!map.containsKey(prv+" "+cur)) { map.put(prv + " " + cur, dist); map.put(cur + " " + prv, dist); } else { map.put(prv + " " + cur, map.get(prv + " " + cur) + dist); map.put(cur + " " + prv, map.get(cur + " " + prv) + dist); } cur /= 2l; prv/=2l; } } else{ long u=in.nextLong(); long v=in.nextLong(); long ansc=find(u,v); long ans=0; long cur = u / 2l; long prv=u; while (prv!= ansc) { if (!map.containsKey(prv+" "+cur)) { } else { ans+= map.get(prv + " " + cur); } cur /= 2l; prv/=2l; } cur=v/2l; prv=v; while (prv!= ansc) { if (!map.containsKey(prv+" "+cur)) { } else { ans+= map.get(prv + " " + cur); } cur /= 2l; prv/=2l; } w.println(ans); } } w.close(); } static long find(long u,long v){ ArrayList <Long> list1=new ArrayList<>(); ArrayList <Long> list2=new ArrayList<>(); long cur=u; while (cur!=1) { list1.add(cur); cur/=2l; } cur=v; while (cur!=1) { list2.add(cur); cur/=2l; } list1.add(1l); list2.add(1l); long ansc=1l; out:for(int i=0;i<list1.size();i++) { long val=list1.get(i); for(int j=0;j<list2.size();j++) { if(val==list2.get(j)){ ansc=val; break out; } } } return ansc; } static class pair2{ int a, b; pair2(int a,int b){ this.a=a; this.b=b; } } static class cmp2 implements Comparator <pair2>{ public int compare(pair2 o1,pair2 o2){ return o1.b-o2.b; } } static void diji(int s,long dist[],ArrayList <pair> adj[]){ dist[s]=0; PriorityQueue <pair> q=new PriorityQueue<>(new cmp()); q.add(new pair(s,0)); while (!q.isEmpty()) { pair p1=q.poll(); for(pair ne:adj[p1.a]){ if((long)p1.b+(long)ne.b<dist[ne.a]){ dist[ne.a]=(long)p1.b+(long)ne.b; pair p2=new pair(ne.a,dist[ne.a]); q.add(p2); } } } } static class cmp implements Comparator<pair>{ public int compare(pair o1,pair o2) { return o1.b<o2.b?-1:o1.b>o2.b?1:0; } } static class pair { int a; long b; pair(int a,long b){ this.a=a; this.b=b; } public boolean equals(Object obj) { // override equals method for object to remove tem from arraylist and sets etc....... if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; pair other = (pair) obj; if (b!= other.b||a!=other.a) return false; return true; } } static long modinv(long a,long b) { long p=power(b,mod-2); p=a%mod*p%mod; p%=mod; return p; } static long power(long x,long y){ if(y==0)return 1%mod; if(y==1)return x%mod; long res=1; x=x%mod; while(y>0){ if((y%2)!=0){ res=(res*x)%mod; } y=y/2; x=(x*x)%mod; } return res; } static int gcd(int a,int b){ if(b==0)return a; return gcd(b,a%b); } static void sev(int a[],int n){ for(int i=2;i<=n;i++)a[i]=i; for(int i=2;i<=n;i++){ if(a[i]!=0){ for(int j=2*i;j<=n;){ a[j]=0; j=j+i; } } } } static class node{ int y; int val; node(int a,int b){ y=a; val=b; } } 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 String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 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); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
c0ab9b725ac8b1d31048c4b373c79101
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.util.*; import java.awt.geom.*; import java.io.*; import java.math.*; public class Main { static HashMap<String,Long> weights=new HashMap<String,Long>(); public static void main(String[] args) throws Exception { long startTime = System.nanoTime(); int q=in.nextInt(); while(q-- > 0) { int type=in.nextInt(); long u=0; long v=0; long w=0; u=in.nextLong();v=in.nextLong(); ArrayList<Long> first=new ArrayList<Long>(); ArrayList<Long> second=new ArrayList<Long>(); while(u>=1) { first.add(u); u/=2; } while(v>=1) { second.add(v); v/=2; } Collections.sort(second); Collections.sort(first); int a=0; int b=0; for(int i=first.size()-1;i>=0;i--) { int temp=Collections.binarySearch(second,first.get(i)); if(temp>=0) { a=i; b=temp; break; } } for(int i=0;i<a;i++) first.remove(0); for(int i=0;i<b;i++) second.remove(0); if(type==1) { w=in.nextLong(); for(int i=0;i<first.size()-1;i++) { update(first.get(i),first.get(i+1),w); } for(int i=0;i<second.size()-1;i++) { update(second.get(i),second.get(i+1),w); } continue; } long ans=0; for(int i=0;i<first.size()-1;i++) { ans+=get(first.get(i),first.get(i+1)); } for(int i=0;i<second.size()-1;i++) { ans+=get(second.get(i),second.get(i+1)); } out.println(ans); } long endTime = System.nanoTime(); err.println("Execution Time : +" + (endTime-startTime)/1000000 + " ms"); exit(0); } static void update(long a,long b,long w) { Long t1=weights.get(a + ":" + b); Long t2=weights.get(b + ":" + a); if(t1 == null && t2 == null) { weights.put(a + ":" + b , w); } else if(t1==null) { weights.put(a + ":" + b , t2+w); } else if(t2==null) { weights.put(a + ":" + b , t1+w); } } static long get(long a,long b) { Long t1=weights.get(a + ":" + b); Long t2=weights.get(b + ":" + a); if(t1 == null && t2 == null) { return 0; } else if(t1==null) { return t2; } else if(t2==null) { return t1; } return 0; } 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 long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } static void exit(int a) { out.close(); err.close(); System.exit(a); } static InputStream inputStream = System.in; static OutputStream outputStream = System.out; static OutputStream errStream = System.err; static InputReader in = new InputReader(inputStream); static PrintWriter out = new PrintWriter(outputStream); static PrintWriter err = new PrintWriter(errStream); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
76fc06aeb8fd88d3cf666e6fda6b042a
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
// package Graphs; import javafx.util.Pair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; public class Lorenzo { public static void govern(HashMap<Pair<Long,Long>,Long> map,long x,long y,long cost){ long tempx=x,tempy=y; ArrayList<Long> a=new ArrayList<>(); ArrayList<Long> b=new ArrayList<>(); while(tempx!=0){ a.add(tempx); tempx/=2; } while(tempy!=0){ b.add(tempy); tempy/=2; } long father=1; for(int i=0;i<a.size();i++){ long curr=a.get(i); boolean flag=false; for(int j=0;j<b.size();j++){ if(b.get(j)==curr){ flag=true; father=curr; break; } } if(flag){ break; } } long parent1=father; long parent2=father; long newx=x,newy=y; while(newx!=parent1){ long parent=newx/2; if(map.containsKey(new Pair<>(parent,newx))){ map.put(new Pair<>(parent,newx),map.get(new Pair<>(parent,newx))+cost); } else{ map.put(new Pair<>(parent,newx),cost); } newx=parent; } while(newy!=parent2){ long parent=newy/2; if(map.containsKey(new Pair<>(parent,newy))){ map.put(new Pair<>(parent,newy),map.get(new Pair<>(parent,newy))+cost); } else{ map.put(new Pair<>(parent,newy),cost); } newy=parent; } } public static long getCost(HashMap<Pair<Long,Long>,Long> map,long x,long y){ long ans=0; long tempx=x,tempy=y; ArrayList<Long> a=new ArrayList<>(); ArrayList<Long> b=new ArrayList<>(); while(tempx!=0){ a.add(tempx); tempx/=2; } while(tempy!=0){ b.add(tempy); tempy/=2; } long father=1; for(int i=0;i<a.size();i++){ long curr=a.get(i); boolean flag=false; for(int j=0;j<b.size();j++){ if(b.get(j)==curr){ flag=true; father=curr; break; } } if(flag){ break; } } long parent1=father; long parent2=father; long newx=x,newy=y; while(newx!=parent1){ long parent=newx/2; if(map.containsKey(new Pair<>(parent,newx))){ ans+=map.get(new Pair<>(parent,newx)); } newx=parent; } while(newy!=parent2){ long parent=newy/2; if(map.containsKey(new Pair<>(parent,newy))){ ans+=map.get(new Pair<>(parent,newy)); } newy=parent; } return ans; } public static void main(String[] args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int q=Integer.parseInt(br.readLine()); HashMap<Pair<Long,Long>,Long> map=new HashMap<>(); while(q--!=0){ String line[]=br.readLine().split(" "); if(line.length==4){ long x=Long.parseLong(line[1]); long y=Long.parseLong(line[2]); long cost=Long.parseLong(line[3]); govern(map,x,y,cost); } else{ long x=Long.parseLong(line[1]); long y=Long.parseLong(line[2]); System.out.println(getCost(map,x,y)); } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
169944c30f4018b5a880ed9326dab0c9
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.TreeMap; import java.util.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 { TreeMap<long[], Long> adj = new TreeMap<>(); public void solve(int testNumber, InputReader in, PrintWriter out) { int Q = in.nextInt(); adj = new TreeMap<>((a, b) -> { for (int i = 0; i < 2; i++) { if (a[i] < b[i]) return -1; if (a[i] > b[i]) return 1; } return 0; }); for (int i = 0; i < Q; i++) { int type = in.nextInt(); long u = in.nextLong(); long v = in.nextLong(); if (type == 1) { long w = in.nextLong(); update(u, v, w); } else { out.println(cost(u, v)); } } } private long cost(long u, long v) { long ans = 0; while (u != v) { if (u > v) { ans += edge(u, u / 2); u /= 2; } else { ans += edge(v, v / 2); v /= 2; } } return ans; } private long edge(long f, long s) { long min = Math.min(f, s); long max = Math.max(f, s); long[] key = {min, max}; Long cost = adj.get(key); if (cost == null) { cost = 0L; } return cost; } private void update(long u, long v, long w) { while (u != v) { if (u > v) { updateEdge(u, u / 2, w); u /= 2; } else { updateEdge(v, v / 2, w); v /= 2; } } } private void updateEdge(long f, long s, long w) { long min = Math.min(f, s); long max = Math.max(f, s); long[] key = {min, max}; Long cost = adj.get(key); if (cost == null) { cost = 0L; } cost += w; adj.put(key, cost); } } 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 long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
a1b2401741d07bd0be5b17633759d1b4
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
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.util.InputMismatchException; import java.io.IOException; import java.util.TreeMap; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int queries = in.readInt(); TreeMap<LongLongPair, Long> tm = new TreeMap<>(); while (queries-- > 0) { int type = in.readInt(); if (type == 1) { long v = in.readLong(); long u = in.readLong(); long w = in.readLong(); while (u != v) { if (v < u) { long tmp = v; v = u; u = tmp; } long nv = v / 2; tm.merge(new LongLongPair(nv, v), w, Long::sum); v = nv; } } else { long v = in.readLong(); long u = in.readLong(); long res = 0; while (u != v) { if (v < u) { long tmp = v; v = u; u = tmp; } long nv = v / 2; if (tm.containsKey(new LongLongPair(nv, v))) res += tm.get(new LongLongPair(nv, v)); v = nv; } out.printLine(res); } } } } 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 close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class LongLongPair implements Comparable<LongLongPair> { public final long first; public final long second; public LongLongPair(long first, long 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; LongLongPair pair = (LongLongPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = Long.hashCode(first); result = 31 * result + Long.hashCode(second); return result; } public String toString() { return "(" + first + "," + second + ")"; } @SuppressWarnings ({"unchecked"}) public int compareTo(LongLongPair o) { int value = Long.compare(first, o.first); if (value != 0) { return value; } return Long.compare(second, o.second); } } 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 long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
8091a4f203b127e47e7140dfb8432c85
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
/** * Date: 14 Nov, 2018 * Link: * * @author Prasad-Chaudhari * @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/ * @git: https://github.com/Prasad-Chaudhari */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Hashtable; import java.util.Map; public class newProgram1 { public static void main(String[] args) throws IOException { // TODO code application logic here FastIO in = new FastIO(); int q = in.ni(); Map<Long, Long> map = new Hashtable<>(); while (q-- > 0) { if (in.ni() == 1) { long u = in.nl(); long v = in.nl(); int w = in.ni(); if (v > u) { u ^= v; v ^= u; u ^= v; } while (u != v) { int distu = (int) (Math.log(u) / Math.log(2)); int distv = (int) (Math.log(v) / Math.log(2)); while (distu > distv) { map.put(u, map.getOrDefault(u, 0l) + w); u /= 2; distu--; } while (distv > distu) { map.put(v, map.getOrDefault(v, 0l) + w); v /= 2; distv--; } if (u != v) { map.put(u, map.getOrDefault(u, 0l) + w); map.put(v, map.getOrDefault(v, 0l) + w); u /= 2; v /= 2; } // System.out.println(u + " " + v); } } else { long ans = 0; long u = in.nl(); long v = in.nl(); if (v > u) { u ^= v; v ^= u; u ^= v; } // int distu = (int) (Math.log(u) / Math.log(2)); // int distv = (int) (Math.log(v) / Math.log(2)); // while (distu > distv) { // ans += map.getOrDefault(u, 0l); // u /= 2; // distu--; // } // while (u != v) { // ans += map.getOrDefault(v, 0l); // ans += map.getOrDefault(u, 0l); // u /= 2; // v /= 2; // } while (u != v) { int distu = (int) (Math.log(u) / Math.log(2)); int distv = (int) (Math.log(v) / Math.log(2)); while (distu > distv) { ans += map.getOrDefault(u, 0l); u /= 2; distu--; } while (distv > distu) { ans += map.getOrDefault(v, 0l); v /= 2; distv--; } if (u != v) { ans += map.getOrDefault(v, 0l); ans += map.getOrDefault(u, 0l); u /= 2; v /= 2; } } System.out.println(ans); } } } static class FastIO { private final BufferedReader br; private final BufferedWriter bw; private String s[]; private int index; private StringBuilder sb; public FastIO() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8")); s = br.readLine().split(" "); sb = new StringBuilder(); index = 0; } public int ni() throws IOException { return Integer.parseInt(nextToken()); } public double nd() throws IOException { return Double.parseDouble(nextToken()); } public long nl() throws IOException { return Long.parseLong(nextToken()); } public String next() throws IOException { return nextToken(); } public String nli() throws IOException { try { return br.readLine(); } catch (IOException ex) { } return null; } public int[] gia(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public int[] gia(int n, int start, int end) throws IOException { validate(n, start, end); int a[] = new int[n]; for (int i = start; i < end; i++) { a[i] = ni(); } return a; } public double[] gda(int n) throws IOException { double a[] = new double[n]; for (int i = 0; i < n; i++) { a[i] = nd(); } return a; } public double[] gda(int n, int start, int end) throws IOException { validate(n, start, end); double a[] = new double[n]; for (int i = start; i < end; i++) { a[i] = nd(); } return a; } public long[] gla(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nl(); } return a; } public long[] gla(int n, int start, int end) throws IOException { validate(n, start, end); long a[] = new long[n]; for (int i = start; i < end; i++) { a[i] = nl(); } return a; } public int[][] gg(int n, int m) throws IOException { int adja[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = ni(); to[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][--count[from[i]]] = to[i]; adja[to[i]][--count[to[i]]] = from[i]; } return adja; } public void print(String s) throws IOException { bw.write(s); } public void println(String s) throws IOException { bw.write(s); bw.newLine(); } private String nextToken() throws IndexOutOfBoundsException, IOException { if (index == s.length) { s = br.readLine().split(" "); index = 0; } return s[index++]; } private void validate(int n, int start, int end) { if (start < 0 || end >= n) { throw new IllegalArgumentException(); } } } static class Data implements Comparable<Data> { int a, b; public Data(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Data o) { if (a == o.a) { return Integer.compare(b, o.b); } return Integer.compare(a, o.a); } public static void sort(int a[]) { Data d[] = new Data[a.length]; for (int i = 0; i < a.length; i++) { d[i] = new Data(a[i], 0); } Arrays.sort(d); for (int i = 0; i < a.length; i++) { a[i] = d[i].a; } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
e7ad4d298cb74ba51e11d6be435ef822
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.lang.annotation.Target; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import java.util.Map.Entry; import static java.lang.Math.*; public class Main { public static void solve(FastScanner in, BufferedWriter out) throws IOException { int q = in.nextInt(); Map<Long, Long> map = new HashMap<Long, Long>(); for (int i = 0; i < q; i++) { int t = in.nextInt(); long v = in.nextLong(); long u = in.nextLong(); long lca = findLCA(v, u); Long x; if(t == 1) { long w = in.nextInt(); //update each leaving node on the path with weight w // put charge of edge on the child node, because // each node have one incoming edge but can have 2 outgoing edge. while(v != lca) { x = map.get(v); x = x == null ? w : x + w; map.put(v, x); v >>>= 1; } while(u != lca) { x = map.get(u); x = x == null ? w : x + w; map.put(u, x); u >>>= 1; } } else { long sum = 0; while(v != lca) { x = map.get(v); if(x != null) { sum += x; } v >>>= 1; } while(u != lca) { x = map.get(u); if(x != null) { sum += x; } u >>>= 1; } out.append(String.valueOf(sum) + "\n"); } } } static long findLCA(long u, long v) { while(v != u) { if(depth(v) > depth(u)) { v >>>= 1; } else { u >>>= 1; } } return v; } static int depth(long u) { // return last digit set on u; int d = 0; while(u != 0) { d++; u >>>= 1; } return d; } /**************** ENTER HERE ********************/ public static void main(String[] args) throws Exception { FastScanner fscan = new FastScanner(System.in); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); solve(fscan,bw); bw.close(); } } class FastScanner { StringTokenizer st; BufferedReader br; public FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
00ec569f7ba56b5c185a34aa6e7365a0
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
//package cf362; import java.io.*; import java.util.*; public class cf362a { public static void main(String[] aegs) { //System.out.println(Math.log(4)/Math.log(2)); InputReader in=new InputReader(System.in); PrintWriter pw=new PrintWriter(System.out); int q=in.nextInt(); HashMap<RabNebanadijodi,Long>hm=new HashMap<RabNebanadijodi,Long>(); //int q=in.nextInt(); while(q-->0) { int t=in.nextInt(); if(t==1) { long node1=in.nextLong(); long node2=in.nextLong(); long weight=in.nextLong(); while(node2!=node1) { if(node2>node1) { long x=node2/2; RabNebanadijodi p=new RabNebanadijodi(node2,x); if(hm.containsKey(p)) { long tt=hm.get(p); tt+=weight; hm.put(p, tt); } else { hm.put(p, weight); } node2=node2/2; } else { long x=node1/2; RabNebanadijodi p=new RabNebanadijodi(node1,x); if(hm.containsKey(p)) { long tt=hm.get(p); tt+=weight; hm.put(p, tt); } else { hm.put(p, weight); } node1=node1/2; } } } else { long node1=in.nextLong(); long node2=in.nextLong(); long myans=0; while(node1!=node2) { if(node2>node1) { long x=node2/2; RabNebanadijodi p=new RabNebanadijodi(node2,x); if(hm.containsKey(p)) { long z=hm.get(p); myans+=z; } node2=node2/2; } else { long x=node1/2; RabNebanadijodi p=new RabNebanadijodi(node1,x); if(hm.containsKey(p)) { long z=hm.get(p); myans+=z; } node1=node1/2; } } pw.println(myans); } // } pw.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } 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); } } static class RabNebanadijodi implements Comparable<RabNebanadijodi> { long a,b; RabNebanadijodi (long a,long b) { this.a=a; this.b=b; } public int compareTo(RabNebanadijodi o) { // TODO Auto-generated method stub if(this.a!=o.a) return Long.compare(this.a,o.a); else return Long.compare(this.b, o.b); //return 0; } public boolean equals(Object o) { if (o instanceof RabNebanadijodi) { RabNebanadijodi p = (RabNebanadijodi)o; return p.a == a && p.b == b; } return false; } public int hashCode() { return new Long(a).hashCode() * 31 + new Long(b).hashCode(); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
9015f9fc505e17f2ac1604c0ea3a06d7
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class A { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); public void run() { int q = in.nextInt(); HashMap<String, Long> costs = new HashMap<>(); for (int i = 0; i < q; i++) { int t = in.nextInt(); ArrayList<Long> list1 = new ArrayList<>(); ArrayList<Long> list2 = new ArrayList<>(); long from = in.nextLong(), to = in.nextLong(); long cur1 = from, cur2 = to; while (cur1 != cur2) { if (cur1 > cur2) { long next = cur1 / 2; list1.add(cur1); cur1 = next; } else { long prev = cur2 / 2; list2.add(cur2); cur2 = prev; } } long[] a = new long[list1.size() + list2.size() + 1]; int ptr = 0; for (long x : list1) a[ptr++] = x; a[ptr++] = cur1; for (int j = list2.size() - 1; j >= 0; j--) a[ptr++] = list2.get(j); if (t == 1) { long w = in.nextLong(); for (int j = 0; j < ptr - 1; j++) { String key = a[j] + " " + a[j+1]; String key2 = a[j+1] + " " + a[j]; if (costs.containsKey(key)) { costs.put(key, costs.get(key) + w); costs.put(key2, costs.get(key2) + w); } else { costs.put(key, w); costs.put(key2, w); } } } else { long res = 0; for (int j = 0; j < ptr - 1; j++) { String key = a[j] + " " + a[j+1]; if (costs.containsKey(key)) res += costs.get(key); } out.println(res); } } out.close(); } public static void main(String[] args) { new A().run(); } public void mapDebug(int[][] a) { System.out.println("--------map display---------"); for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.printf("%3d ", a[i][j]); } System.out.println(); } System.out.println("----------------------------"); System.out.println(); } public void debug(Object... obj) { System.out.println(Arrays.deepToString(obj)); } class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; //stream = new FileInputStream(new File("dec.in")); } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = nextInt(); return array; } int[][] nextIntMap(int n, int m) { int[][] map = new int[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextIntArray(m); } return map; } long nextLong() { return Long.parseLong(next()); } long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) array[i] = nextLong(); return array; } long[][] nextLongMap(int n, int m) { long[][] map = new long[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextLongArray(m); } return map; } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) array[i] = nextDouble(); return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextDoubleArray(m); } return map; } 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(); } String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) array[i] = next(); return array; } String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
05069e38b40ba8266620e5a9aac6f466
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.TreeMap; import java.util.Scanner; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top * * @author zodiacLeo */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int Q = in.nextInt(); TreeMap<Edge, Long> edgeCost = new TreeMap<Edge, Long>(); for (int q = 0; q < Q; q++) { int type = in.nextInt(); long u = in.nextLong(); long v = in.nextLong(); ArrayList<Long> uPath = getRootPath(u); ArrayList<Long> vPath = getRootPath(v); long root = -1; for (int i = 0; i < uPath.size(); i++) { if (vPath.contains(uPath.get(i))) { root = uPath.get(i); break; } } if (type == 1) { long cost = in.nextLong(); //Adding edges from u -> root for (int i = 0; i < uPath.size(); i++) { if (uPath.get(i) == root) { break; } Edge e = new Edge(uPath.get(i), uPath.get(i + 1)); if (edgeCost.containsKey(e)) { edgeCost.put(e, edgeCost.get(e) + cost); } else { edgeCost.put(e, cost); } } //Adding edges from v -> root for (int i = 0; i < vPath.size(); i++) { if (vPath.get(i) == root) { break; } Edge e = new Edge(vPath.get(i), vPath.get(i + 1)); if (edgeCost.containsKey(e)) { edgeCost.put(e, edgeCost.get(e) + cost); } else { edgeCost.put(e, cost); } } } else { long totalCost = 0; for (int i = 0; i < uPath.size(); i++) { if (uPath.get(i) == root) { break; } Edge e = new Edge(uPath.get(i), uPath.get(i + 1)); if (edgeCost.containsKey(e)) { totalCost += edgeCost.get(e); } } for (int i = 0; i < vPath.size(); i++) { if (vPath.get(i) == root) { break; } Edge e = new Edge(vPath.get(i), vPath.get(i + 1)); if (edgeCost.containsKey(e)) { totalCost += edgeCost.get(e); } } out.println(totalCost); } } } public ArrayList<Long> getRootPath(long u) { ArrayList<Long> path = new ArrayList<Long>(); while (u != 0) { path.add(u); u >>= 1; } return path; } class Edge implements Comparable<Edge> { long u; long v; Edge(long u, long v) { this.u = Math.min(u, v); this.v = Math.max(u, v); } public int compareTo(Edge that) { if (this.u == that.u) { return (int) Long.compare(this.v, that.v); } return (int) Long.compare(this.u, that.u); } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
fe8a767407165246fbe41fdb866acd8a
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
//package ; import java.io.*; import java.util.*; public class D { static int log(long x) { return (int)(Math.log(x)/Math.log(2)); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter pw = new PrintWriter(System.out); int q=sc.nextInt(); TreeMap<Pair, Long>hm=new TreeMap<>(); while(q-->0) { long t=sc.nextInt(); long u=sc.nextLong(),v=sc.nextLong(); Pair p=new Pair(u,v); u=p.u; v=p.v; if(t==1) { long w=sc.nextLong(); int i=log(u),j=log(v); while(u!=v) { if(i>j) { u>>=1;i=log(u); } else { v>>=1;j=log(v); } } long lca=v; u=p.u; v=p.v; while(u!=lca) { hm.put(new Pair(u, u>>1), hm.getOrDefault(new Pair(u, u>>1), 0l)+w); u>>=1; } while(v!=lca) { hm.put(new Pair(v, v>>1), hm.getOrDefault(new Pair(v, v>>1), 0l)+w); v>>=1; } } else { long ans=0; int i=log(u),j=log(v); while(u!=v) { if(i>j) { u>>=1;i=log(u); } else { v>>=1;j=log(v); } } long lca=v; u=p.u; v=p.v; while(u!=lca) { ans+=hm.getOrDefault(new Pair(u, u>>1), 0l); u>>=1; } while(v!=lca) { ans+=hm.getOrDefault(new Pair(v, v>>1), 0l); v>>=1; } pw.println(ans); } } pw.close(); } static class Pair implements Comparable<Pair> { long u,v; public Pair(long x,long y) { // TODO Auto-generated constructor stub u=Math.min(x, y); v=Math.max(x, y); } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return u==o.u?Long.compare(v, o.v):Long.compare(u, o.u); } @Override public String toString() { // TODO Auto-generated method stub return u+" "+v; } } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasnext() throws IOException { return br.ready(); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
bb03515dd7c962d3cbe07cbbdc840116
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(System.out); new A(new FastScanner(System.in), out); out.close(); } int getDepth(long v) { return Long.numberOfTrailingZeros(Long.highestOneBit(v)); } ArrayList<Long> getNodes(long i, long j) { ArrayList<Long> res = new ArrayList<>(); int d1 = getDepth(i); int d2 = getDepth(j); while (i != j) { if (d1 > d2) { res.add(i); i /= 2; d1--; } else if (d1 < d2) { res.add(j); j /= 2; d2--; } else { res.add(i); res.add(j); i /= 2; d1--; j /= 2; d2--; } } return res; } public A(FastScanner in, PrintWriter out) { HashMap<Long, Long> mmp = new HashMap<>(); int Q = in.nextInt(); while (Q-->0) { int t = in.nextInt(); if (t == 1) { long i = in.nextLong(); long j = in.nextLong(); int w = in.nextInt(); ArrayList<Long> vs = getNodes(i, j); for (long k : vs) { Long rr = mmp.get(k); if (rr == null) rr = 0L; rr += w; mmp.put(k, rr); } } else { long res = 0; long i = in.nextLong(); long j = in.nextLong(); ArrayList<Long> vs = getNodes(i, j); for (long k : vs) { Long rr = mmp.get(k); if (rr != null) res += rr; } out.println(res); } } } } class FastScanner{ private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; } 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++]; } boolean isSpaceChar(int c) { return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1; } boolean isEndline(int c) { return c=='\n'||c=='\r'||c==-1; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } 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(); } String nextLine(){ int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do{ res.appendCodePoint(c); c = read(); }while(!isEndline(c)); return res.toString(); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
2cbe515d23cd3bbe9584cb01907ab7cb
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { // OutputStream out = new BufferedOutputStream(System.out); FastReader sc = new FastReader(); Map<Long, Long> map = new HashMap<Long, Long>(); int q = sc.nextInt(); for (int i = 0; i < q; i++) { int t = sc.nextInt(); if (t == 1) { long u = sc.nextLong(); long v = sc.nextLong(); long value = sc.nextInt(); do { if (u > v) { if (map.get(u) != null) { map.replace(u, map.get(u) + value); } else { map.put(u, value); } u /= 2; } else { if (map.get(v) != null) { map.replace(v, map.get(v) + value); } else { map.put(v, value); } v /= 2; } } while (u != v); } else { long u = sc.nextLong(); long v = sc.nextLong(); long ans = 0; do { if (u > v) { if (map.get(u) != null) { ans += map.get(u); } u /= 2; } else { if (map.get(v) != null) { ans += map.get(v); } v /= 2; } } while (u != v); out.write((ans + "\n").getBytes()); } } out.flush(); } 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) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
1deab9f68d48b6f828e3d73c648be805
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
// package codeforces.cf3xx.cf362.div1; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; /** * Created by hama_du on 2016/07/15. */ public class A { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int q = in.nextInt(); Map<Long,Long> cost = new HashMap<>(); while (--q >= 0) { int type = in.nextInt(); long u = in.nextLong(); long v = in.nextLong(); List<Long> arr = doit(u, v); if (type == 1) { long c = in.nextInt(); for (long a : arr) { cost.put(a, cost.getOrDefault(a, 0L)+c); } } else { long sum = 0; for (long a : arr) { sum += cost.getOrDefault(a, 0L); } out.println(sum); } } out.flush(); } private static List<Long> doit(long u, long v) { List<Long> ret = new ArrayList<>(); if (u == v) { return ret; } int ud = depth(u); int vd = depth(v); while (ud != vd) { if (ud < vd) { ret.add(v); v /= 2; vd--; } else { ret.add(u); u /= 2; ud--; } } while (u != v) { ret.add(u); ret.add(v); u /= 2; v /= 2; } return ret; } private static int depth(long v) { int d = 0; while (v >= 1) { d++; v /= 2; } return d; } 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 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 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
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
69d0979861744f88cbe4b7d0dac7ec52
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; public class A696 { static HashMap<Long, Long> cost = new HashMap<Long, Long>(); static long lca(long u, long v) { if (u > v) { long tmp = u; u = v; v = tmp; } if (u == v || u == 1) { return u; } while(fa(v) != u && fa(v) != fa(u)) { v = fa(v); if (v < u) { long tmp = u; u = v; v = tmp; } } return fa(v); } static long fa(long u) { if (u == 1) { return 1; } else { return u / 2; } } static void add(long v, long w) { if (cost.containsKey(v)) { cost.put(v, cost.get(v) + w); } else { cost.put(v, w); } } static long get(long v) { if (cost.containsKey(v)) { return cost.get(v); } else { return 0L; } } static void addCost(long u, long cf, long w) { while(u != cf) { add(u, w); u = fa(u); } } static long getPathToRoot(long u, long cf) { long ans = 0; while(u != cf) { ans += get(u); u = fa(u); } return ans; } static long getPath(long u, long v) { long cf = lca(u, v); return getPathToRoot(u,cf) + getPathToRoot(v,cf); } public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int q = in.nextInt(); int t; long u, v, w, cf; while(q-- > 0) { t = in.nextInt(); u = in.nextLong(); v = in.nextLong(); if (t == 1) { w = in.nextLong(); cf = lca(u, v); addCost(u, cf , w); addCost(v, cf, w); } else { out.println(getPath(u, v)); } } out.close(); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
7876a4c7ee14ba975309c9e3ca4a358a
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.util.*; import java.io.*; public class Solution696A { private static FastScanner in; private static PrintWriter out; public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new Solution().solve(); out.close(); } public static class Solution { public void solve() { int q = in.nextInt(); Map<Long, Long> d = new HashMap<>(); for (int i = 0; i < q; i++) { int qhead = in.nextInt(); long v = in.nextLong(); long u = in.nextLong(); if (qhead == 1) { long w = in.nextLong(); while (u != v) { if (u > v) { d.put(u, (d.containsKey(u) ? d.get(u) : 0) + w); u /= 2; } else { d.put(v, (d.containsKey(v) ? d.get(v) : 0) + w); v /= 2; } } } else { long cost = 0; while (u != v) { if (u > v) { cost += d.containsKey(u) ? d.get(u) : 0; u /= 2; } else { cost += d.containsKey(v) ? d.get(v) : 0; v /= 2; } } out.println(cost); } } } } private static class FastScanner { private BufferedReader br; private StringTokenizer st; public FastScanner(BufferedReader br) { this.br = br; } private String next() { while (st == null || !st.hasMoreTokens()) { 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
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
91d3e493d77c1911872535c75a5e9546
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
//package round362; import java.io.ByteArrayInputStream; 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 A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { Map<Long, Long> map = new HashMap<>(); for(int Q = ni();Q > 0;Q--){ int t = ni(); if(t == 1){ long x = nl(), y = nl(); int w = ni(); long lca = lca(x, y); for(long u = x;u != lca;u>>>=1){ map.merge(u, (long)w, Long::sum); } for(long u = y;u != lca;u>>>=1){ map.merge(u, (long)w, Long::sum); } }else{ long x = nl(), y = nl(); long lca = lca(x, y); long ret = 0; for(long u = x;u != lca;u>>>=1){ ret += map.getOrDefault(u, 0L); } for(long u = y;u != lca;u>>>=1){ ret += map.getOrDefault(u, 0L); } out.println(ret); } } } long lca(long x, long y) { long xx = x, yy = y; if(Long.highestOneBit(x) > Long.highestOneBit(y)){ xx /= Long.highestOneBit(x)/Long.highestOneBit(y); }else{ yy /= Long.highestOneBit(y)/Long.highestOneBit(x); } if(xx == yy)return xx; long lca = xx/Long.highestOneBit(xx^yy)/2; return lca; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
19b3355542b12b6f3b1c373f56987868
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class zizo { public static void main(String args[]) throws IOException { Scanner zizo=new Scanner (System.in); PrintWriter wr=new PrintWriter(System.out); HashMap<Long , Long> map = new HashMap<>(); int q = zizo.nextInt(); while(q-->0) { int t = zizo.nextInt(); long u = zizo.nextLong(); long v = zizo.nextLong(); if(t==1) { long w = zizo.nextLong(); while(u != v) { if(v > u) { long temp = u; u = v; v = temp; } if(map.containsKey(u)) map.put(u , map.get(u)+w); else map.put(u , w); u/=2; } }else { long ans = 0; while(u != v) { if(v > u) { long temp = u; u=v; v = temp; } if(map.containsKey(u)) ans+=map.get(u); u/=2; }wr.println(ans); } } wr.close(); } } class DSU{ int[]p,size; DSU(int n){ p=new int[n]; size=new int[n]; for(int i=0;i<n;i++) { p[i]=i;size[i]=1; } } int findSet(int x) { return p[x]==x?x:(p[x]=findSet(p[x])); } void union(int u,int v) { int x=findSet(u); int y=findSet(v); if(x==y)return; if(size[x]>=size[y]) { p[y]=x;size[x]+=size[y]; }else { p[x]=y;size[y]+=size[x]; } } boolean sameSet(int x,int y) { return findSet(x)==findSet(y); } } class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine(), " "); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
13f97415350d13afe5c623427a60684c
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class Main { static TreeMap<String, Long> edges; public static void main(String[] args) throws Exception { Scanner s = new Scanner(System.in); BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); edges = new TreeMap<>(); int q = Integer.parseInt(f.readLine()); for(int i = 0; i < q; i++) { String[] split = f.readLine().split("\\s+"); int op = Integer.parseInt(split[0]); if(op == 1) { long u = Long.parseLong(split[1]), v = Long.parseLong(split[2]); long max = Math.max(u, v), min = Math.min(u, v); long w = Long.parseLong(split[3]); while(u != v) { if(u > v) { long to = u / 2; String it = u + " " + to; if(!edges.containsKey(it)) edges.put(it, 0l); edges.put(it, edges.get(it) + w); u = to; } else { long to = v / 2; String it = v + " " + to; if(!edges.containsKey(it)) edges.put(it, 0l); edges.put(it, edges.get(it) + w); v = to; } } } else { long print = 0; long u = Long.parseLong(split[1]), v = Long.parseLong(split[2]); while(u != v) { if(u > v) { long to = u / 2; String it = u + " " + to; if(!edges.containsKey(it)) edges.put(it, 0l); print += edges.get(it); u = to; } else { long to = v / 2; String it = v + " " + to; if(!edges.containsKey(it)) edges.put(it, 0l); print += edges.get(it); v = to; } } out.println(print); } } out.close(); } static int gcd(int a, int b) { if(b == 0) return a; return gcd(b, a%b); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
09e5f48530aba2467ce611cef41507ab
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
//package com.pb.codeforces.practice; import java.util.HashMap; import java.util.Scanner; public class CF696A { public static void LCA(long u, long v, long wt, HashMap<String,Long> emap) { while(u != v) { if(u > v) { long tu = u/2; emap.put(u+"-"+tu, emap.getOrDefault(u+"-"+tu, 0L)+wt); emap.put(tu+"-"+u, emap.getOrDefault(tu+"-"+u, 0L)+wt); u = tu; }else { long tv = v/2; emap.put(v+"-"+tv, emap.getOrDefault(v+"-"+tv, 0L)+wt); emap.put(tv+"-"+v, emap.getOrDefault(tv+"-"+v, 0L)+wt); v = tv; } } } public static long LCACost(long u, long v, HashMap<String,Long> emap) { long cost = 0; while(u != v) { if(u > v) { long tu = u/2; if(emap.containsKey(u+"-"+tu)) cost += emap.get(u+"-"+tu); u = tu; }else { long tv = v/2; if(emap.containsKey(v+"-"+tv)) cost += emap.get(v+"-"+tv); v = tv; } } return cost; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int q = in.nextInt(); HashMap<String,Long> emap = new HashMap<String,Long>(); while(q-- > 0) { int event = in.nextInt(); if(event == 1) { long u = in.nextLong(); long v = in.nextLong(); long w = in.nextLong(); LCA(u,v,w,emap); }else { long u = in.nextLong(); long v = in.nextLong(); System.out.println(LCACost(u,v,emap)); } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
3f8026d26e8093a938342b4ff3206c4f
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; public class Main { private FastScanner in; private PrintWriter out; private void solve() throws IOException { int q = in.nextInt(); Map<Long, Long> m = new TreeMap<>(); while (q-- > 0) { long u, v, w, res; switch (in.nextInt()) { case 1: u = in.nextLong(); v = in.nextLong(); w = in.nextLong(); while (u != v) { if (u < v) { long t = u; u = v; v = t; } // u > v m.put(u, w + m.getOrDefault(u, 0L)); u /= 2; } break; case 2: u = in.nextLong(); v = in.nextLong(); res = 0; while (u != v) { if (u < v) { long t = u; u = v; v = t; } // u > v res += m.getOrDefault(u, 0L); u /= 2; } out.println(res); break; } } } private void run() throws IOException { in = new FastScanner(); out = new PrintWriter(System.out, false); solve(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } } class FastScanner { private final BufferedReader br; private StringTokenizer st; private String last; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String path) throws IOException { br = new BufferedReader(new FileReader(path)); } public FastScanner(String path, String decoder) throws IOException { br = new BufferedReader(new InputStreamReader(new FileInputStream(path), decoder)); } String next() throws IOException { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); last = null; return st.nextToken(); } String nextLine() throws IOException { st = null; return (last == null) ? br.readLine() : last; } boolean hasNext() { if (st != null && st.hasMoreElements()) return true; try { while (st == null || !st.hasMoreElements()) { last = br.readLine(); st = new StringTokenizer(last); } } catch (Exception e) { return false; } return true; } String[] nextStrings(int n) throws IOException { String[] arr = new String[n]; for (int i = 0; i < n; i++) arr[i] = next(); return arr; } String[] nextLines(int n) throws IOException { String[] arr = new String[n]; for (int i = 0; i < n; i++) arr[i] = nextLine(); return arr; } int nextInt() throws IOException { return Integer.parseInt(next()); } int[] nextInts(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } Integer[] nextIntegers(int n) throws IOException { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } int[][] next2Ints(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextInt(); return arr; } long nextLong() throws IOException { return Long.parseLong(next()); } long[] nextLongs(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } long[][] next2Longs(int n, int m) throws IOException { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextLong(); return arr; } double nextDouble() throws IOException { return Double.parseDouble(next().replace(',', '.')); } double[] nextDoubles(int size) throws IOException { double[] arr = new double[size]; for (int i = 0; i < size; i++) arr[i] = nextDouble(); return arr; } boolean nextBool() throws IOException { String s = next(); if (s.equalsIgnoreCase("true") || s.equals("1")) return true; if (s.equalsIgnoreCase("false") || s.equals("0")) return false; throw new IOException("Boolean expected, String found!"); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
6b785d458ba4c37eeb39524014e73b23
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author sarthak */ import java.util.*; import java.math.*; import java.io.*; public class rnd362_C { static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return ""; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } static class P implements Comparable { private long x, y; public P(long x, long y) { this.x = x; this.y = y; } public int hashCode() { return ((int) x * 31) ^ (int) y; } public boolean equals(Object o) { if (o instanceof P) { P other = (P) o; return (x == other.x && y == other.y); } return false; } public int compareTo(Object obj) { P l = (P) obj; if (this.x == l.x) { if (this.y == l.y) { return 0; } return (this.y < l.y) ? -1 : 1; } return (this.x < l.x) ? -1 : 1; } } public static long l(long v) { int cl = 1; while (v != 1) { v=v/2; cl++; } return cl; } public static void main(String[] args) { FastScanner s = new FastScanner(System.in); StringBuilder op = new StringBuilder(); int q = s.nextInt(); HashMap<P,Long>hs=new HashMap<>(); for (int i = 0; i < q; i++) { int t = s.nextInt(); if (t == 1) { long u = s.nextLong(); long v = s.nextLong(); long w=s.nextLong(); long su=u; long sv=v; long lu = l(u); long lv = l(v); ArrayList<Long> U=new ArrayList<>();U.add(u); ArrayList<Long> V=new ArrayList<>();V.add(v); while(lv!=lu){ if(lv>lu){ v=v/2;lv--;V.add(v); }else{ u=u/2;lu--;U.add(u); } } while(u!=v){ u=u/2;U.add(u); v=v/2;V.add(v); } int szu=U.size()-1;int szv=V.size()-1; for(int j=szu;j>0;j--){ if(!hs.containsKey(new P(Math.min(U.get(j), U.get(j-1)),Math.max(U.get(j), U.get(j-1))))){ hs.put(new P(Math.min(U.get(j), U.get(j-1)),Math.max(U.get(j), U.get(j-1))),0L); } long cw=hs.get(new P(Math.min(U.get(j), U.get(j-1)),Math.max(U.get(j), U.get(j-1)))); cw+=w; hs.put(new P(Math.min(U.get(j), U.get(j-1)),Math.max(U.get(j), U.get(j-1))),cw); } for(int j=szv;j>0;j--){ if(!hs.containsKey(new P(Math.min(V.get(j), V.get(j-1)),Math.max(V.get(j), V.get(j-1))))){ hs.put(new P(Math.min(V.get(j), V.get(j-1)),Math.max(V.get(j), V.get(j-1))),0L); } long cw=hs.get(new P(Math.min(V.get(j), V.get(j-1)),Math.max(V.get(j), V.get(j-1)))); cw+=w; hs.put(new P(Math.min(V.get(j), V.get(j-1)),Math.max(V.get(j), V.get(j-1))),cw); } } if (t == 2) { long u = s.nextLong(); long v = s.nextLong(); long su=u; long sv=v; long lu = l(u); long lv = l(v); ArrayList<Long> U=new ArrayList<>();U.add(u); ArrayList<Long> V=new ArrayList<>();V.add(v); while(lv!=lu){ if(lv>lu){ v=v/2;lv--;V.add(v); }else{ u=u/2;lu--;U.add(u); } } while(u!=v){ u=u/2;U.add(u); v=v/2;V.add(v); } int szu=U.size()-1;int szv=V.size()-1; long an=0; for(int j=szu;j>0;j--){ if(hs.containsKey(new P(Math.min(U.get(j), U.get(j-1)),Math.max(U.get(j), U.get(j-1))))){ an+=hs.get(new P(Math.min(U.get(j), U.get(j-1)),Math.max(U.get(j), U.get(j-1)))); } } for(int j=szv;j>0;j--){ if(hs.containsKey(new P(Math.min(V.get(j), V.get(j-1)),Math.max(V.get(j), V.get(j-1))))){ an+=hs.get(new P(Math.min(V.get(j), V.get(j-1)),Math.max(V.get(j), V.get(j-1)))); } } op.append(an+"\n"); } } System.out.print(op); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
f2155c8fdb879097a27da5e4eee48f36
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class A { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); public void run() { int q = in.nextInt(); HashMap<String, Long> costs = new HashMap<>(); for (int i = 0; i < q; i++) { int t = in.nextInt(); ArrayList<Long> list1 = new ArrayList<>(); ArrayList<Long> list2 = new ArrayList<>(); long from = in.nextLong(), to = in.nextLong(); long cur1 = from, cur2 = to; while (cur1 != cur2) { if (cur1 > cur2) { long next = cur1 / 2; list1.add(cur1); cur1 = next; } else { long prev = cur2 / 2; list2.add(cur2); cur2 = prev; } } long[] a = new long[list1.size() + list2.size() + 1]; int ptr = 0; for (long x : list1) a[ptr++] = x; a[ptr++] = cur1; for (int j = list2.size() - 1; j >= 0; j--) a[ptr++] = list2.get(j); if (t == 1) { long w = in.nextLong(); for (int j = 0; j < ptr - 1; j++) { String key = a[j] + " " + a[j+1]; String key2 = a[j+1] + " " + a[j]; if (costs.containsKey(key)) { costs.put(key, costs.get(key) + w); costs.put(key2, costs.get(key2) + w); } else { costs.put(key, w); costs.put(key2, w); } } } else { long res = 0; for (int j = 0; j < ptr - 1; j++) { String key = a[j] + " " + a[j+1]; if (costs.containsKey(key)) res += costs.get(key); } out.println(res); } } out.close(); } public static void main(String[] args) { new A().run(); } public void mapDebug(int[][] a) { System.out.println("--------map display---------"); for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.printf("%3d ", a[i][j]); } System.out.println(); } System.out.println("----------------------------"); System.out.println(); } public void debug(Object... obj) { System.out.println(Arrays.deepToString(obj)); } class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; //stream = new FileInputStream(new File("dec.in")); } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = nextInt(); return array; } int[][] nextIntMap(int n, int m) { int[][] map = new int[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextIntArray(m); } return map; } long nextLong() { return Long.parseLong(next()); } long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) array[i] = nextLong(); return array; } long[][] nextLongMap(int n, int m) { long[][] map = new long[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextLongArray(m); } return map; } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) array[i] = nextDouble(); return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextDoubleArray(m); } return map; } 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(); } String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) array[i] = next(); return array; } String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
66e76543e98bb8fc595f59029c44af44
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedHashMap; import java.util.Map; import java.util.StringTokenizer; /** * Created by pallavi on 18/7/16. */ public class A696 { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int q = Integer.parseInt(reader.readLine()); Map<Path, Long> gv = new LinkedHashMap<>(); for (int i = 0; i < q; i++) { StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int qq = Integer.parseInt(tokenizer.nextToken()); switch (qq) { case 1: long u = Long.parseLong(tokenizer.nextToken()); long v = Long.parseLong(tokenizer.nextToken()); long w = Long.parseLong(tokenizer.nextToken()); Path path = new Path(u, v); Path[] paths = f(path); for (Path path1 : paths) { gv.put(path1, w); } break; case 2: u = Long.parseLong(tokenizer.nextToken()); v = Long.parseLong(tokenizer.nextToken()); long r = 0; path = new Path(u, v); paths = f(path); for (Path path1: gv.keySet()) { for (Path path2: paths) { r += gv.get(path1) * s(path1, path2); } } System.out.println(r); break; } } } static long s(Path path1, Path path2) { long u1 = path1.u, v1 = path1.v, u2 = path2.u, v2 = path2.v; long c = 0; while (v1 != u1 && v2 != u2) { if (v1 > v2) { v1 >>= 1; } else if (v2 > v1) { v2 >>= 1; } else { c++; v1 >>= 1; v2 >>= 1; } } return c; } static Path[] f(Path path) { Path npath = new Path(path.u, path.v); while (npath.u != npath.v) { npath = new Path(npath.u, npath.v/2); } if (npath.u == path.u) return new Path[]{path}; return new Path[]{new Path(npath.u, path.u), new Path(npath.u, path.v)}; } static class Path { long u, v; public Path(long u, long v) { this.u = Math.min(u, v); this.v = Math.max(u, v); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
f4315677056c9ea5837a2022ce55a65f
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
/** * Created by ankeet on 7/14/16. */ import java.io.*; import java.util.*; import java.math.*; public class C697 { public static BufferedReader read = null; public static PrintWriter out = null; public static StringTokenizer token = null; public static long LCA(long a, long b) { ArrayList<Long> anc = new ArrayList<>(); while(a > 0) { anc.add(a); a/=2; } while(b > 0) { if(anc.contains(b)) return b; b/=2; } return 1; } public static void solve() { HashMap<Long, Long> hm = new HashMap<Long, Long>(); int q = nint(); while(q-->0) { int t = nint(); if(t == 1) { long v = nlong(), u = nlong(), w = nlong(); long anc = LCA(u,v); while(v != anc) { if(hm.containsKey(v)) { hm.put(v,hm.get(v)+w); } else { hm.put(v, w); } v/=2; } while(u != anc) { if(hm.containsKey(u)) { hm.put(u,hm.get(u)+w); } else { hm.put(u, w); } u/=2; } } else { long v = nlong(), u = nlong(); long anc = LCA(u,v); long sum = 0; while(v != anc) { if(hm.containsKey(v)) { sum+=hm.get(v); } v/=2; } while(u != anc) { if(hm.containsKey(u)) { sum+=hm.get(u); } u/=2; } out.println(sum); } } } public static void main(String[] args) { read = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.flush(); out.close(); } // i/o functions public static String next() // returns the next string { while(token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(read.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return token.nextToken(); } public static int nint() { return Integer.parseInt(next()); } public static long nlong() { return Long.parseLong(next()); } public static double ndouble() { return Double.parseDouble(next()); } public static int[] narr(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = nint(); return a; } public static long[] nlarr(int n) { long[] a = new long[n]; for(int i=0; i<n; i++) a[i] = nlong(); return a; } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
07920d04c5c8eea575ef57d65568e0b6
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class C { public static StringTokenizer tokenizer = null; public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public static String nextToken() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.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 class Node { public long number; public Node left = null, right = null; public long leftDist = 0, rightDist = 0; public Node(long number) { this.number = number; } } public static Map<Long, Node> map = new HashMap<>(); public static List<Long> firstList = new ArrayList<>(200); public static List<Long> secondList = new ArrayList<>(200); public static void build(long v) { Node prevNode = null; long prevV = -1; while (!map.containsKey(v)) { Node newNode = new Node(v); if (prevV == v * 2) { newNode.left = prevNode; } else if (prevV == v * 2 + 1) { newNode.right = prevNode; } map.put(v, newNode); prevNode = newNode; prevV = v; v /= 2; } Node existingNode = map.get(v); if (prevV == v * 2) { existingNode.left = prevNode; } else if (prevV == v * 2 + 1) { existingNode.right = prevNode; } } public static void buildList(List<Long> list, long v) { list.clear(); while (v != 1) { list.add(v); v /= 2; } list.add(1L); } public static void raiseNode(long v, long child, long w) { Node node = map.get(v); if (child == v * 2) { node.leftDist += w; } else { node.rightDist += w; } } public static void raise(long u, long v, long w) { buildList(firstList, u); buildList(secondList, v); int indexFirst = firstList.size() - 1; int indexSecond = secondList.size() - 1; while (indexFirst > 0 && indexSecond > 0 && firstList.get(indexFirst - 1).equals(secondList.get(indexSecond - 1))) { indexFirst--; indexSecond--; } for (int i = indexFirst; i > 0; i--) { raiseNode(firstList.get(i), firstList.get(i - 1), w); } for (int i = indexSecond; i > 0; i--) { raiseNode(secondList.get(i), secondList.get(i - 1), w); } } public static long getCost(long v, long child) { Node node = map.get(v); if (child == v * 2) { return node.leftDist; } else { return node.rightDist; } } public static long count(long u, long v) { long result = 0; buildList(firstList, u); buildList(secondList, v); int indexFirst = firstList.size() - 1; int indexSecond = secondList.size() - 1; while (indexFirst > 0 && indexSecond > 0 && firstList.get(indexFirst - 1).equals(secondList.get(indexSecond - 1))) { indexFirst--; indexSecond--; } for (int i = indexFirst; i > 0; i--) { result += getCost(firstList.get(i), firstList.get(i - 1)); } for (int i = indexSecond; i > 0; i--) { result += getCost(secondList.get(i), secondList.get(i - 1)); } return result; } public static void main(String[] args) throws IOException { map.put(1L, new Node(1)); int q = nextInt(); for (int i = 0; i < q; i++) { int type = nextInt(); if (type == 1) { long u = nextLong(); long v = nextLong(); long w = nextLong(); build(u); build(v); raise(u, v, w); } else { long u = nextLong(); long v = nextLong(); build(u); build(v); long answer = count(u, v); System.out.println(answer); } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
881c240c0a305f57114a427a5ebe43b1
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class A { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void solve() throws IOException { int t = 1; while (t-- > 0) { solveTest(); } } class Edge implements Comparable<Edge> { long x; long y; public Edge(long x, long y) { if(x > y) { long tmp = x; x = y; y = tmp; } this.x = x; this.y = y; } @Override public int compareTo(Edge o) { int res = Long.compare(this.x, o.x); if(res != 0) return res; return Long.compare(this.y, o.y); } } void solveTest() throws IOException { int q = readInt(); Map<Edge, Long> added = new TreeMap<>(); for(int i = 0; i < q; i++) { int t = readInt(); long v = readLong(); long u = readLong(); List<Long> path = path(v, u); if(t == 1) { long w = readLong(); for(int j = 0; j < path.size() - 1; j++) { Edge e = new Edge(path.get(j), path.get(j+1)); if(added.containsKey(e)) { added.put(e, added.get(e) + w); } else { added.put(e, w); } } } else { long res = 0; for(int j = 0; j < path.size() - 1; j++) { Edge e = new Edge(path.get(j), path.get(j+1)); if(added.containsKey(e)) { res += added.get(e); } } out.println(res); } } } List<Long> path(long x, long y) { if(x > y) { long tmp = x; x = y; y = tmp; } int xLvl = lvl(x); int yLvl = lvl(y); List<Long> resX = new ArrayList<>(); List<Long> resY = new ArrayList<>(); while (yLvl != xLvl) { yLvl--; resY.add(y); y /= 2; } while (x != y) { resX.add(x); resY.add(y); x /= 2; y /= 2; } Collections.reverse(resY); resX.add(x); resX.addAll(resY); return resX; } int lvl(long x) { int res = 0; while(x != 1) { res++; x /= 2; } return res; } void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } int[] readArr(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = readInt(); } return res; } long[] readArrL(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = readLong(); } return res; } public static void main(String[] args) { new A().run(); } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
c3777dbb4e61608141557597803b3cf8
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class A { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void solve() throws IOException { int t = 1; while (t-- > 0) { solveTest(); } } class Edge implements Comparable<Edge> { long x; long y; public Edge(long x, long y) { if(x > y) { long tmp = x; x = y; y = tmp; } this.x = x; this.y = y; } @Override public int compareTo(Edge o) { int res = Long.compare(this.x, o.x); if(res != 0) return res; return Long.compare(this.y, o.y); } } void solveTest() throws IOException { int q = readInt(); Map<Edge, Long> added = new TreeMap<>(); for(int i = 0; i < q; i++) { int t = readInt(); long v = readLong(); long u = readLong(); List<Long> path = path(v, u); if(t == 1) { long w = readLong(); for(int j = 0; j < path.size() - 1; j++) { Edge e = new Edge(path.get(j), path.get(j+1)); if(added.containsKey(e)) { added.put(e, added.get(e) + w); } else { added.put(e, w); } } } else { long res = 0; for(int j = 0; j < path.size() - 1; j++) { Edge e = new Edge(path.get(j), path.get(j+1)); if(added.containsKey(e)) { res += added.get(e); } } out.println(res); } } } List<Long> path(long x, long y) { if(x > y) { long tmp = x; x = y; y = tmp; } int xLvl = lvl(x); int yLvl = lvl(y); List<Long> resX = new ArrayList<>(); List<Long> resY = new ArrayList<>(); while (yLvl != xLvl) { yLvl--; resY.add(y); y /= 2; } while (x != y) { resX.add(x); resY.add(y); x /= 2; y /= 2; } Collections.reverse(resY); resX.add(x); resX.addAll(resY); return resX; } int lvl(long x) { int res = 0; while(x != 1) { res++; x /= 2; } return res; } void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } int[] readArr(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = readInt(); } return res; } long[] readArrL(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = readLong(); } return res; } public static void main(String[] args) { new A().run(); } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
2c81a90ecd6c89cf77f2338039501298
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class A { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void solve() throws IOException { int t = 1; while (t-- > 0) { solveTest(); } } class Edge implements Comparable<Edge> { long x; long y; public Edge(long x, long y) { if(x > y) { long tmp = x; x = y; y = tmp; } this.x = x; this.y = y; } @Override public int compareTo(Edge o) { int res = Long.compare(this.x, o.x); if(res != 0) return res; return Long.compare(this.y, o.y); } } void solveTest() throws IOException { int q = readInt(); Map<Edge, Long> added = new TreeMap<>(); for(int i = 0; i < q; i++) { int t = readInt(); long v = readLong(); long u = readLong(); List<Long> path = path(v, u); if(t == 1) { long w = readLong(); for(int j = 0; j < path.size() - 1; j++) { Edge e = new Edge(path.get(j), path.get(j+1)); added.compute(e, (key, old) -> old == null ? w : old + w); } } else { long res = 0; for(int j = 0; j < path.size() - 1; j++) { Edge e = new Edge(path.get(j), path.get(j+1)); res += added.getOrDefault(e, 0l); } out.println(res); } } } List<Long> path(long x, long y) { if(x > y) { long tmp = x; x = y; y = tmp; } int xLvl = lvl(x); int yLvl = lvl(y); List<Long> resX = new ArrayList<>(); List<Long> resY = new ArrayList<>(); while (yLvl != xLvl) { yLvl--; resY.add(y); y /= 2; } while (x != y) { resX.add(x); resY.add(y); x /= 2; y /= 2; } Collections.reverse(resY); resX.add(x); resX.addAll(resY); return resX; } int lvl(long x) { int res = 0; while(x != 1) { res++; x /= 2; } return res; } void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } int[] readArr(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = readInt(); } return res; } long[] readArrL(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = readLong(); } return res; } public static void main(String[] args) { new A().run(); } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
7f5edaf8ff009bc34c6993709da62efe
train_002.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; /** * Hello world! * */ public class App { private static Map<Long, Long> tree = new HashMap<>(); public static void main(String[] args) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { String[] line; line = reader.readLine().split(" "); int q = Integer.parseInt(line[0]); for (int i = 0; i < q; ++i) { line = reader.readLine().split(" "); long u = Long.parseLong(line[1]); long v = Long.parseLong(line[2]); if (line[0].equals("1")) { int weight = Integer.parseInt(line[3]); setWeight(u, v, weight); } else { System.out.println(getWeight(u, v)); } } } } private static long getWeight(long u, long v) { return u == v ? 0 : u < v ? tree.getOrDefault(v, 0L) + getWeight(u, v >> 1) : tree.getOrDefault(u, 0L) + getWeight(u >> 1, v); } private static void setWeight(long u, long v, int w) { while (u != v) { if (u > v) { tree.put(u, tree.getOrDefault(u, 0L) + w); u >>= 1; } else if (u < v) { tree.put(v, tree.getOrDefault(v, 0L) + w); v >>= 1; } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≤ q ≤ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output