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
9198a62be29a3f2b13ca1eab15cb0b82
train_002.jsonl
1590327300
Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly $$$n$$$ shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); while(t-- > 0){ int n = s.nextInt(); int k = s.nextInt(); if(k >= n) System.out.println(1); else{ int ans = n; int highest = 1; for(int i = 2; i <= Math.sqrt(n); i++){ if(n % i == 0){ int a = i, b = n/i; if(b <= k){ highest = b; i = b; }else if(a <= k){ highest = a; i = a; }else{ break; } } } ans = n/highest; System.out.println(ans); } } } }
Java
["5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733"]
2 seconds
["2\n8\n1\n999999733\n1"]
NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.
Java 8
standard input
[ "number theory", "math" ]
f00eb0452f5933103f1f77ef06473c6a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.
1,300
Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.
standard output
PASSED
cb43ea6277149443d138407db798be2f
train_002.jsonl
1590327300
Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly $$$n$$$ shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.
256 megabytes
//package codeforces; //import codechef.HomeDelivery; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.StringTokenizer; public class BuyingShovels { public void printR(int a, int b) { List<Integer> factor = new LinkedList<>(); int k = a; int res = Integer.MAX_VALUE; if(b>=a) { System.out.println(1); } else { for (int i = 1; i*i <= a; i++) { if (a % i == 0 && i <= b) { res = Math.min(a/i, res); factor.add(i); if(a/i <= b) { res = Math.min(i, res); } } } System.out.println(res); } } public static void main(String []args) { FastReader sc = new FastReader(); BuyingShovels l = new BuyingShovels(); int n = sc.nextInt(); while (n > 0) { int i = sc.nextInt(); int b = sc.nextInt(); l.printR(i, b); n--; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733"]
2 seconds
["2\n8\n1\n999999733\n1"]
NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.
Java 8
standard input
[ "number theory", "math" ]
f00eb0452f5933103f1f77ef06473c6a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.
1,300
Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.
standard output
PASSED
735cb573bed67b28679940ca9237f732
train_002.jsonl
1590327300
Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly $$$n$$$ shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.
256 megabytes
import java.io.*; import java.util.Arrays; public class prog { public static void main(String[] args) throws IOException{ // TODO Auto-generated method stub BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(bf.readLine()); int flag=0; while(t>0) { String str1[] = bf.readLine().split(" "); long m = Long.parseLong(str1[0]); long n = Long.parseLong(str1[1]); long min = m; long sq = Sqrt(m)+1; for(int i=1;i<=sq;i++) { if(m%i==0 && (m/i)<=n) { System.out.println(i); flag=1; break; } if(m%i==0 && i<=n) { if(m/i < min) min = m/i; } } if(flag==0) { System.out.println(min); } flag=0; t--; } } public static long Sqrt(long x) { if (x==0 || x == 1) return x; long s = 1, e = x, a=0; while (s <= e) { long mid = (s + e)/2; if (mid*mid == x) return mid; if (mid*mid < x) { s = mid + 1; a = mid; } else e = mid-1; } return a; } }
Java
["5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733"]
2 seconds
["2\n8\n1\n999999733\n1"]
NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.
Java 8
standard input
[ "number theory", "math" ]
f00eb0452f5933103f1f77ef06473c6a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.
1,300
Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.
standard output
PASSED
576ff60ff9f87822dc21d430fd2d6a38
train_002.jsonl
1590327300
Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly $$$n$$$ shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.
256 megabytes
import java.io.*; import java.util.Arrays; public class prog { public static void main(String[] args) throws IOException{ // TODO Auto-generated method stub BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(bf.readLine()); int flag=0; int index = 0; int index2 = 0; long arr[][] = new long[3][t]; while(index<t) { String str1[] = bf.readLine().split(" "); long m = Long.parseLong(str1[0]); long n = Long.parseLong(str1[1]); for(int i = 0;i<arr[0].length;i++){ if(arr[0][i]==0){ index2 = i; break; } else if(arr[0][i]==m && arr[1][i]==n){ System.out.println(arr[2][i]); flag=1; break; } } if(flag==1){ flag=0; index++; continue; } long min = m; long sq = Sqrt(m)+1; for(int i=1;i<=sq;i++) { if(m%i==0 && (m/i)<=n) { System.out.println(i); arr[0][index2] = m; arr[1][index2] = n; arr[2][index2] = i; flag=1; break; } if(m%i==0 && i<=n) { if(m/i < min) min = m/i; } } if(flag==0) { arr[0][index2] = m; arr[1][index2] = n; arr[2][index2] = min; System.out.println(min); } flag=0; index++; } } public static long Sqrt(long x) { if (x==0 || x == 1) return x; long s = 1, e = x, a=0; while (s <= e) { long mid = (s + e)/2; if (mid*mid == x) return mid; if (mid*mid < x) { s = mid + 1; a = mid; } else e = mid-1; } return a; } }
Java
["5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733"]
2 seconds
["2\n8\n1\n999999733\n1"]
NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.
Java 8
standard input
[ "number theory", "math" ]
f00eb0452f5933103f1f77ef06473c6a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.
1,300
Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.
standard output
PASSED
9ac3d8ff99ab6e66fe54691af6a306a5
train_002.jsonl
1590327300
Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly $$$n$$$ shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.
256 megabytes
import java.util.Scanner; public class buying_shovels_codeforces { public static void main(String args[]){ int t,n,k; Scanner sc=new Scanner(System.in); t=sc.nextInt(); for(int i=1;i<=t;i++){ n=sc.nextInt(); k=sc.nextInt(); int ans=n; for(int j=1;j<=Math.sqrt(n);j++){ if(n%j==0){ if (j <= k) { ans = Math.min(ans, n / j); } if (n / j <= k) { ans = Math.min(ans, j); } } } System.out.println(ans); } } }
Java
["5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733"]
2 seconds
["2\n8\n1\n999999733\n1"]
NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.
Java 8
standard input
[ "number theory", "math" ]
f00eb0452f5933103f1f77ef06473c6a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.
1,300
Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.
standard output
PASSED
a8711807632ab0b27d847f7e81feeef4
train_002.jsonl
1590327300
Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly $$$n$$$ shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.
256 megabytes
import java.util.*; public class solution{ public static long function(long n,long k){ long ans=n; if(n<=k){ return 1; }else if(n%k==0){ ans=n/k; }else{ long end=(long)Math.sqrt(n); end=Math.min(end,k); for(long i=2;i<=end;i++){ if(n%i==0 && n/i<=k) ans=Math.min(ans,i); if(n%i==0 && i<=k) ans=Math.min(ans,n/i); // or Method-2 // if(n%i==0 && (n/i)<=k){ // ans=Math.min(ans,i); // } // if(n%i==0 ){ // ans=Math.min(ans,n/i); // } } } return ans; } public static void main(String[] args){ Scanner scn=new Scanner(System.in); int t=scn.nextInt(); long[] result=new long[t]; for(int i=0;i<t;i++){ long n=scn.nextLong(); long k=scn.nextLong(); result[i]=function(n,k); } for(int i=0;i<t;i++){ System.out.println(result[i]); } } }
Java
["5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733"]
2 seconds
["2\n8\n1\n999999733\n1"]
NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.
Java 8
standard input
[ "number theory", "math" ]
f00eb0452f5933103f1f77ef06473c6a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.
1,300
Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.
standard output
PASSED
6676132e80da2eb2f14f161c8ff9554c
train_002.jsonl
1590327300
Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly $$$n$$$ shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.
256 megabytes
import java.io.*; import java.util.Scanner; import java.util.*; import java.lang.*; public class buyingshovels { public static void main(String[] args) throws IOException { Scanner sc=new Scanner (System.in); int t; t=sc.nextInt(); sc.nextLine(); int i; int a[]=new int[t]; long maxm=0; for(i=0;i<t;i++) { int n=sc.nextInt(); int k=sc.nextInt(); sc.nextLine(); int c=0; maxm=0; if(n<=k) { a[i]=1; c=1; } else if(k==1) { a[i]=n; c=1; } else { for(int u=1;u*u<=n;u++) { if(n%u!=0) continue; long y=(long) n/u; if(u<=k) maxm=(long) Math.max(u,maxm); if(y<=k) maxm= (long)Math.max(y,maxm); } } if(c!=1) a[i]=(int) (n/maxm); } for(i=0;i<t;i++) { System.out.println(a[i]); } } }
Java
["5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733"]
2 seconds
["2\n8\n1\n999999733\n1"]
NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.
Java 8
standard input
[ "number theory", "math" ]
f00eb0452f5933103f1f77ef06473c6a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.
1,300
Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.
standard output
PASSED
959259d17dc3a125363ac30c4da550a5
train_002.jsonl
1590327300
Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly $$$n$$$ shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.
256 megabytes
import java.util.Scanner; public class Buying_Shovels { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); int t = scan.nextInt(); StringBuilder sb = new StringBuilder(); for(int i=0; i<t; i++) { int n = scan.nextInt(); int k = scan.nextInt(); int p = findPrime(n, k); sb.append(p); sb.append("\n"); } System.out.println(sb.toString()); } static int findPrime(int n, int k) { /* int bound = Math.min((int) Math.sqrt(n), k); if(k == 1) return n; if(k >= n) return 1; if(n % 2 == 0) { return 2; } else { for (int i = 3; i <= Math.sqrt(n); i+= 2) { if (n%i == 0 && n/i <= k) return i; } // sad n is prime return n; } */ if(n <= k) return 1; if(k == 1) return n; int trailer = 0; for(int i=2; i<=Math.sqrt(n); i++) { if(n % i == 0 && n/i <= k) { return i; } else if(n % i == 0 && n/i > k && i <=k) { trailer = n/i; } } if(trailer != 0 ) return trailer; // have to use 1! return n; /* if(n <= k) return 1; for(int i= n; i>Math.sq; i--) { if(n % i == 0 ) { return n/i; } } // have to use 1! return n; */ } }
Java
["5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733"]
2 seconds
["2\n8\n1\n999999733\n1"]
NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.
Java 8
standard input
[ "number theory", "math" ]
f00eb0452f5933103f1f77ef06473c6a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.
1,300
Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.
standard output
PASSED
e68f6750f5c659200ecb7a87a01d384a
train_002.jsonl
1590327300
Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly $$$n$$$ shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Random; import java.io.FileWriter; import java.io.PrintWriter; /* Solution Created: 15:24:13 29/07/2020 Custom Competitive programming helper. */ public class Main { public static void solve(Reader in, Writer out) { int t = in.nextInt(); while(t-->0) { int n = in.nextInt(), k = in.nextInt(); int maxDiv = 1; for(int i = 1; i*i<=n; i++) { if(n%i==0) { if(i<=k) maxDiv = Math.max(maxDiv, i); if(n/i<=k) maxDiv = Math.max(maxDiv, n/i); } } out.println(n/maxDiv); } } public static void main(String[] args) { Reader in = new Reader(); Writer out = new Writer(); solve(in, out); out.exit(); } static class Graph { private ArrayList<Integer> con[]; private boolean[] visited; public Graph(int n) { con = new ArrayList[n]; for (int i = 0; i < n; ++i) con[i] = new ArrayList(); visited = new boolean[n]; } public void reset() { Arrays.fill(visited, false); } public void addEdge(int v, int w) { con[v].add(w); } public void dfs(int cur) { visited[cur] = true; for (Integer v : con[cur]) { if (!visited[v]) { dfs(v); } } } public void bfs(int cur) { Queue<Integer> q = new LinkedList<>(); q.add(cur); visited[cur] = true; while (!q.isEmpty()) { cur = q.poll(); for (Integer v : con[cur]) { if (!visited[v]) { visited[v] = true; q.add(v); } } } } } static class Reader { static BufferedReader br; static StringTokenizer st; private int charIdx = 0; private String s; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public Reader(String f){ try { this.br = new BufferedReader(new FileReader(f)); } catch (IOException e) { e.printStackTrace(); } } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nd(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char nextChar() { if (s == null || charIdx >= s.length()) { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } s = st.nextToken(); charIdx = 0; } return s.charAt(charIdx++); } public long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[] nca() { return next().toCharArray(); } public String[] nS(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int nextInt() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Integer.parseInt(st.nextToken()); } public double nextDouble() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Double.parseDouble(st.nextToken()); } public Long nextLong() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Long.parseLong(st.nextToken()); } public String next() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return st.nextToken(); } public static void readLine() { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } } } static class Sort { static Random random = new Random(); public static void sortArray(int[] s) { shuffle(s); Arrays.sort(s); } public static void sortArray(long[] s) { shuffle(s); Arrays.sort(s); } public static void sortArray(String[] s) { shuffle(s); Arrays.sort(s); } public static void sortArray(char[] s) { shuffle(s); Arrays.sort(s); } private static void shuffle(int[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); int t = s[i]; s[i] = s[j]; s[j] = t; } } private static void shuffle(long[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); long t = s[i]; s[i] = s[j]; s[j] = t; } } private static void shuffle(String[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); String t = s[i]; s[i] = s[j]; s[j] = t; } } private static void shuffle(char[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); char t = s[i]; s[i] = s[j]; s[j] = t; } } } static class Util{ private static Random random = new Random(); static long[] fact; public static void initFactorial(int n, long mod) { fact = new long[n+1]; fact[0] = 1; for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod; } public static long modInverse(long a, long MOD) { long[] gcdE = gcdExtended(a, MOD); if (gcdE[0] != 1) return -1; // Inverted doesn't exist long x = gcdE[1]; return (x % MOD + MOD) % MOD; } public static long[] gcdExtended(long p, long q) { if (q == 0) return new long[] { p, 1, 0 }; long[] vals = gcdExtended(q, p % q); long tmp = vals[2]; vals[2] = vals[1] - (p / q) * vals[2]; vals[1] = tmp; return vals; } public static long nCr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nCr(int n, int r) { return (fact[n]/fact[r])/fact[n-r]; } public static long nPr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nPr(int n, int r) { return fact[n]/fact[n-r]; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static int lowerBound(int[] a, int v) { int l = 0, h = a.length; while(l<h) { int mid = (l+h)/2; if(v<=a[mid]) h = mid; else l = mid+1; } return l; } public static int lowerBound(long[] a, long v) { int l = 0, h = a.length; while(l<h) { int mid = (l+h)/2; if(v<=a[mid]) h = mid; else l = mid+1; } return l; } public static int upperBound(int[] a, int v) { int l = 0, h = a.length; while(l<h) { int mid = (l+h)/2; if(a[mid]<=v) l = mid+1; else h = mid; } return l; } public static int upperBound(long[] a, long v) { int l = 0, h = a.length; while(l<h) { int mid = (l+h)/2; if(a[mid]<=v) l = mid+1; else h = mid; } return l; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i*i <= n; i++) if (isPrime[i]) for (int j = i; i*j <= n; j++) isPrime[i*j] = false; return isPrime; } public static int gcd(int a, int b) { int tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static long gcd(long a, long b) { long tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static int random(int min, int max) { return random.nextInt(max-min+1)+min; } public static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } public static void reverse(int[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { int tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(int[] s) { reverse(s, 0, s.length-1); } public static void reverse(long[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { long tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(long[] s) { reverse(s, 0, s.length-1); } public static void reverse(float[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { float tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(float[] s) { reverse(s, 0, s.length-1); } public static void reverse(double[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { double tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(double[] s) { reverse(s, 0, s.length-1); } public static void reverse(char[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { char tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(char[] s) { reverse(s, 0, s.length-1); } public static <T> void reverse(T[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { T tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static <T> void reverse(T[] s) { reverse(s, 0, s.length-1); } public static void shuffle(int[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); int t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(long[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); long t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(float[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); float t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(double[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); double t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(char[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); char t = s[i]; s[i] = s[j]; s[j] = t; } } public static <T> void shuffle(T[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); T t = s[i]; s[i] = s[j]; s[j] = t; } } public static void sortArray(int[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(long[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(float[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(double[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(char[] a) { shuffle(a); Arrays.sort(a); } public static <T extends Comparable<T>> void sortArray(T[] a) { Arrays.sort(a); } } static class Writer { private PrintWriter pw; public Writer(){ pw = new PrintWriter(System.out); } public Writer(String f){ try { pw = new PrintWriter(new FileWriter(f)); } catch (IOException e) { e.printStackTrace(); } } public void printArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void printArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void print(Object o) { pw.print(o.toString()); } public void println(Object o) { pw.println(o.toString()); } public void println() { pw.println(); } public void flush() { pw.flush(); } public void exit() { pw.close(); } } }
Java
["5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733"]
2 seconds
["2\n8\n1\n999999733\n1"]
NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.
Java 8
standard input
[ "number theory", "math" ]
f00eb0452f5933103f1f77ef06473c6a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.
1,300
Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.
standard output
PASSED
95fe82533783aec2f86ac0fc827a1e2a
train_002.jsonl
1590327300
Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly $$$n$$$ shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { private static void solve(BufferedReader in) throws IOException { int n, k, ans; String[] tokens = in.readLine().split(" "); n = Integer.parseInt((tokens[0])); k = Integer.parseInt((tokens[1])); ans = n; for (int j = 1; j <= Math.sqrt(n); j++) { if (n%j==0 && n/j<=k) { ans = j; System.out.println(ans); return; } } for (int j = (int) Math.sqrt(n); j >= 1; j--) { if (n%j==0 && j<=k) { ans = n/j; System.out.println(ans); return; } } System.out.println(ans); } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); for (int i = 0; i < t; i++) { solve(in); } } }
Java
["5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733"]
2 seconds
["2\n8\n1\n999999733\n1"]
NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.
Java 8
standard input
[ "number theory", "math" ]
f00eb0452f5933103f1f77ef06473c6a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.
1,300
Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.
standard output
PASSED
2e7e6bae22f83b6178ce7039543b3788
train_002.jsonl
1590327300
Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly $$$n$$$ shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.
256 megabytes
import java.util.*; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); int k = sc.nextInt(); int ans = n; for(int j = 1; j*j <= n; j++){ if(n % j == 0){ if(j <= k){ ans = Math.min(ans, n/j); } if(n/j <= k){ ans = Math.min(ans, j); } } } System.out.println(ans); } } }
Java
["5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733"]
2 seconds
["2\n8\n1\n999999733\n1"]
NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.
Java 8
standard input
[ "number theory", "math" ]
f00eb0452f5933103f1f77ef06473c6a
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.
1,300
Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.
standard output
PASSED
e0594f505daae60fa9ca8ab4d5cb892b
train_002.jsonl
1439483400
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Bat-Orgil */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { static char[][] field; static int n; static int m; static int mod = 1000000007; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); m = in.nextInt(); field = new char[n + 1][m + 1]; for (int i = 1; i <= n; i++) { String s = in.next(); for (int j = 0; j < m; j++) { field[i][j + 1] = s.charAt(j); } } long[][][] dp = new long[2][501][501]; for (int x = 1; x <= n; x++) { for (int i = n; i >= 1; i--) { for (int j = m; j >= 1; j--) { int y = m - (i - 1 + j - 1 - (n - x)); long ans = 0; if (y <= 0 || y > m) { ans = 0; } else if (field[i][j] != field[x][y]) { ans = 0; } else if (i > x || j > y) { ans = 0; } else if (i == x && y == j) { ans = 1; } else if ((i == x && Math.abs(y - j) == 1) || (y == j && Math.abs(i - x) == 1)) { ans = 1; } else { if (i + 1 <= n) { ans += dp[x % 2][i + 1][j]; ans += dp[(x + 1) % 2][i + 1][j]; } if (j + 1 <= m) { ans += dp[x % 2][i][j + 1]; ans += dp[(x + 1) % 2][i][j + 1]; } ans = ans % mod; } dp[x % 2][i][j] = ans; } } } out.println(dp[n % 2][1][1]); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3 4\naaab\nbaaa\nabba"]
4 seconds
["3"]
NotePicture illustrating possibilities for the sample test.
Java 8
standard input
[ "dp", "combinatorics" ]
07fb2247b4b4ee5d3592fda21b814c7c
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field. Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
2,300
Print a single integer — the number of beautiful paths modulo 109 + 7.
standard output
PASSED
6aa8262e8a99985a0bea3355e034b7f9
train_002.jsonl
1439483400
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; public class CF_316_E { private static int n, m; private static final long MOD = 1000000007; private static char[][] map; private static long[][][] DP; private static long rec(int i1, int j1, int i2){ int j2 = (i1 + j1 - (n - 1 - i2) - (m - 1))*-1; if((i1 == i2 && j1 == j2) || (i1 + 1 == i2 && j1 == j2) || (i1 == i2 && j1 + 1 == j2))return 1L; if(DP[i1][j1][i2] != -1)return DP[i1][j1][i2]; long ans = 0; if(i1 + 1 < n && i2 - 1 >= 0 && map[i1 + 1][j1] == map[i2 - 1][j2]){ ans = (ans + rec(i1 + 1, j1, i2 - 1))%MOD; } if(i1 + 1 < n && j2 - 1 >= 0 && map[i1 + 1][j1] == map[i2][j2 - 1]){ ans = (ans + rec(i1 + 1, j1, i2))%MOD; } if(j1 + 1 < m && i2 - 1 >= 0 && map[i1][j1 + 1] == map[i2 - 1][j2]){ ans = (ans + rec(i1, j1 + 1, i2 - 1))%MOD; } if(j1 + 1 < m && j2 - 1 >= 0 && map[i1][j1 + 1] == map[i2][j2 - 1]){ ans = (ans + rec(i1, j1 + 1, i2))%MOD; } return DP[i1][j1][i2] = ans%MOD; } public static void main(String[] args) throws IOException{ PrintWriter pw = new PrintWriter(System.out, true); BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String[] line = input.readLine().split(" "); n = Integer.parseInt(line[0]); m = Integer.parseInt(line[1]); map = new char[n][m]; for(int i = 0; i < n; i++){ map[i] = input.readLine().toCharArray(); } if(map[0][0] == map[n - 1][m - 1]){ DP = new long[2][m][n]; //DP = new long[n][m][n]; // for(int i = 0; i < n; i++){ // for(int j = 0; j < m; j++){ // Arrays.fill(DP[i][j], -1); // } // } // pw.println(rec(0,0,n-1)); int max1 = (int)Math.ceil((((double)(m + n - 2)))/2); for(int i1 = Math.min(max1, n-1); i1 >= 0; i1--){ for(int j1 = Math.min(max1 - i1, m-1); j1 >= 0; j1--){ for(int i2 = 0; i2 <= n - 1; i2++){ int j2 = (i1 + j1 - (n - 1 - i2) - (m - 1))*-1; long ans = 0; if(j2 < 0 || j2 >= m){ ans = 0; }else if((i1 == i2 && j1 == j2) || (i1 + 1 == i2 && j1 == j2) || (i1 == i2 && j1 + 1 == j2)){ ans = 1L; }else{ if(i1 + 1 < n && i2 - 1 >= 0 && map[i1 + 1][j1] == map[i2 - 1][j2]){ ans = (ans + DP[((i1)&1)^1][j1][i2 - 1])%MOD; } if(i1 + 1 < n && j2 - 1 >= 0 && map[i1 + 1][j1] == map[i2][j2 - 1]){ ans = (ans + DP[((i1)&1)^1][j1][i2])%MOD; } if(j1 + 1 < m && i2 - 1 >= 0 && map[i1][j1 + 1] == map[i2 - 1][j2]){ ans = (ans + DP[i1&1][j1 + 1][i2 - 1])%MOD; } if(j1 + 1 < m && j2 - 1 >= 0 && map[i1][j1 + 1] == map[i2][j2 - 1]){ ans = (ans + DP[i1&1][j1 + 1][i2])%MOD; } } DP[i1&1][j1][i2] = ans%MOD; } } } pw.println(DP[0][0][n-1]); }else{ pw.println(0); } pw.close(); input.close(); } }
Java
["3 4\naaab\nbaaa\nabba"]
4 seconds
["3"]
NotePicture illustrating possibilities for the sample test.
Java 8
standard input
[ "dp", "combinatorics" ]
07fb2247b4b4ee5d3592fda21b814c7c
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field. Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
2,300
Print a single integer — the number of beautiful paths modulo 109 + 7.
standard output
PASSED
0601a009e982ae6b4a9e69b5dbaa095c
train_002.jsonl
1439483400
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static void main() throws Exception{ int n=sc.nextInt(),m=sc.nextInt(); char[][]in=new char[n][m]; for(int i=0;i<n;i++)in[i]=sc.nextLine().toCharArray(); int mod=(int)1e9+7; int pathLen=n+m-1; ArrayList<int[]>[]dist=new ArrayList[n+m]; for(int i=0;i<n+m;i++)dist[i]=new ArrayList<>(); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ dist[i+j].add(new int[] {i,j}); } } int upper=pathLen/2; int lower=(pathLen&1)==1?upper:upper-1; int memo[][]=new int[n][n]; //dp(lowerX,upperX,distanceFromStart) while(lower>=0) { int [][]nextMemo=new int[n][n]; for(int o=0;o<dist[lower].size();o++) { for(int z=0;z<dist[upper].size();z++) { int i=dist[lower].get(o)[0],j=dist[lower].get(o)[1],x=dist[upper].get(z)[0],y=dist[upper].get(z)[1]; if(i>x || j>y)continue; if(in[i][j]!=in[x][y])continue; int d=x-i+y-j; if(d<=1) { nextMemo[i][x]=1; } else { int ways=0; if(i+1<n && x-1>=0) ways+=memo[i+1][x-1]; if(i+1<n && y-1>=0) ways+=memo[i+1][x]; if(ways>=mod)ways-=mod; if(j+1<m && x-1>=0) ways+=memo[i][x-1]; if(ways>=mod)ways-=mod; if(j+1<m && y-1>=0) ways+=memo[i][x]; if(ways>=mod)ways-=mod; nextMemo[i][x]=ways; } } } lower--; upper++; memo=nextMemo; } pw.println(memo[0][n-1]); } public static void main(String[] args) throws Exception{ pw=new PrintWriter(System.out); sc = new MScanner(System.in); int tc=1; // tc=sc.nextInt(); while(tc-->0) main(); pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } }
Java
["3 4\naaab\nbaaa\nabba"]
4 seconds
["3"]
NotePicture illustrating possibilities for the sample test.
Java 8
standard input
[ "dp", "combinatorics" ]
07fb2247b4b4ee5d3592fda21b814c7c
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field. Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
2,300
Print a single integer — the number of beautiful paths modulo 109 + 7.
standard output
PASSED
c9f97c9d4e12f495430a53dd5af9d268
train_002.jsonl
1439483400
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class R316qE { public static void main(String args[]) { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); char s[][] = new char[n][m]; for(int i=0;i<n;i++) s[i] = in.readString().toCharArray(); int mod = (int)1e9 + 7; int dp[][][] = new int[n][n][2]; for(int steps=(n+m-2)/2;steps>=0;steps--){ for(int x=0;x<n;x++){ for(int y=0;y<n;y++){ int a = x; int b = steps - x; int c = n - 1 - y; int d = m - 1 - (steps - y); if(a < 0 || b < 0 || a >= n || b >= m) continue; if(c < 0 || d < 0 || c >= n || d >= m) continue; if(s[a][b] == s[c][d]){ if(steps == (n + m - 2)/2){ if(c >= a && d >= b && ((c - a) + (d - b)) <= 1) dp[x][y][0] = 1; else dp[x][y][0] = 0; } else{ dp[x][y][0] = 0; if(b + 1 < m && d - 1 >= 0)dp[x][y][0] += dp[x][y][1]; if(dp[x][y][0] >= mod) dp[x][y][0] -= mod; if(b + 1 < m && c - 1 >= 0)dp[x][y][0] += dp[x][y+1][1]; if(dp[x][y][0] >= mod) dp[x][y][0] -= mod; if(a + 1 < n && d - 1 >= 0)dp[x][y][0] += dp[x+1][y][1]; if(dp[x][y][0] >= mod) dp[x][y][0] -= mod; if(a + 1 < n && c - 1 >= 0)dp[x][y][0] += dp[x+1][y+1][1]; if(dp[x][y][0] >= mod) dp[x][y][0] -= mod; } } } } for(int x=0;x<n;x++){ for(int y=0;y<n;y++){ dp[x][y][1] = dp[x][y][0]; dp[x][y][0] = 0; } } } w.println(dp[0][0][1]); w.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); } } }
Java
["3 4\naaab\nbaaa\nabba"]
4 seconds
["3"]
NotePicture illustrating possibilities for the sample test.
Java 8
standard input
[ "dp", "combinatorics" ]
07fb2247b4b4ee5d3592fda21b814c7c
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field. Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
2,300
Print a single integer — the number of beautiful paths modulo 109 + 7.
standard output
PASSED
c41876bdf31d087de8ed31054b79f018
train_002.jsonl
1439483400
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.text.*; public class Main { //private static long startTime = System.currentTimeMillis(); static int n,m,mod=1000000007,diag_one_start,diag_two_start,diag_one_x,diag_one_y,diag_two_x,diag_two_y,offset1=1000000,offset2=1000; static int[][] grid; static int[][][] dp; public static void compute_DP_Table1(int loop) { int x1,y1,x2,y2,key,val=0,cur; for(int l=1;l<loop;l++) { for(x1=diag_one_x,y1=diag_one_y;x1<m && y1>=0;x1++,y1--) { for(x2=diag_two_x,y2=diag_two_y;x2<m && y2>=0;x2++,y2--) { if(x2<x1 || y2<y1) continue; val=dp[x1][x2][0]; if(x1-1>=0 && x2+1<m) { if(grid[y1][x1-1]==grid[y2][x2+1]) { dp[x1-1][x2+1][1]+=val; if(dp[x1-1][x2+1][1]>=mod) dp[x1-1][x2+1][1]-=mod; } } if(x1-1>=0 && y2+1<n) { if(grid[y1][x1-1]==grid[y2+1][x2]) { dp[x1-1][x2][1]+=val; if(dp[x1-1][x2][1]>=mod) dp[x1-1][x2][1]-=mod; } } if(y1-1>=0 && x2+1<m) { if(grid[y1-1][x1]==grid[y2][x2+1]) { dp[x1][x2+1][1]+=val; if(dp[x1][x2+1][1]>=mod) dp[x1][x2+1][1]-=mod; } } if(y1-1>=0 && y2+1<n) { if(grid[y1-1][x1]==grid[y2+1][x2]) { dp[x1][x2][1]+=val; if(dp[x1][x2][1]>=mod) dp[x1][x2][1]-=mod; } } } } diag_one_start--; diag_two_start++; if(diag_one_start<=n) { diag_one_x=0; diag_one_y=diag_one_start-1; } else { diag_one_x=diag_one_start-n; diag_one_y=n-1; } if(diag_two_start<=n) { diag_two_x=0; diag_two_y=diag_two_start-1; } else { diag_two_x=diag_two_start-n; diag_two_y=n-1; } for(x1=diag_one_x,y1=diag_one_y;x1<m && y1>=0;x1++,y1--) { for(x2=diag_two_x,y2=diag_two_y;x2<m && y2>=0;x2++,y2--) { dp[x1][x2][0]=dp[x1][x2][1]; dp[x1][x2][1]=0; } } } } public static void determine_Diagonal_Startings() { int total=n+m-1; if(total%2==0) { diag_one_start=(total+1)/2; diag_two_start=diag_one_start+1; } else { diag_one_start=(total+1)/2; diag_two_start=diag_one_start; } if(diag_one_start<=n) { diag_one_x=0; diag_one_y=diag_one_start-1; } else { diag_one_x=diag_one_start-n; diag_one_y=n-1; } if(diag_two_start<=n) { diag_two_x=0; diag_two_y=diag_two_start-1; } else { diag_two_x=diag_two_start-n; diag_two_y=n-1; } } @SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { //BufferedReader in = new BufferedReader(new FileReader(".\\mmk\\input.txt")); //PrintWriter out=new PrintWriter("output.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int i,j,x1,y1,x2,y2,dist1,dist2,dist,key,ans; String str=in.readLine().trim(); String[] token=str.split(" "); n=Integer.parseInt(token[0]); m=Integer.parseInt(token[1]); grid=new int[n][m]; dp=new int[m][m][2]; for(i=0;i<n;i++) { str=in.readLine().trim(); for(j=0;j<m;j++) { grid[i][j]=(int)str.charAt(j)-96; } } diag_one_start=-1; diag_two_start=-1; determine_Diagonal_Startings(); for(x1=diag_one_x,y1=diag_one_y;x1<m && y1>=0;x1++,y1--) { for(x2=0;x2<m;x2++) { dist1=x1+y1; dist2=dist1; y2=(n-1)-dist2+(m-1-x2); if( (y2>=0 && y2<n)) { if(x1<=x2 && y1<=y2) { dist=x2-x1+y2-y1; if(dist<=1) { if(grid[y1][x1]==grid[y2][x2]) { dp[x1][x2][0]=1; } } } } } } compute_DP_Table1(diag_one_start); System.out.println(dp[0][m-1][0]); // At the end //long endTime = System.currentTimeMillis(); //System.out.println("\n\nIt took " + (endTime - startTime) + " milliseconds"); out.flush(); out.close(); } }
Java
["3 4\naaab\nbaaa\nabba"]
4 seconds
["3"]
NotePicture illustrating possibilities for the sample test.
Java 8
standard input
[ "dp", "combinatorics" ]
07fb2247b4b4ee5d3592fda21b814c7c
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field. Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
2,300
Print a single integer — the number of beautiful paths modulo 109 + 7.
standard output
PASSED
28fca778d046413dc015baa9a217e433
train_002.jsonl
1439483400
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.
256 megabytes
import java.util.*; import java.io.*; public class PigPalindrome { static int [][][] dp = new int [2][510][510]; static char [][] a = new char [510][510]; static int mod = 1000000007; public static void main (String[] args) { Reader in = new Reader (); int n = in.nextInt(); int m = in.nextInt(); for(int i = 0; i < n; i++) { String s = in.next(); for(int j = 0; j < m; j++) { a[i][j] = s.charAt(j); } } if(a[0][0] != a[n-1][m-1]) { System.out.println (0); System.exit(0); } int [] lx = {1, 0}; int [] ly = {0, 1}; int [] rx = {-1, 0}; int [] ry = {0, -1}; int mid; if((n + m - 1) % 2 == 0) { mid = (n + m - 1) / 2; mid -= 1; } else { mid = (n + m - 1) / 2; } dp[0][0][n-1] = 1; for(int i = 0; i < mid; i++) { int cur = i % 2; int nxt = cur ^ 1; for(int x1 = 0; x1 < n; x1++) { for(int x2 = 0; x2 < n; x2++) { dp[nxt][x1][x2] = 0; } } for(int x1 = 0; x1 < n; x1++) { int y1 = i - x1; if(0 > y1 || y1 >= m) continue; for(int x2 = 0; x2 < n; x2++) { int y2 = (m - 1) - (i - (n - 1 - x2)); if(0 > y2 || y2 >= m) continue; // System.out.printf("%d %d %d %d %d = %d\n", i, x1, y1, x2, y2, dp[cur][x1][x2]); for(int p = 0; p < 2; p++) { for(int q = 0; q < 2; q++) { int nx1 = x1 + lx[p]; int ny1 = y1 + ly[p]; int nx2 = x2 + rx[q]; int ny2 = y2 + ry[q]; // System.out.printf("%d %d %d %d\n", nx1, ny1, nx2, ny2); if(nx1 <= nx2 && ny1 <= ny2) {} else continue; if(0 <= nx1 && nx1 < n && 0 <= ny1 && ny1 < m) {} else continue; if(0 <= nx2 && nx2 < n && 0 <= ny2 && ny2 < m) {} else continue; if(a[nx1][ny1] == a[nx2][ny2]) { dp[nxt][nx1][nx2] += dp[cur][x1][x2]; dp[nxt][nx1][nx2] %= mod; } } } } } } int ans = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { ans += dp[mid % 2][i][j]; ans %= mod; } } System.out.println (ans); } static class Reader { private BufferedReader a; private StringTokenizer b; Reader() { a = new BufferedReader (new InputStreamReader (System.in)); } public String next () { while(b == null || !b.hasMoreTokens()) { try { b = new StringTokenizer (a.readLine()); } catch (IOException e) { e.printStackTrace(); } } return b.nextToken(); } public int nextInt () { return Integer.parseInt(next()); } public long nextLong () { return Long.parseLong(next()); } public double nextDouble () { return Double.parseDouble(next()); } public String nextLine () { try { return a.readLine(); } catch (IOException e) { e.printStackTrace (); } return "##"; } } static class Pair <P, Q> { P first; Q second; Pair () {} Pair (P first, Q second) { this.first = first; this.second = second; } } }
Java
["3 4\naaab\nbaaa\nabba"]
4 seconds
["3"]
NotePicture illustrating possibilities for the sample test.
Java 8
standard input
[ "dp", "combinatorics" ]
07fb2247b4b4ee5d3592fda21b814c7c
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field. Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
2,300
Print a single integer — the number of beautiful paths modulo 109 + 7.
standard output
PASSED
afb808a7e225384267efb987f80a2a30
train_002.jsonl
1439483400
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; /** * Created by ringod on 10/21/15. */ public class Task { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pr = new PrintWriter(System.out); Dp solver = new Dp(); solver.readTable(sc); solver.doIt(); solver.printAnswer(pr); } } class Dp { public final int N = 502; public final int Mod = 1000 * 1000 * 1000 + 7; public int n, m; public long result; public String [] s = new String [N]; public long[][][] tab = new long[2][N][N]; public Dp() {} public void readTable(Scanner sc) { n = sc.nextInt(); m = sc.nextInt(); for (int i = 0; i < n; ++i) { s[i] = sc.next(); } } public void doIt() { int maxLen = (n + m) / 2 + 1; tab[0][1][n] = 1; for (int len = 2; len <= maxLen; ++len) { int base = n + m - len + 2; for (int r1 = 1; r1 <= n; ++r1) { for (int r2 = r1; r2 <= n; ++r2) { int c1 = len - r1, c2 = base - r2; if(c2 < 1 || c2 > m || c1 < 1 || c1 > m || c1 > c2) { continue; } if (s[r1 - 1].charAt(c1 - 1) != s[r2 - 1].charAt(c2 - 1)) { tab[1][r1][r2] = 0; } else { tab[1][r1][r2] = ( tab[0][r1 - 1][r2 + 1] + tab[0][r1 - 1][r2] + tab[0][r1][r2 + 1] + tab[0][r1][r2]) % Mod; } } } for (int i = 1; i <= n; ++i) { System.arraycopy(tab[1][i], 0, tab[0][i], 0, n + 1); Arrays.fill(tab[1][i], 0); } } result = 0; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { result = (result + tab[0][i][j]) % Mod; } } } public void printAnswer(PrintWriter pr) { pr.print(result); pr.flush(); } }
Java
["3 4\naaab\nbaaa\nabba"]
4 seconds
["3"]
NotePicture illustrating possibilities for the sample test.
Java 8
standard input
[ "dp", "combinatorics" ]
07fb2247b4b4ee5d3592fda21b814c7c
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field. Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
2,300
Print a single integer — the number of beautiful paths modulo 109 + 7.
standard output
PASSED
fe4f35713ace827ff27805e0dde44744
train_002.jsonl
1439483400
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.
256 megabytes
import java.util.*; import java.io.*; public class CF570E { static final int MOD = (int) 1e9 + 7; static int[] d1 = {1, 0, 1, 0}; static int[] d2 = {0, 1, 0, 1}; static int[] d3 = {-1, -1, 0, 0}; static int[] d4 = {0, 0, -1, -1}; static int r, c, halfLength; static char[][] grid; public static void main(String[] args) { Scanner scan = new Scanner(System.in); r = scan.nextInt(); c = scan.nextInt(); grid = new char[r][c]; for(int i = 0 ; i < r ; i++) grid[i] = scan.next().toCharArray(); halfLength = (r + c - 1) / 2; int[][][] dp = new int[2][r][r]; int d = 0; for(int i = 0 ; i < r ; i++) { for(int j = 0 ; j < r ; j++) { int r1 = i, c1 = halfLength - i - 1; int r2 = j, c2 = c - (halfLength - (r - j)) - 1; if(inbounds(r1, c1) && inbounds(r2, c2) && grid[r1][c1] == grid[r2][c2]) dp[d][i][j] = baseCase(r1, c1, r2, c2); } } for(int k = halfLength - 1 ; k > 0 ; k--) { d ^= 1; // flip for(int i = 0 ; i < r ; i++) { for(int j = 0 ; j < r ; j++) { int r1 = i, c1 = k - i - 1; int r2 = j, c2 = c - (k - (r - j)) - 1; if(inbounds(r1, c1) && inbounds(r2, c2)) { int res = 0; for(int l = 0 ; l < 4 ; l++) { int dr1 = r1 + d1[l], dc1 = c1 + d2[l]; int dr2 = r2 + d3[l], dc2 = c2 + d4[l]; if(inbounds(dr1, dc1) && inbounds(dr2, dc2) && grid[dr1][dc1] == grid[dr2][dc2]) { res = (res + dp[d ^ 1][dr1][dr2]) % MOD; } } dp[d][r1][r2] = res; } } } } if(grid[0][0] != grid[r - 1][c - 1]) System.out.println(0); else System.out.println(dp[d][0][r - 1]); } static boolean inbounds(int row, int col) { return 0 <= row && row < r && 0 <= col && col < c; } static int baseCase(int r1, int c1, int r2, int c2) { if((r + c) % 2 == 0) { if(r1 + 1 == r2 && c1 + 1 == c2) return 2; if(r1 == r2 && Math.abs(c1 - c2) == 2) return 1; if(c1 == c2 && Math.abs(r1 - r2) == 2) return 1; return 0; } else { if(c1 == c2 && Math.abs(r1 - r2) == 1) return 1; if(r1 == r2 && Math.abs(c1 - c2) == 1) return 1; return 0; } } } /* */
Java
["3 4\naaab\nbaaa\nabba"]
4 seconds
["3"]
NotePicture illustrating possibilities for the sample test.
Java 8
standard input
[ "dp", "combinatorics" ]
07fb2247b4b4ee5d3592fda21b814c7c
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field. Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
2,300
Print a single integer — the number of beautiful paths modulo 109 + 7.
standard output
PASSED
b27274950272ac57c84af78e69e6edbf
train_002.jsonl
1439483400
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.
256 megabytes
import java.util.*; import java.io.*; public class R316D2_E { public static PrintWriter outWriter; public static MyScanner sc; public static Long MOD = 1000000007L; public static void main(String[] args) { sc = new MyScanner(); outWriter = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int m = sc.nextInt(); String[] p = new String[n]; for(int i = 0;i < n;i++) { p[i] = sc.nextLine(); } int midDist = (n + m - 2) / 2; long[][][] dp = new long[2][n + 2][n + 2]; if(p[0].charAt(0) == p[n - 1].charAt(m - 1)) { dp[0][1][n] = 1L; } long ans = 0L; int curr = 0; for(int dist = 1; dist <= midDist; dist++) { for(int x1 = 1; x1 <= n; x1++) { for(int x2 = 1; x2 <= n; x2++) { int y1 = dist + 2 - x1; int y2 = n + m - x2 - dist; if(y1 > 0 && y1 <= m && y2 > 0 && y2 <= m && y1 <= y2 && x1 <= x2 && p[x1 - 1].charAt(y1 - 1) == p[x2 - 1].charAt(y2 - 1)) { dp[1 - curr][x1][x2] = madd(dp[curr][x1 - 1][x2], madd(dp[curr][x1 - 1][x2 + 1], madd(dp[curr][x1][x2], dp[curr][x1][x2 + 1]))); } else { dp[1 - curr][x1][x2] = 0l; } } } curr = 1 - curr; } for(int x1 = 1; x1 <= n; x1++) { for(int x2 = 1; x2 <= n; x2++) { if(dp[curr][x1][x2] > 0) { ans = madd(ans, dp[curr][x1][x2]); } } } /*for(int dist = 0; dist <= (n + m - 2) / 2; dist++) { for(int x1 = 0; x1 <= n; x1++) { for(int x2 = 0; x2 <= n; x2++) { System.out.println(dist + "," + x1 + "," + x2 + ": " + dp[dist][x1][x2]); } } System.out.println(); }*/ outWriter.write("" + ans); outWriter.close(); } static long madd(long a, long b) { return (long)(a + b) % MOD; } static boolean areAdj(int i, int j, int k, int l) { return ((i + 1) == k && j == l) || (i == k && (j + 1) == l); } static boolean areSame(int i, int j, int k, int l) { return i == k && j == l; } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); outWriter = new PrintWriter(new BufferedOutputStream(System.out)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3 4\naaab\nbaaa\nabba"]
4 seconds
["3"]
NotePicture illustrating possibilities for the sample test.
Java 8
standard input
[ "dp", "combinatorics" ]
07fb2247b4b4ee5d3592fda21b814c7c
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field. Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
2,300
Print a single integer — the number of beautiful paths modulo 109 + 7.
standard output
PASSED
93ed115777a5c28a668b5e73cfdba625
train_002.jsonl
1439483400
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.
256 megabytes
import java.util.*; import java.io.*; public class R316D2_E { public static PrintWriter outWriter; public static MyScanner sc; public static Long MOD = 1000000007L; public static void main(String[] args) { sc = new MyScanner(); outWriter = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int m = sc.nextInt(); String[] p = new String[n]; for(int i = 0;i < n;i++) { p[i] = sc.nextLine(); } int midDist = (n + m - 2) / 2; long[][][] dp = new long[2][n + 2][n + 2]; if(p[0].charAt(0) == p[n - 1].charAt(m - 1)) { dp[0][1][n] = 1L; } long ans = 0L; int curr = 0; for(int dist = 1; dist <= midDist; dist++) { for(int x1 = 1; x1 <= n; x1++) { for(int x2 = 1; x2 <= n; x2++) { int y1 = dist + 2 - x1; int y2 = n + m - x2 - dist; if(y1 > 0 && y1 <= m && y2 > 0 && y2 <= m && y1 <= y2 && x1 <= x2 && p[x1 - 1].charAt(y1 - 1) == p[x2 - 1].charAt(y2 - 1)) { dp[1 - curr][x1][x2] = madd(dp[curr][x1 - 1][x2], madd(dp[curr][x1 - 1][x2 + 1], madd(dp[curr][x1][x2], dp[curr][x1][x2 + 1]))); } else { dp[1 - curr][x1][x2] = 0l; } } } curr = 1 - curr; } for(int x1 = 1; x1 <= n; x1++) { for(int x2 = 1; x2 <= n; x2++) { if(dp[curr][x1][x2] > 0) { ans = madd(ans, dp[curr][x1][x2]); } } } outWriter.write("" + ans); outWriter.close(); } static long madd(long a, long b) { return (long)(a + b) % MOD; } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); outWriter = new PrintWriter(new BufferedOutputStream(System.out)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3 4\naaab\nbaaa\nabba"]
4 seconds
["3"]
NotePicture illustrating possibilities for the sample test.
Java 8
standard input
[ "dp", "combinatorics" ]
07fb2247b4b4ee5d3592fda21b814c7c
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field. Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
2,300
Print a single integer — the number of beautiful paths modulo 109 + 7.
standard output
PASSED
0b51fd3ec7b48aab706a6708a89f4ff8
train_002.jsonl
1439483400
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.
256 megabytes
//package codeforcesround316; import java.io.*; import java.util.*; public class pigandpalindrome { public static void main(String[] args) throws Exception { //BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //PrintWriter pw=new PrintWriter(System.out); //StringTokenizer st=new StringTokenizer(br.readLine()); InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); int mod=(int)(1e9+7); int n=in.readInt(); int m=in.readInt(); char[][] arr=new char[n][m]; for(int i=0;i<n;i++) { arr[i]=in.readString().toCharArray(); } int[][][] dp=new int[2][501][501]; for(int x=n-1;x>=0;x--) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { int y=(n-1-i+m-1-j)-x; int ans=0; if(y<0 ||y>=m) { ans=0; } else if(arr[x][y]!=arr[i][j]) { ans=0; } else if(x>i || y>j) { ans=0; } else if(i==x && y==j) { ans=1; } else if((i==x && Math.abs(y-j)==1 ) || (y==j && Math.abs(i-x)==1)) { ans=1; } else { if(i-1>=0) { ans+=dp[x%2][i-1][j]; if(ans>=mod) { ans-=mod; } ans+=dp[(x+1)%2][i-1][j]; if(ans>=mod) { ans-=mod; } } if(j-1>=0) { ans+=dp[x%2][i][j-1]; if(ans>=mod) { ans-=mod; } ans+=dp[(x+1)%2][i][j-1]; if(ans>=mod) { ans-=mod; } } } dp[x%2][i][j]=ans; } } } System.out.println(dp[0][n-1][m-1]); } } 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(char[] array) { writer.println(array); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } 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 String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["3 4\naaab\nbaaa\nabba"]
4 seconds
["3"]
NotePicture illustrating possibilities for the sample test.
Java 8
standard input
[ "dp", "combinatorics" ]
07fb2247b4b4ee5d3592fda21b814c7c
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field. Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
2,300
Print a single integer — the number of beautiful paths modulo 109 + 7.
standard output
PASSED
eac09403ab9967c7c77ba685de556a54
train_002.jsonl
1439483400
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.
256 megabytes
//package codeforcesround316; import java.io.*; import java.util.*; public class pigandpalindrome { public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(System.out); StringTokenizer st=new StringTokenizer(br.readLine()); int mod=(int)(1e9+7); int n=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); char[][] arr=new char[n][m]; for(int i=0;i<n;i++) { arr[i]=br.readLine().toCharArray(); } long[][][] dp=new long[2][501][501]; for(int x=n-1;x>=0;x--) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { int y=(n-1-i+m-1-j)-x; long ans=0; if(y<0 ||y>=m) { ans=0; } else if(arr[x][y]!=arr[i][j]) { ans=0; } else if(x>i || y>j) { ans=0; } else if(i==x && y==j) { ans=1; } else if((i==x && Math.abs(y-j)==1 ) || (y==j && Math.abs(i-x)==1)) { ans=1; } else { if(i-1>=0) { ans+=dp[x%2][i-1][j]%mod; ans+=dp[(x+1)%2][i-1][j]%mod; } if(j-1>=0) { ans+=dp[x%2][i][j-1]%mod; ans+=dp[(x+1)%2][i][j-1]%mod; } } dp[x%2][i][j]=ans%mod; } } } System.out.println(dp[0][n-1][m-1]); } }
Java
["3 4\naaab\nbaaa\nabba"]
4 seconds
["3"]
NotePicture illustrating possibilities for the sample test.
Java 8
standard input
[ "dp", "combinatorics" ]
07fb2247b4b4ee5d3592fda21b814c7c
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field. Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
2,300
Print a single integer — the number of beautiful paths modulo 109 + 7.
standard output
PASSED
c0bfd821619b1dfa10bce9f20233d144
train_002.jsonl
1439483400
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.
256 megabytes
/** * Created by Aminul on 11/21/2018. */ import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.Arrays; import java.util.InputMismatchException; public class CF570E_3 { public static void main(String[] args)throws Exception { FastReader in = new FastReader(System.in); PrintWriter pw = new PrintWriter(System.out); n = in.nextInt(); m = in.nextInt(); map = new int[n][n]; int cnt = 0; for (int i = 0; i < n; i++) { for(int j = i; j < n; j++) { map[i][j] = cnt++; } } dp = new int[m][cnt]; for(int d[] : dp) Arrays.fill(d, -1); s = new char[n][]; for (int i = 0; i < n; i++) { s[i] = in.next().toCharArray(); //Arrays.fill(s[i], 'a'); } int ans = solve(0, 0, n-1, m-1); pw.println(ans); pw.close(); } static char s[][]; static int dp[][], map[][]; static int n, m, mod = (int)1e9+7; static boolean isValid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } static int solve(int r1, int c1, int r2, int c2) { if(!isValid(r1, c1) || !isValid(r2, c2)) return 0; if(s[r1][c1] != s[r2][c2]) return 0; if(r1 > r2 || c1 > c2) return 0; if((r2 - r1 + c2 - c1) <= 1) return 1; if(dp[c1][map[r1][r2]] != -1) return dp[c1][map[r1][r2]]; int ans = 0; ans = (ans + solve(r1 + 1, c1, r2 - 1, c2)) % mod; ans = (ans + solve(r1 + 1, c1, r2, c2 - 1)) % mod; ans = (ans + solve(r1, c1 + 1, r2 - 1, c2)) % mod; ans = (ans + solve(r1, c1 + 1, r2, c2 - 1)) % mod; return dp[c1][map[r1][r2]] = ans; } static void debug(Object...obj) { System.err.println(Arrays.deepToString(obj)); } static class FastReader { InputStream is; private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; public FastReader(InputStream is) { this.is = is; } public 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++]; } public boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } public String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public String nextLine() { int c = skip(); StringBuilder sb = new StringBuilder(); while (!isEndOfLine(c)){ sb.appendCodePoint(c); c = readByte(); } return sb.toString(); } public 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 << 3) + (num << 1) + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public 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 << 3) + (num << 1) + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public double nextDouble() { return Double.parseDouble(next()); } public 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); } public char readChar() { return (char) skip(); } } }
Java
["3 4\naaab\nbaaa\nabba"]
4 seconds
["3"]
NotePicture illustrating possibilities for the sample test.
Java 8
standard input
[ "dp", "combinatorics" ]
07fb2247b4b4ee5d3592fda21b814c7c
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field. Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
2,300
Print a single integer — the number of beautiful paths modulo 109 + 7.
standard output
PASSED
b9ca58456edb361cb19246892f7d5f9f
train_002.jsonl
1361719800
A little girl loves problems on trees very much. Here's one of them.A tree is an undirected connected graph, not containing cycles. The degree of node x in the tree is the number of nodes y of the tree, such that each of them is connected with node x by some edge of the tree. Let's consider a tree that consists of n nodes. We'll consider the tree's nodes indexed from 1 to n. The cosidered tree has the following property: each node except for node number 1 has the degree of at most 2.Initially, each node of the tree contains number 0. Your task is to quickly process the requests of two types: Request of form: 0 v x d. In reply to the request you should add x to all numbers that are written in the nodes that are located at the distance of at most d from node v. The distance between two nodes is the number of edges on the shortest path between them. Request of form: 1 v. In reply to the request you should print the current number that is written in node v.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static public class SegmentTree { // 1-based DS, OOP int N; int[] array, lazy; SegmentTree(int n) { N=n; array = new int[N+1]; lazy = new int[N<<2]; } void update_range(int i, int j, int val) // O(log n) { update_range(1,1,N,i,j,val); } void update_range(int node, int b, int e, int i, int j, int val) { if(i > e || j < b) return; if(b >= i && e <= j) { lazy[node] += val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node<<1,b,mid,i,j,val); update_range(node<<1|1,mid+1,e,i,j,val); } } void propagate(int node, int b, int mid, int e) { lazy[node<<1] += lazy[node]; lazy[node<<1|1] += lazy[node]; lazy[node] = 0; } int query_point(int i) { return query_point(1,1,N,i); } int query_point(int node, int b, int e, int i) // O(log n) { if(b == i && e == i) return lazy[node]+array[b]; int mid = b + e >> 1; propagate(node, b, mid, e); if(i<=mid) { return query_point(node<<1,b,mid,i); } return query_point(node<<1|1,mid+1,e,i); } } static LinkedList<Integer>[]adj; static int[]treeOf,depth; static int dfs(int i,int p,int dep,int idx) { depth[i]=dep; treeOf[i]=idx; for(int j:adj[i]) { if(j==p)continue; return 1+dfs(j, i, dep+1,idx); } return 1; } static void main() throws Exception{ int n=sc.nextInt(),q=sc.nextInt(); adj=new LinkedList[n]; for(int i=0;i<n;i++)adj[i]=new LinkedList<>(); treeOf=new int[n]; depth=new int[n]; for(int i=0;i<n-1;i++) { int x=sc.nextInt()-1,y=sc.nextInt()-1; adj[x].add(y); adj[y].add(x); } SegmentTree[]trees=new SegmentTree[adj[0].size()+1]; int idx=1; int maxDepth=0; int[]sub=new int[n]; for(int i:adj[0]) { int size=dfs(i, 0, 1, idx); sub[idx]=size; trees[idx++]=new SegmentTree(size); maxDepth=Math.max(maxDepth, size); } trees[0]=new SegmentTree(maxDepth+1); while(q-->0) { if(sc.nextInt()==0) { int v=sc.nextInt()-1,x=sc.nextInt(),d=sc.nextInt(); if(v==0) { trees[0].update_range(1, d+1, x); continue; } int cur=depth[v],tree=treeOf[v]; int left=cur-d,right=Math.min(cur+d, sub[tree]); int extra=-1; if(left<1) { extra=-left; left=1; } trees[tree].update_range(left, right, x); if(extra!=-1) { trees[0].update_range(1, 1+extra, x); if(extra>0) { trees[tree].update_range(1, extra, -x); } } } else { int v=sc.nextInt()-1; int tree=treeOf[v]; if(v==0) { pw.println(trees[0].query_point(1)); continue; } pw.println(trees[tree].query_point(depth[v])+trees[0].query_point(depth[v]+1)); } } } public static void main(String[] args) throws Exception{ pw=new PrintWriter(System.out); sc = new MScanner(System.in); int tc=1; while(tc-->0)main(); pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } }
Java
["3 6\n1 2\n1 3\n0 3 1 2\n0 2 3 1\n0 1 5 2\n1 1\n1 2\n1 3", "6 11\n1 2\n2 5\n5 4\n1 6\n1 3\n0 3 1 3\n0 3 4 5\n0 2 1 4\n0 1 5 5\n0 4 6 2\n1 1\n1 2\n1 3\n1 4\n1 5\n1 6"]
2 seconds
["9\n9\n6", "11\n17\n11\n16\n17\n11"]
null
Java 11
standard input
[ "data structures", "trees", "graphs" ]
2399ea65e035a8bcd082342b9a6cc89d
The first line contains integers n (2 ≤ n ≤ 105) and q (1 ≤ q ≤ 105) — the number of tree nodes and the number of requests, correspondingly. Each of the next n  -  1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that show that there is an edge between nodes ui and vi. Each edge's description occurs in the input exactly once. It is guaranteed that the given graph is a tree that has the property that is described in the statement. Next q lines describe the requests. The request to add has the following format: 0 v x d (1 ≤ v ≤ n, 1 ≤ x ≤ 104, 1 ≤ d &lt; n). The request to print the node value has the following format: 1 v (1 ≤ v ≤ n). The numbers in the lines are separated by single spaces.
2,100
For each request to print the node value print an integer — the reply to the request.
standard output
PASSED
cf0bf86e7b69cf3520bd8cf413742304
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.lang.reflect.Array; import java.math.*; import java.nio.file.Path; import java.util.stream.Collectors; import javafx.util.Pair; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; public class JavaApplication1 { static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); static StringBuilder out = new StringBuilder(); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static int I(String s) { return Integer.parseInt(s); } static long L(String s) { return Long.parseLong(s); } static double D(String s) { return Double.parseDouble(s); } public static void main(String[] args) throws IOException { int n = I(bf.readLine()); ArrayList<Pair<Integer, Integer>> al = new ArrayList(); StringTokenizer in = new StringTokenizer(""); for (int i = 0; i < n; i++) { in = new StringTokenizer(bf.readLine()); int x = I((String) in.nextElement()); int y = I((String) in.nextElement()); al.add(new Pair<>(x, y )); } int count = 2; long prev=al.get(n-1).getKey(); for (int i = n - 2; i >= 1;i--) { long k=al.get(i).getKey(); long v=al.get(i).getValue(); if ((k+v) < prev) { count++; prev=(long)k; // System.err.println("i"+i); } else if ((k-v)>al.get(i-1).getKey()) { count++; prev=(long)k-(long)v; // System.err.println("ii"+i); }else{prev=(long)al.get(i).getKey();//System.err.println("iii"+i); } } if(n==1){count=1;} System.out.println(count); } } //:
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
d0553bff3fb59cf0bf5e5b0247fa590f
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
//package DynamicProgramming; import java.util.Scanner; public class M545C { public static Scanner enter = new Scanner(System.in); public static void main(String[] args) { int n=enter.nextInt(); long lastpoint=Integer.MIN_VALUE; int kolvo=0; int wanted=0; long lastmb=Integer.MIN_VALUE; for (int i = 0; i < n; i++) { long point=enter.nextLong(); long height=enter.nextLong(); if(wanted==1){ if(lastmb<point){ kolvo++; lastpoint=lastmb; } } if(point-height>lastpoint){ lastpoint=point; kolvo++; wanted=0; } else{ wanted=1; lastmb=point+height; lastpoint=point; } } if(wanted==1) kolvo++; System.out.println(kolvo); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
a85562e76f10b01101d807278a075460
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { static final long MOD = 1000000007L; static final int INF = 50000000; public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int N = sc.ni(); int[][] nums = new int[N][2]; for (int i = 0; i < N; i++) { nums[i][0] = sc.ni(); nums[i][1] = sc.ni(); } if (N <= 2) { pw.println(N); pw.close(); return; } int[][] dp = new int[N-1][3]; //dont cut, cut left, cut right dp[0][0] = 0; dp[0][1] = 1; for (int i = 1; i < N-1; i++) { Arrays.fill(dp[i],Integer.MIN_VALUE); dp[i][0] = Math.max(dp[i-1][0],Math.max(dp[i-1][1], dp[i-1][2])); if (nums[i][0]-nums[i][1] > nums[i-1][0]) { dp[i][1] = 1+Math.max(dp[i-1][0], dp[i-1][1]); if (nums[i][0]-nums[i][1] > nums[i-1][0]+nums[i-1][1]) { dp[i][1] = Math.max(dp[i][1], 1+dp[i-1][2]); } } if (nums[i][0]+nums[i][1] < nums[i+1][0]) { dp[i][2] = 1+dp[i][0]; } } pw.println(1+Math.max(dp[N-2][0], Math.max(dp[N-2][1], dp[N-2][2]))); pw.close(); } //Fast exponentiation (x^y mod m) public static long power(long x, long y, long m) { long ans = 1; x %= m; while (y > 0) { if(y % 2 == 1) ans = (ans * x) % m; y /= 2; x = (x * x) % m; } return ans; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { 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 ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
ba5dbbe229ef4b57a77f4b083dc18e69
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int numTrees = scan.nextInt(); int totalFell = 0; long thisCoord = scan.nextInt(); long thisHeight = scan.nextInt(); long lastRightMost = 0; boolean isFirst = true; for (int i = 0; i < numTrees - 1; i++) { int nextCoord = scan.nextInt(); int nextHeight = scan.nextInt(); long left = thisCoord - thisHeight; long right = thisCoord + thisHeight; if (left > lastRightMost || isFirst) { totalFell++; lastRightMost = thisCoord; isFirst = false; } else if (right < nextCoord) { totalFell++; lastRightMost = right; } else { lastRightMost = thisCoord; } thisCoord = nextCoord; thisHeight = nextHeight; } totalFell++; System.out.println(totalFell); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
7feb216aabea5518c4ac24cbd8bfb005
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; /** * Created by Kunaal on 10/21/17. */ public class Woodcutters { public static class Tree { int position; int height; Tree(int p, int h) { position = p; height = h; } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); if(n <= 2) { System.out.println(n); return; } Tree[] t = new Tree[n]; for (int i = 0; i < n; i++) { t[i] = new Tree(scan.nextInt(), scan.nextInt()); } int num = 2; for(int i = 1; i < n-1; i++) { if(t[i].position - t[i].height > t[i-1].position) { num++; } else if(t[i].position + t[i].height < t[i+1].position){ t[i].position += t[i].height; num++; } } System.out.println(num); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
2e84b4bfcfdeb7e01d1c9051fda77fbf
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.InputStream; import java.util.NoSuchElementException; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.IOException; /** * Built using CHelper plug-in * Actual solution is at the top * @author PloadyFree */ 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 { int getLeftPos(int index, int toCompare) { return Math.max(toCompare, index == 0 ? Integer.MIN_VALUE : trees[index - 1].first); } int getRightPos(int index) { return index == n - 1 ? Integer.MAX_VALUE : trees[index + 1].first; } Pair<Integer, Integer> trees[]; private int n; private int ans; void goRecursive(int lastTreeEnds, int indexStartTree, int currentRes) { ans = Math.max(currentRes, ans); for (int i = indexStartTree; i < n; i++) { Pair<Integer, Integer> tree = trees[i]; int pos = tree.first; int h = tree.second; int leftPos = getLeftPos(i, lastTreeEnds); int rightPos = getRightPos(i); if (pos - h > leftPos && pos < rightPos) { ans++; lastTreeEnds = pos; } else if (pos > leftPos && pos + h < rightPos) { ans++; lastTreeEnds = pos + h; } } } public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.readInt(); trees = new Pair[n]; for (int i = 0; i < n; i++) trees[i] = Pair.makePair(in.readInt(), in.readInt()); goRecursive(Integer.MIN_VALUE, 0, 0); out.print(ans); } } class Pair<U, V> implements Comparable<Pair<U, V>> { public final U first; public final V second; public static<U, V> Pair<U, V> makePair(U first, V second) { return new Pair<U, V>(first, second); } private Pair(U first, V second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null); } public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(Pair<U, V> o) { int value = ((Comparable<U>)first).compareTo(o.first); if (value != 0) return value; return ((Comparable<V>)second).compareTo(o.second); } } 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 void close() { writer.close(); } public void print(int i) { writer.print(i); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
cb0616301371740604227d25275215a0
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; public class Main { static Scanner s = new Scanner(System.in); static int N = -1; static int[][] treeInfo = null; static int[][] process = null; public static void main(String[] args) { init(); solve(); } public static void init(){ N = s.nextInt(); treeInfo = new int[2][N]; process = new int[N][3]; process[0][0] = 1; //0 : 왼, 1 : 가운 2 : 오 process[0][1] = 0; process[0][2] = 1; for(int i=0;i<N;i++){ treeInfo[0][i] = s.nextInt();//point treeInfo[1][i] = s.nextInt(); //height; } } public static void solve(){ for(int i=1;i<N;i++){ solveForLeft(i); solveForMiddle(i); solveForRight(i); } int Max = 0; for(int i=0;i<3;i++){ if(Max<process[N-1][i]) Max = process[N-1][i]; } System.out.println(Max); } public static void solveForLeft(int curIndex){ int maxTree = 0; int prv_tree_point = treeInfo[0][curIndex-1]; int prv_tree_height = treeInfo[1][curIndex -1]; int cur_tree_point = treeInfo[0][curIndex]; int cur_tree_height = treeInfo[1][curIndex]; //내전이 왼쪽이었다 if(prv_tree_point < cur_tree_point - cur_tree_height){ maxTree = process[curIndex-1][0] +1>process[curIndex-1][1] + 1? process[curIndex-1][0] +1:process[curIndex-1][1] + 1; } else{ maxTree = process[curIndex-1][0]>process[curIndex-1][1]? process[curIndex-1][0]:process[curIndex-1][1] ; } //내 전이 오른쪽이래 if(prv_tree_point+prv_tree_height<cur_tree_point-cur_tree_height){ maxTree = maxTree>process[curIndex-1][2]+1?maxTree:process[curIndex-1][2]+1; }else{ maxTree = maxTree>process[curIndex-1][2]?maxTree:process[curIndex-1][2]; } process[curIndex][0] = maxTree; } public static void solveForMiddle(int curIndex){ int maxTree = 0; for(int i=0;i<3;i++){ if(maxTree<process[curIndex-1][i]) maxTree = process[curIndex-1][i]; } process[curIndex][1] = maxTree; } public static void solveForRight(int curIndex){ int maxTree = 0; for(int i=0;i<3;i++){ if(maxTree<process[curIndex-1][i]) maxTree = process[curIndex-1][i]; } if(curIndex==N-1){ process[curIndex][2] = maxTree+1; return; } int nxt_tree_point = treeInfo[0][curIndex+1]; int nxt_tree_height = treeInfo[1][curIndex +1]; int cur_tree_point = treeInfo[0][curIndex]; int cur_tree_height = treeInfo[1][curIndex]; if(nxt_tree_point>cur_tree_point+cur_tree_height){ process[curIndex][2] = maxTree+1; }else{ process[curIndex][2] = maxTree; } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
bca1211cc7aeccac61fd155173b70c0a
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.*; import java.io.*; public class cf { private static final Scanner sc = new Scanner(new BufferedInputStream(System.in)); private static final PrintWriter pw = new PrintWriter(System.out, true); private static StringBuffer ans = new StringBuffer(); public static void main(String args[]) throws Exception { int n = sc.nextInt(), cnt = 1; long[] a = new long[n]; long[] h = new long[n]; for(int i = 0; i < n; i++) { a[i] = sc.nextLong(); h[i] = sc.nextLong(); } for(int i = 1; i < n - 1; i++) { if(a[i - 1] < a[i] - h[i]) cnt++; else if(a[i] + h[i] < a[i + 1]) { cnt++; a[i] += h[i]; } } if(n > 1)cnt++; ans.append(cnt); pw.print(ans); sc.close(); pw.close(); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
f0d49728b880249fe11851d838b3ab9f
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); TaskC.tree[] arr = new TaskC.tree[n + 1]; for (int i = 0; i < n; i++) { arr[i] = new TaskC.tree(); arr[i].x = in.nextInt(); arr[i].h = in.nextInt(); } int ans = 1; int right = arr[0].x; for (int i = 1; i < n; i++) { if (arr[i].x - arr[i].h > right) { ans++; right = arr[i].x; } else if (i == n - 1 || arr[i].x + arr[i].h < arr[i + 1].x) { ans++; right = arr[i].x + arr[i].h; } else right = arr[i].x; } out.println(ans); } static class tree { int x; int h; } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
ca406af5d1fb21a47b304c706d1eeaf2
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.*; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; public class Mai { // for (Map.Entry<Integer, Integer> e : x.entrySet()) // { // e.getValue() , e.getKey static int n ; static int rec( int i , int state , long r , long x[] , long h[] , int dy[][] ) { if ( i == n ) return 0 ; if ( dy[i][state] != -1 ) return dy[i][state] ; if ( r >= x[i] ) return (int) -1e9 ; int op1 = rec ( i + 1 , 2 , x[i] , x , h , dy ) , op2 = 0 , op3 = 0 ; if ( r < x[i] - h[i] ) op2 = 1 + rec( i + 1 , 1 , x[i] , x , h , dy ) ; op3 = 1 + rec( i + 1 , 0 , x[i] + h[i] , x , h , dy ) ; return dy[i][state] = Math.max(op1, Math.max(op2, op3)) ; } public static void main(String[] args) throws FileNotFoundException { // TODO code application logic here LetsDoIt in = new LetsDoIt(); // Scanner in = new Scanner(System.in) ; // FastReaderFile in = new FastReaderFile(new FileInputStream("girls.in")) ; // out = new PrintWriter(new BufferedOutputStream(new FileOutputStream("output.txt")), true) ; out = new PrintWriter(new BufferedOutputStream(System.out), true) ; n = in.nextInt() ; long x[] = new long [n] ; long h[] = new long [n] ; int dy[][] = new int [n][4] ; for ( int i = 0 ; i < n ; ++i ) { x[i] = in.nextLong() ; h[i] = in.nextLong() ; Arrays.fill(dy[i], -1); } out.println(rec( 0 , 3 , (int)-1e9 , x , h , dy )); } public static class FastReaderFile { BufferedReader br; StringTokenizer st; public FastReaderFile(InputStream in) { br = new BufferedReader(new InputStreamReader(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; } } public static class LetsDoIt { BufferedReader br; StringTokenizer st; public LetsDoIt() { 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; } } public static PrintWriter out; static boolean isPrime( long n) { if (n < 2) return false; if (n < 4) return true; if (n%2 == 0 || n%3 == 0) return false; for (long i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0) return false ; return true; } static long gcd(long a, long b) { return b == 0 ? (a < 0 ? -a : a) : gcd(b, a % b); } static long lcm(long a, long b) { long lcm = (a / gcd(a, b)) * b; return lcm > 0 ? lcm : -lcm ; } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
e4bfd012975b99d3231e51b664289383
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
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. */ import java.util.*; import java.io.*; /** * * @author MR */ public class Code { /** * @param args the command line arguments */ static int n , y[][] ; static long x[][] ; static int ret( int i , long h , int st ) { if ( i == n ) return 0 ; if ( h == -1 ) return 1 + ret( i + 1 , x[i][0] , 1 ) ; if ( y[i][st] != -1 ) return y[i][st] ; int a = 0 , b = 0 , c = 0 ; if ( h >= x[i][0] ) return -1000000000 ; if ( x[i][0] - x[i][1] > h ) c = 1 + ret( i + 1 , x[i][0] , 1 ) ; a = Math.max(c, ret( i + 1 , x[i][0] , 0 )) ; b = 1 + ret( i + 1 , x[i][0] + x[i][1] , 2 ) ; return y[i][st] = Math.max(a, b) ; } public static void main(String[] args) { // TODO code application logic here LetsDoIt in = new LetsDoIt(); // Scanner in = new Scanner(System.in) ; // FastReaderFile in = new FastReaderFile(new FileInputStream("fun.in")) ; // out = new PrintWriter(new BufferedOutputStream(new FileOutputStream("output.txt")), true) ; out = new PrintWriter(new BufferedOutputStream(System.out), true) ; n = in.nextInt() ; x = new long[n][2] ; y = new int[n][3] ; for ( int i = 0 ; i < n ; ++i ) { x[i][0] = in.nextInt() ; x[i][1] = in.nextInt() ; Arrays.fill(y[i], -1) ; } out.println(ret( 0 , -1 , -1)) ; } static long nCk( long n, long k ) { if (k > n) return 0; if (k * 2 > n) k = n-k; if (k == 0) return 1; long result = n; for( long i = 2; i <= k; ++i ) { result *= (n-i+1); result /= i; } return result; } static boolean isPrime( long n) { if (n < 2) return false; if (n < 4) return true; if (n%2 == 0 || n%3 == 0) return false; for (long i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0) return false ; return true; } static long gcd(long a, long b) { return b == 0 ? (a < 0 ? -a : a) : gcd(b, a % b); } static long lcm(long a, long b) { long lcm = (a / gcd(a, b)) * b; return lcm > 0 ? lcm : -lcm ; } public static class FastReaderFile { BufferedReader br; StringTokenizer st; public FastReaderFile(InputStream in) { br = new BufferedReader(new InputStreamReader(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; } } public static class LetsDoIt { BufferedReader br; StringTokenizer st; public LetsDoIt() { 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; } } public static PrintWriter out; }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
9381510eb46e3415c63e9c5941f8ae7e
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
// All important imports import static java.lang.System.in; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.Queue; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Vector; /** * * @author Mustafa Filmwala * Built using Netbeans IDE 8.0.1 */ public class Main{ public static void solve() throws IOException { int n=ni(),a,b,occupy=Integer.MIN_VALUE; int ans=0; int arr[][]=new int[n+1][2]; for(int i=0;i<n;i++) { arr[i][0]=ni(); arr[i][1]=ni(); } for(int i=0;i<n;i++) { if(arr[i][0]-arr[i][1]>occupy){ans++; occupy=arr[i][0];} else if(arr[i][0]+arr[i][1]<arr[i+1][0] || i==n-1){ans++; occupy=arr[i][0]+arr[i][1];} else occupy=arr[i][0]; //out.println(occupy); } out.println(ans); } static String TESTCASES; static PrintWriter out; public static void main(String[] args) throws Exception { out=new PrintWriter(System.out); InputStream myinp=System.in; init(myinp); //int tc=ni(); //for(int i=0;i<tc;i++) solve(); out.flush(); //endTime=System.currentTimeMillis(); } static InputStream is; static BufferedReader brr; public static void init(InputStream input) { is=input; //brr=new BufferedReader(new InputStreamReader(input)); } protected static byte[] inbuf = new byte[1024]; static int lenbuf = 0, ptrbuf = 0; protected static 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++]; } protected static String readline() throws IOException { return brr.readLine(); } // extras protected static double nd() { return Double.parseDouble(ns()); } protected static char nc() { return (char)skip(); } protected static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } protected static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } protected static 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(); } protected static char[] nca(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); } protected static int[] nia(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } protected static int[][] niaindex(int n) { int ea[][]=new int[n][2]; for(int i=0;i<n;i++) { ea[i][0]=ni(); ea[i][1]=i; } return ea; } protected static long[] nla(int n) { long[] a = new long[n]; for(int i = 0;i < n;i++)a[i] = nl(); return a; } protected static long[][] nlaindex(int n) { long ea[][]=new long[n][2]; for(int i=0;i<n;i++) { ea[i][0]=ni(); ea[i][1]=i; } return ea; } protected static String[] nsa(int n) { String[] a = new String[n]; for(int i = 0;i < n;i++)a[i] = ns(); return a; } protected static double[] nda(int n) { double[] a = new double[n]; for(int i = 0;i < n;i++)a[i] = nd(); return a; } protected static 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(); } } protected static 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(); } } // Outputs public static void pln(){out.println();} public static void ps(String s){out.print(s);} public static void pi(int s){out.print(s);} public static void pl(long s){out.print(s);} public static void pd(double s){out.print(s);} public static void psp(){out.print(" ");} public static void parr(int s[]){out.println(Arrays.toString(s));} public static void parr(String s[]){out.println(Arrays.toString(s));} public static void parr(long s[]){out.println(Arrays.toString(s));} public static void parr2(int s[][]){for(int i=0;i<s.length;i++)out.println(Arrays.toString(s[i]));} public static void parr2(long s[][]){for(int i=0;i<s.length;i++)out.println(Arrays.toString(s[i]));} public static void parr2(String s[][]){for(int i=0;i<s.length;i++)out.println(Arrays.toString(s[i]));} }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
ae1d5ecfb102bfd04a8cc06ea9b80e91
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; public class WoodCutter { public static void main(String[] args) { // TODO Auto-generated method stub long[] numberOfTree = new long[3]; long[] xCoordinate = new long[3]; // 입력 Scanner scanner = new Scanner(System.in); long number = scanner.nextLong(); long[] treeLocation = new long[(int)number]; long[] height = new long[(int)number]; for(long i=0; i<number; i++){ treeLocation[(int)i] = scanner.nextLong(); height[(int)i] = scanner.nextLong(); } // 최적 찾기 long tempTreeNumber = 0; long tempX = 0; // 맨처음에 tree를 왼쪽으로 넘긴다 무조건 // numberOfTree[0] = 1; // xCoordinate[0] = treeLocation[0]; // // numberOfTree[1] = 0; // xCoordinate[1] = treeLocation[0]; // // if(treeLocation[0] + height[0] < treeLocation[1]){ // numberOfTree[2] = 1; // xCoordinate[2] = treeLocation[0] + height[0]; // }else{ // numberOfTree[2] = 0; // xCoordinate[2] = treeLocation[0]; // } long optimalX = treeLocation[0]; long optimalNumber = 1; for(long i=1; i<number-1; i++){ // 왼쪽으로 쓰러질 수 있다면 if(treeLocation[(int)i]-height[(int)i] > optimalX){ numberOfTree[0] = optimalNumber + 1; xCoordinate[0] = treeLocation[(int)i]; } // 오른쪽으로 쓰러질 수 있다면 if(treeLocation[(int)i] + height[(int)i] < treeLocation[(int)i+1]){ numberOfTree[2] = optimalNumber + 1; xCoordinate[2] = treeLocation[(int)i] + height[(int)i]; } numberOfTree[1] = optimalNumber; xCoordinate[1] = treeLocation[(int)i]; if(numberOfTree[0] < numberOfTree[1]){ if(numberOfTree[1] < numberOfTree[2]){ optimalNumber = numberOfTree[2]; optimalX = treeLocation[(int)i] + height[(int)i]; }else{ optimalNumber = numberOfTree[1]; optimalX = treeLocation[(int)i]; } }else{ if(numberOfTree[0] < numberOfTree[2]){ optimalNumber = numberOfTree[2]; optimalX = treeLocation[(int)i] + height[(int)i]; }else{ optimalNumber = numberOfTree[0]; optimalX = treeLocation[(int)i]; } } } // if(numberOfTree[0] < numberOfTree[1]){ // if(numberOfTree[1] < numberOfTree[2]){ // System.out.println(numberOfTree[2] + 1); // }else{ // System.out.println(numberOfTree[1] + 1); // } // }else{ // if(numberOfTree[0] < numberOfTree[2]){ // System.out.println(numberOfTree[2] + 1); // }else{ // System.out.println(numberOfTree[0] + 1); // } // } if(number >1){ System.out.println(optimalNumber+1); }else{ System.out.println(optimalNumber); } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
1bc234c95370638cd7d3e008fa8087f5
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { InputReader fi=new InputReader(System.in); int n=fi.nextInt(); int i,j,k; int x[]=new int[n]; int h[]=new int[n]; for (i=0;i<n;i++){ x[i]=fi.nextInt(); h[i]=fi.nextInt(); } long current=x[0]; int ans=Math.min(n,2); int stay,left,right; left=right=1; stay=0; for(i=1;i<n-1;i++){ if (x[i]-h[i] > current){ current=x[i]; left++; } else if (x[i] + h[i] < x[i+1]){ current=x[i]+h[i]; right++; } else { current=x[i]; } ans=Math.max(ans,Math.max(left+right,0)); } System.out.println(ans); } } class InputReader { private InputStream stream; private 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+1]; for (int i = 1; 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
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
653d31aab5863caaee6e5f4ca279f49d
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { InputReader fi=new InputReader(System.in); int n=fi.nextInt(); int i,j,k; int x[]=new int[n]; int h[]=new int[n]; for (i=0;i<n;i++){ x[i]=fi.nextInt(); h[i]=fi.nextInt(); } long current=x[0]; int ans=Math.min(n,2); for (i=1;i<n-1;i++){ if (x[i]-h[i] > current){ current=x[i]; ans++; } else if (x[i]+h[i] < x[i+1]){ current=x[i]+h[i]; ans++; } else current=x[i]; } System.out.println(ans); } } class InputReader { private InputStream stream; private 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+1]; for (int i = 1; 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
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
6d08c2a55b1624d05de2ffa2104a8b52
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class C545 { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.valueOf(new StringTokenizer(br.readLine()).nextToken()); int[] point = new int[n+1]; int[] height = new int[n+1]; int count = 2,now = 0; if(n==1){ count--; System.out.println(count);return; } for(int i=1;i<n+1;i++){ String a = br.readLine(); String[] v = a.split(" "); point[i] = Integer.parseInt(v[0]); height[i] = Integer.parseInt(v[1]); } now = point[1]; for(int i=2;i<n;i++){ if(point[i]-height[i]>now){ count++;now = point[i]; }else if(point[i]+height[i]<point[i+1]){ count++;now = point[i]+height[i]; }else now = point[i]; } System.out.println(count); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
a203e5bf7a15ae04f6757c4a744be81e
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; public class Main { static Scanner s = new Scanner(System.in); static int N = -1; static int[][] treeInfo = null; static int[][] process = null; public static void main(String[] args) { init(); solve(); } public static void init(){ N = s.nextInt(); treeInfo = new int[2][N]; process = new int[N][3]; process[0][0] = 1; //0 : 왼, 1 : 가운 2 : 오 process[0][1] = 0; process[0][2] = 1; for(int i=0;i<N;i++){ treeInfo[0][i] = s.nextInt();//point treeInfo[1][i] = s.nextInt(); //height; } } public static void solve(){ for(int i=1;i<N;i++){ solveForLeft(i); solveForMiddle(i); solveForRight(i); } int Max = 0; for(int i=0;i<3;i++){ if(Max<process[N-1][i]) Max = process[N-1][i]; } System.out.println(Max); } public static void solveForLeft(int curIndex){ int maxTree = 0; int prv_tree_point = treeInfo[0][curIndex-1]; int prv_tree_height = treeInfo[1][curIndex -1]; int cur_tree_point = treeInfo[0][curIndex]; int cur_tree_height = treeInfo[1][curIndex]; //내전이 왼쪽이었다 if(prv_tree_point < cur_tree_point - cur_tree_height){ maxTree = process[curIndex-1][0] +1>process[curIndex-1][1] + 1? process[curIndex-1][0] +1:process[curIndex-1][1] + 1; } else{ maxTree = process[curIndex-1][0]>process[curIndex-1][1]? process[curIndex-1][0]:process[curIndex-1][1] ; } //내 전이 오른쪽이래 if(prv_tree_point+prv_tree_height<cur_tree_point-cur_tree_height){ maxTree = maxTree>process[curIndex-1][2]+1?maxTree:process[curIndex-1][2]+1; }else{ maxTree = maxTree>process[curIndex-1][2]?maxTree:process[curIndex-1][2]; } process[curIndex][0] = maxTree; } public static void solveForMiddle(int curIndex){ int maxTree = 0; for(int i=0;i<3;i++){ if(maxTree<process[curIndex-1][i]) maxTree = process[curIndex-1][i]; } process[curIndex][1] = maxTree; } public static void solveForRight(int curIndex){ int maxTree = 0; for(int i=0;i<3;i++){ if(maxTree<process[curIndex-1][i]) maxTree = process[curIndex-1][i]; } if(curIndex==N-1){ process[curIndex][2] = maxTree+1; return; } int nxt_tree_point = treeInfo[0][curIndex+1]; int nxt_tree_height = treeInfo[1][curIndex +1]; int cur_tree_point = treeInfo[0][curIndex]; int cur_tree_height = treeInfo[1][curIndex]; if(nxt_tree_point>cur_tree_point+cur_tree_height){ process[curIndex][2] = maxTree+1; }else{ process[curIndex][2] = maxTree; } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
892b1502ef6cb26dcbca1be968b1738f
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; public class Main { static Scanner s = new Scanner(System.in); static int N = -1; static int[][] treeInfo = null; static int[][] process = null; public static void main(String[] args) { init(); solve(); } public static void init(){ N = s.nextInt(); treeInfo = new int[2][N]; process = new int[N][3]; process[0][0] = 1; //0 : 왼, 1 : 가운 2 : 오 process[0][1] = 0; process[0][2] = 1; for(int i=0;i<N;i++){ treeInfo[0][i] = s.nextInt();//point treeInfo[1][i] = s.nextInt(); //height; } } public static void solve(){ for(int i=1;i<N;i++){ solveForLeft(i); solveForMiddle(i); solveForRight(i); } int Max = 0; for(int i=0;i<3;i++){ if(Max<process[N-1][i]) Max = process[N-1][i]; } System.out.println(Max); } public static void solveForLeft(int curIndex){ int maxTree = 0; int prv_tree_point = treeInfo[0][curIndex-1]; int prv_tree_height = treeInfo[1][curIndex -1]; int cur_tree_point = treeInfo[0][curIndex]; int cur_tree_height = treeInfo[1][curIndex]; //내전이 왼쪽이었다 if(prv_tree_point < cur_tree_point - cur_tree_height){ maxTree = process[curIndex-1][0] +1>process[curIndex-1][1] + 1? process[curIndex-1][0] +1:process[curIndex-1][1] + 1; } else{ maxTree = process[curIndex-1][0]>process[curIndex-1][1]? process[curIndex-1][0]:process[curIndex-1][1] ; } //내 전이 오른쪽이래 if(prv_tree_point+prv_tree_height<cur_tree_point-cur_tree_height){ maxTree = maxTree>process[curIndex-1][2]+1?maxTree:process[curIndex-1][2]+1; }else{ maxTree = maxTree>process[curIndex-1][2]?maxTree:process[curIndex-1][2]; } process[curIndex][0] = maxTree; } public static void solveForMiddle(int curIndex){ int maxTree = 0; for(int i=0;i<3;i++){ if(maxTree<process[curIndex-1][i]) maxTree = process[curIndex-1][i]; } process[curIndex][1] = maxTree; } public static void solveForRight(int curIndex){ int maxTree = 0; for(int i=0;i<3;i++){ if(maxTree<process[curIndex-1][i]) maxTree = process[curIndex-1][i]; } if(curIndex==N-1){ process[curIndex][2] = maxTree+1; return; } int nxt_tree_point = treeInfo[0][curIndex+1]; int nxt_tree_height = treeInfo[1][curIndex +1]; int cur_tree_point = treeInfo[0][curIndex]; int cur_tree_height = treeInfo[1][curIndex]; if(nxt_tree_point>cur_tree_point+cur_tree_height){ process[curIndex][2] = maxTree+1; }else{ process[curIndex][2] = maxTree; } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
a5379ea83869c6b31b6b54f8d243820b
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.awt.*; import java.util.Scanner; public class Woodcutters { private static class Tuple { long x; long y; Tuple(long x, long y) { this.x = x; this.y = y; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); if (n == 1) { System.out.println(1); return; } /** * max goint to left 1 0 0 0 3// 0 if intersects in place, if it intersects the right then 1+(max(left, in place)), else right+1(?) * max going in place 0 1 2 2 2 // max of previous's left, in place, right * max going to right 0 2 0 0 3 // 0 if intersects next's in place && not last element, else 1+max of previous's left, in place, right * return max * 1 2 * 2 1 * 5 10 * 10 9 * 19 1 */ long[] left = new long[n]; long[] place = new long[n]; long[] right = new long[n]; Tuple[] data = new Tuple[n]; for (int i = 0; i < n; i++) { data[i] = new Tuple(in.nextLong(), in.nextLong()); } left[0] = 1; place[0] = 0; right[0] = data[0].x + data[0].y >= data[1].x ? 0 : 1; // System.out.printf("%d %d %d\n", right[0], place[0], left[0]); for (int i = 1; i < n; i++) { left[i] = data[i].x - data[i].y <= data[i - 1].x ? 0 : data[i].x - data[i].y <= data[i - 1].x + data[i - 1].y ? 1 + max(left[i - 1], place[i - 1]) : right[i - 1] + 1; place[i] = max(left[i - 1], place[i - 1], right[i - 1]); right[i] = (i != n - 1 && data[i].x + data[i].y >= data[i + 1].x) ? 0 : 1 + max(left[i - 1], place[i - 1], right[i - 1]); // System.out.printf("%d %d %d\n", right[i], place[i], left[i]); } System.out.println(max(left[n - 1], place[n - 1], right[n - 1])); } // static long max(long a, long b, long c) { return Math.max(Math.max(a, b), c); } static long max(long a, long b) { return Math.max(a, b); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
a9fb2374e3dd36675d83c705c9a77c4c
train_002.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; /* * 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 Gerasimov */ public class Main { public static void main(String[] args) throws FileNotFoundException, IOException { PrintWriter out = new PrintWriter(System.out); BufferedReader inp = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(inp.readLine()); int n = Integer.parseInt(st.nextToken()); HashMap<Integer, Integer> mas = new HashMap<>(); st = new StringTokenizer(inp.readLine()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); mas.put(1, x); for (int i = 0; i < n - 1; i++) { st = new StringTokenizer(inp.readLine()); x = Integer.parseInt(st.nextToken()); y = Integer.parseInt(st.nextToken()); HashSet<Integer> hh = new HashSet<>(); for (int j : mas.keySet()) { if (mas.get(j) >= x) { hh.add(j); } } for (int j : hh) { mas.remove(j); } int mm = 0; HashMap<Integer, Integer> smas = new HashMap<>(); for (int j : mas.keySet()) { int h = mas.get(j); if (h < x - y) { if (mas.containsKey(j + 1)) { if (mas.get(j + 1) > x) { mas.replace(j + 1, x); } } else { smas.put(j + 1, x); } } else { if (h < x) { if (mas.containsKey(j + 1)) { if (mas.get(j + 1) > x + y) { mas.replace(j + 1, x + y); } } else { smas.put(j + 1, x + y); } } } if (mas.get(j) < x) { mas.replace(j, x); if (mm < j) { mm = j; } } } mas.putAll(smas); hh = new HashSet<>(); for (int j : mas.keySet()) { if (j < mm) { hh.add(j); } } for (int j : hh) { mas.remove(j); } } int max = 0; for (int j : mas.keySet()) { if (max < j) { max = j; } } out.print(max); out.close(); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
9f29cd57a7c1f80cfef12fc86bd669ac
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
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. */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; /** * * @author sataev_mb */ public class Xusha { static int n; static int a[]; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); pow(); args = in.readLine().split(" "); n = Integer.parseInt(args[0]); int m = Integer.parseInt(args[1]); String str[] = in.readLine().split(" "); a = new int[pow[n]]; for (int i = 0; i < str.length; i++) { a[i] = Integer.parseInt(str[i]); } Node root = new Node(); root.calcNodes(n, 0); for (int i = 0; i < m; i++) { args = in.readLine().split(" "); int p = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); if (a[p - 1] != b) { root.change(p - 1, b, 0); a[p - 1] = b; } out.write(fromBinary(root.var) + "\n"); } out.flush(); out.close(); } static class Node { int level; boolean var[]; Node right; Node left; void calcNodes(int level, int index) { this.level = level; if (this.level == 0) { this.var = toBinary(a[index]); return; } else { this.left = new Node(); this.right = new Node(); this.left.calcNodes(level - 1, index * 2); this.right.calcNodes(level - 1, index * 2 + 1); if (this.level % 2 == 1) { this.var = or(this.left.var, this.right.var); } else { this.var = xor(this.left.var, this.right.var); } } } void change(int index, int value, int parent) { if (this.level == 0) { this.var = toBinary(value); } else { int middle = pow[this.level - 1]; if (index < parent + middle) { this.left.change(index, value, parent); } else { this.right.change(index, value, parent + middle); } if (this.level % 2 == 1) { this.var = or(this.left.var, this.right.var); } else { this.var = xor(this.left.var, this.right.var); } } } } static int pow[] = new int[31]; static int pow() { int result = 1; for (int i = 0; i < 31; i++) { pow[i] = result; result *= 2; } return result; } static boolean[] toBinary(int value) { int k = 0; for (int i = 0; i < pow.length; i++) { if (pow[i] > value) { k = i; break; } } boolean result[] = new boolean[k]; for (int i = 0; i < 31 && value > 0; i++) { result[i] = (value % 2 == 1); value = value / 2; } return result; } static int fromBinary(boolean[] a) { int result = 0; for (int i = 0; i < a.length; i++) { if (a[i]) { result += pow[i]; } } return result; } static boolean[] or(boolean a[], boolean b[]) { int maxlen = (a.length > b.length ? a.length : b.length); int minlen = (a.length < b.length ? a.length : b.length); boolean c[] = new boolean[maxlen]; for (int i = 0; i < minlen; i++) { c[i] = b[i] | a[i]; } if (a.length > b.length) { for (int i = minlen; i < c.length; i++) { c[i] = a[i]; } } else if (a.length < b.length) { for (int i = minlen; i < c.length; i++) { c[i] = b[i]; } } return c; } static boolean[] xor(boolean a[], boolean b[]) { int maxlen = (a.length > b.length ? a.length : b.length); int minlen = (a.length < b.length ? a.length : b.length); boolean c[] = new boolean[maxlen]; for (int i = 0; i < minlen; i++) { c[i] = b[i] ^ a[i]; } if (a.length > b.length) { for (int i = minlen; i < c.length; i++) { c[i] = a[i]; } } else if (a.length < b.length) { for (int i = minlen; i < c.length; i++) { c[i] = b[i]; } } return c; } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
30ee4768d0bd5008ac2fe9092d48f16b
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class XeniaandBitOperations { private static int n, q; private static long[] arr; private static long[] segmentTree; private static void build(int node, int start, int end, boolean OR){ if(start == end){ segmentTree[node] = arr[start]; return; } int mid = (start + end)/2; build(2*node, start, mid, !OR); build(2*node+1, mid+1, end, !OR); segmentTree[node] = (OR)? segmentTree[2*node]|segmentTree[2*node+1] : segmentTree[2*node]^segmentTree[2*node+1]; } private static void update(int node, int a, int b, int pos, long value, boolean OR){ if(a == b){ segmentTree[node] = value; return; } int mid = (a+b)/2; if(pos <= mid){ update(2*node, a, mid, pos, value, !OR); }else{ update(2*node+1, mid+1, b, pos, value, !OR); } segmentTree[node] = (OR)? segmentTree[2*node]|segmentTree[2*node+1] : segmentTree[2*node]^segmentTree[2*node+1]; } public static void main(String[] args){ PrintWriter pw = new PrintWriter(System.out, true); Scanner sc = new Scanner(System.in); boolean OR; long a, b; n = sc.nextInt(); a = n; n = 1<<a; q = sc.nextInt(); arr = new long[n]; segmentTree = new long[4*n+1]; for(int i=0;i<n;i++){ arr[i] = sc.nextLong(); } OR = (a%2 != 0); build(1, 0, n-1, OR); for(int i=0;i<q;i++){ a = sc.nextInt()-1; b = sc.nextInt(); update(1, 0, n-1, (int)a, (long)b, OR); pw.println(segmentTree[1]); } sc.close(); pw.close(); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
83798544276cbdb04c7bda4aef94177f
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.InputMismatchException; 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); int N = in.readInt(); int M = in.readInt(); long A[] = new long[(int) Math.pow(2, N)]; for (int I = 0; I < A.length; I++) { A[I] = in.readLong(); } segment seg = new segment(A); seg.init(1, 0, A.length-1); //System.out.println(seg.M[1]); for (int I = 0; I < M; I++) { int X = in.readInt()-1; long Val = in.readLong(); seg.update(1, 0, A.length-1, X, Val); out.printLine(seg.M[1]); } out.close(); } } class segment { long[] M; int N; long A[]; public segment(long A[]) { N = A.length; M = new long[N * 18 + 10]; this.A = A; } public int init(int node, int b, int e) { //System.out.println("Entered Node "+node+" "+b+" "+e); if (b == e) { M[node] = A[b]; //System.out.println("Node "+node+" ->"+M[node]); return 0; } else { int x = init(node * 2, b, (b + e) / 2); init(node * 2 + 1, (b + e) / 2 + 1, e); if (x % 2 == 0) { M[node] = M[node * 2] | M[node * 2 + 1]; } else { M[node] = M[node * 2] ^ M[node * 2 + 1]; } //System.out.println("Node "+node+" ->"+M[node]); return x + 1; } } public int update(int node, int b, int e, int exa, long val) { if (b == e && b == exa) { M[node] = val; // System.out.println("Node "+node+" ->"+M[node]); return 0; } else { if (exa >= b && exa <= (b + e) / 2) { int x = update(node * 2, b, (b + e) / 2, exa, val); if (x % 2 == 0) M[node] = M[node * 2] | M[node * 2 + 1]; else { M[node] = M[node * 2] ^ M[node * 2 + 1]; } // System.out.println("Node "+node+" ->"+M[node]); return x + 1; } else { int x = update(node * 2 + 1, (b + e) / 2 + 1, e, exa, val); if (x % 2 == 0) M[node] = M[node * 2] | M[node * 2 + 1]; else { M[node] = M[node * 2] ^ M[node * 2 + 1]; } // System.out.println("Node "+node+" ->"+M[node]); return x + 1; } } } } 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 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 String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(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
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
3a7d44123fef78b63cb00fbb0da70a34
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class XeniaAndBitOperations { class SegmentTree { int tree[], arr[]; public SegmentTree(int sz, int arr[], int lv) { tree = new int[4 * sz]; this.arr = arr; build(0, 0, arr.length - 1, lv); } void build(int idx, int st, int en, int lev) { if (st == en) { tree[idx] = arr[st]; return; } int mid = st + (en - st) / 2; build(2 * idx + 1, st, mid, lev ^ 1); build(2 * idx + 2, mid + 1, en, lev ^ 1); if (lev != 0) tree[idx] = tree[2 * idx + 1] | tree[2 * idx + 2]; else tree[idx] = tree[2 * idx + 1] ^ tree[2 * idx + 2]; } void update(int idx, int st, int en, int tar, int val, int lev) { if(tar < st || tar > en) return; if (st == en) { tree[idx] = val; return; } int mid = st + (en - st) / 2; update(2 * idx + 1, st, mid, tar, val, lev ^ 1); update(2 * idx + 2, mid + 1, en, tar, val, lev ^ 1); if (lev != 0) tree[idx] = tree[2 * idx + 1] | tree[2 * idx + 2]; else tree[idx] = tree[2 * idx + 1] ^ tree[2 * idx + 2]; } } void run() throws Exception { BufferedReader bfd = new BufferedReader( new InputStreamReader(System.in)); StringTokenizer tk = new StringTokenizer(bfd.readLine()); int n = Integer.parseInt(tk.nextToken()); int m = Integer.parseInt(tk.nextToken()); int arr[] = new int[1 << n]; tk = new StringTokenizer(bfd.readLine()); for (int i = 0; i < (1 << n); ++i) { arr[i] = Integer.parseInt(tk.nextToken()); } SegmentTree st = new SegmentTree(arr.length, arr, n % 2); int p, b; while (m-- > 0) { tk = new StringTokenizer(bfd.readLine()); p = Integer.parseInt(tk.nextToken()) - 1; b = Integer.parseInt(tk.nextToken()); st.update(0, 0, arr.length - 1, p, b, n % 2); // root always contains the answer System.out.println(st.tree[0]); } } public static void main(String[] args) throws Exception { new XeniaAndBitOperations().run(); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
539a6f724e4854a489527005bd64e920
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Xenia { static int[] in; static int[] out; final static int IDENTITY = 0; static int HEIGHT = 0; public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in)); String[] input = stdin.readLine().split(" "); int n = Integer.parseInt(input[0]); int m = Integer.parseInt(input[1]); String[] inp = stdin.readLine().split(" "); in = new int[(int) Math.pow(2, n)]; for (int i = 0; i < in.length; i++) in[i] = Integer.parseInt(inp[i]); HEIGHT = (int) Math.ceil(Math.log(in.length) / Math.log(2)); out = new int[(int) (Math.pow(2, HEIGHT)) << 1]; Arrays.fill(out, IDENTITY); initialiseOR(1, 0, in.length - 1, HEIGHT); //System.out.println(Arrays.toString(out)); for (int i = 0; i < m; i++) { String[] inp1 = stdin.readLine().split(" "); update(Integer.parseInt(inp1[0]) - 1, Integer.parseInt(inp1[1])); System.out.println(out[0]); } } static void initialiseOR(int node, int beg, int end, int level) { if (beg == end) { out[node - 1] = in[beg]; } else { initialiseOR((2 * node), beg, ((end + beg) / 2) ,level - 1); initialiseOR((2 * node + 1), ((end + beg) / 2) + 1, end, level -1); /* * Sum of children */ int res = 0; if (level % 2 == 0) res = out[2 * node - 1] ^ out[2 * node]; else res = out[2 * node - 1] | out[2 * node]; out[node - 1] = res; } } static void update(int index, int value) { index += in.length; out[index - 1] = value; int level = 0; while (index > 1) { int res = 0; index >>= 1; level += 1; if (level % 2 == 0) res = out[2 * index - 1] ^ out[2 * index]; else res = out[2 * index - 1] | out[2 * index]; out[index - 1] = res; } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
8a228acc48fe8c6e1215656ad2da272f
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; /* br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); */ public class Main { private static BufferedReader br; private static StringTokenizer st; private 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 qq = 1; int qq = Integer.MAX_VALUE; //int qq = readInt(); for(int casenum = 1; casenum <= qq; casenum++) { int n = readInt(); int m = readInt(); int[] list = new int[1<<n]; for(int i = 0; i < 1<<n; i++) { list[i] = readInt(); } SegmentTree ret = new SegmentTree(list); while(m-- > 0) { int index = readInt(); int val = readInt(); ret.update(--index, val); pw.println(ret.getRoot()); } } pw.close(); } static class SegmentTree { int[] tree; boolean[] or; int size; public SegmentTree(int[] list) { tree = new int[4*list.length]; or = new boolean[4*list.length]; size = list.length; build(1,0,list.length-1,list); } public void build(int index, int l, int r, int[] list) { if(l == r) { tree[index] = list[l]; } else { int m = (l+r)/2; build(2*index, l, m, list); build(2*index+1, m+1, r, list); or[index] = !or[2*index]; if(or[index]) { tree[index] = tree[2*index] | tree[2*index+1]; } else { tree[index] = tree[2*index] ^ tree[2*index+1]; } } } public void update(int index, int val) { update(1, 0, size-1, index, val); } public void update(int index, int l, int r, int ii, int v) { if(ii < l || ii > r) return; if(l==r) { tree[index] = v; return; } else { int m = (l+r)/2; update(2*index, l, m, ii, v); update(2*index+1, m+1, r, ii, v); if(or[index]) { tree[index] = tree[2*index] | tree[2*index+1]; } else { tree[index] = tree[2*index] ^ tree[2*index+1]; } } } public int getRoot() { return tree[1]; } } private static void exitImmediately() { pw.close(); System.exit(0); } private static long readLong() throws IOException { return Long.parseLong(nextToken()); } private static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } private static int readInt() throws IOException { return Integer.parseInt(nextToken()); } private static String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { if(!br.ready()) { exitImmediately(); } st = new StringTokenizer(br.readLine().trim()); } return st.nextToken(); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
d6a57747ac94b0216a058dfebfb9a80e
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class XeniaAndBitOperations { class SegmentTree { int tree[], arr[]; public SegmentTree(int sz, int arr[], int n) { tree = new int[4 * sz]; this.arr = arr; build(0, 0, arr.length - 1, n%2); } void build(int idx, int st, int en, int lev) { if (st == en) { tree[idx] = arr[st]; return; } int mid = st + (en - st) / 2; build(2 * idx + 1, st, mid, lev ^ 1); build(2 * idx + 2, mid + 1, en, lev ^ 1); if (lev != 0) tree[idx] = tree[2 * idx + 1] | tree[2 * idx + 2]; else tree[idx] = tree[2 * idx + 1] ^ tree[2 * idx + 2]; } void update(int idx, int st, int en, int tar, int val, int lev) { if(tar < st || tar > en) return; if (st == en) { tree[idx] = val; return; } int mid = st + (en - st) / 2; update(2 * idx + 1, st, mid, tar, val, lev ^ 1); update(2 * idx + 2, mid + 1, en, tar, val, lev ^ 1); if (lev != 0) tree[idx] = tree[2 * idx + 1] | tree[2 * idx + 2]; else tree[idx] = tree[2 * idx + 1] ^ tree[2 * idx + 2]; } } void run() throws Exception { BufferedReader bfd = new BufferedReader( new InputStreamReader(System.in)); StringTokenizer tk = new StringTokenizer(bfd.readLine()); int n = Integer.parseInt(tk.nextToken()); int m = Integer.parseInt(tk.nextToken()); int arr[] = new int[1 << n]; tk = new StringTokenizer(bfd.readLine()); for (int i = 0; i < (1 << n); ++i) { arr[i] = Integer.parseInt(tk.nextToken()); } SegmentTree st = new SegmentTree(arr.length, arr, n); int p, b; while (m-- > 0) { tk = new StringTokenizer(bfd.readLine()); p = Integer.parseInt(tk.nextToken()) - 1; b = Integer.parseInt(tk.nextToken()); st.update(0, 0, arr.length - 1, p, b, n % 2); // root always contains the answer System.out.println(st.tree[0]); } } public static void main(String[] args) throws Exception { new XeniaAndBitOperations().run(); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
54ca098ab49711905ce36039ce93e5c5
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
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.StringTokenizer; public class XeniaAndBitOperations { static class Node { int value; Node left, right, parent; public Node(int v) { value = v; } } static int[] arr; static Node[] nodes; public static Node build(int start, int end, int level) { if (start == end) { return nodes[start] = new Node(arr[start]); } int mid = (start + end) / 2; Node left = build(start, mid, level - 1); Node right = build(mid + 1, end, level - 1); Node curr = level % 2 == 0 ? new Node(left.value ^ right.value) : new Node(left.value | right.value); curr.left = left; curr.right = right; left.parent = curr; right.parent = curr; return curr; } public static void main(String[] args) { InputReader r = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = r.nextInt(); int m = r.nextInt(); arr = new int[1 << n]; for (int i = 0; i < arr.length; i++) { arr[i] = r.nextInt(); } nodes = new Node[1 << n]; Node root = build(0, arr.length - 1, n); for (int q = 0; q < m; q++) { int index = r.nextInt() - 1; int val = r.nextInt(); Node curr = nodes[index]; curr.value = val; curr = curr.parent; int level = 1; while (curr != null) { curr.value = level % 2 == 0 ? curr.left.value ^ curr.right.value : curr.left.value | curr.right.value; curr = curr.parent; level++; } out.println(root.value); } out.close(); } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
95a5306e985ed67960aff7bb2e7f3c88
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.IOException; public class CFD { private static final int IN_BUFFER_SIZE = 1 << 16; private static final int OUT_BUFFER_SIZE = 1 << 16; private byte[] input = new byte[IN_BUFFER_SIZE]; private int ix = IN_BUFFER_SIZE; private int bytesRead = ix; private byte[] output = new byte[OUT_BUFFER_SIZE]; private int ox = 0; private void readMore() { try { bytesRead = System.in.read(input, 0, IN_BUFFER_SIZE); if (bytesRead <= 0) throw new RuntimeException(); ix = 0; } catch (IOException e) { throw new RuntimeException(); } } private void flushOut() { System.out.write(output, 0, ox); ox = 0; } private void append(char c) { if (ox == OUT_BUFFER_SIZE) flushOut(); output[ox++] = (byte) c; } private int nextInt() { skipSpaces(); int ret = 0; if (ix == bytesRead) { readMore(); } int sign = 1; if (input[ix] == '-') { sign = -1; ix++; } while (true) { if (ix == bytesRead) { try { readMore(); } catch (RuntimeException e) { return ret; } } if (input[ix] < '0') { break; } ret *= 10; ret += input[ix++] - '0'; } return sign * ret; } int cntSize; private void skipSpaces() { while (true) { if (ix == bytesRead) { readMore(); } if (input[ix] > ' ') break; ix++; } } private char[] nn = new char[32]; private void printInt(int n) { if (n == 0) { append('0'); } else { if (n < 0) { append('-'); n = -n; } int kk = 0; while (n > 0) { nn[kk++] = (char) (n % 10 + '0'); n /= 10; } for (int i = kk - 1; i >= 0; i--) { append(nn[i]); } } } public static void main(String[] args) throws IOException { new CFD().work(); } private void work() { int n = nextInt(); int m = nextInt(); int[] a = new int[1 << (n + 1)]; for (int i = 0; i < 1 << n; i++) { a[i] = nextInt(); } int cur = 1 << n; int start = 0; boolean or = true; while (cur > 1) { for (int i = start; i < start + cur / 2; i++) { int u = (i - start) * 2 + start; int v = (i - start) * 2 + 1 + start; if (or) { a[i + cur] = a[u] | a[v]; } else { a[i + cur] = a[u] ^ a[v]; } } start += cur; cur >>= 1; or = !or; } while (m-- > 0) { int p = nextInt() - 1; int nv = nextInt(); a[p] = nv; int u = p; if ((u & 1) != 0) u--; int v = u + 1; cur = 1 << n; start = 0; or = true; while (cur > 1) { int next = start + (u - start) / 2 + cur; if (or) { a[next] = a[u] | a[v]; } else { a[next] = a[u] ^ a[v]; } u = next; if ((u & 1) != 0) u--; v = u + 1; start += cur; cur >>= 1; or = !or; } printInt(a[(1 << (n + 1)) - 2]); append('\n'); } if (ox > 0) flushOut(); System.out.close(); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
5f11db5ff97de76119f576a079188d5f
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.util.*; import java.io.*; public class Main{ BufferedReader in; StringTokenizer str = null; PrintWriter out; 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()); } int n; int []a, b; public void run() throws Exception{ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); n = nextInt(); int m = nextInt(); b = new int[1<<n]; for(int i=0;i<1<<n;i++){ b[i] = nextInt(); } int cnt = 1; int s = 0; while(cnt < 1<<n) { s+=cnt; cnt<<=1; } s+=cnt; a = new int[s+1]; init(cnt); //System.out.println(Arrays.toString(a)); for(int i=0;i<m;i++){ int p = nextInt()-1; int d = nextInt(); update(cnt, p, d); out.println(a[1]); } out.close(); } private void init(int cnt) { for(int i=0;i<1<<n;i++){ a[cnt+i] = b[i]; } int v = cnt>>1; int operation = 0; for(int i=cnt-1;i>0;i--){ if (operation == 0) { a[i] = a[2*i] | a[2*i+1]; }else{ a[i] = a[2*i] ^ a[2*i+1]; } if (i == v) { operation^=1; v>>=1; } } } private void update(int cnt, int x, int d) { int v = cnt + x; a[v] = d; int operation = 0; while(v > 1) { int neig = v-1; if (v % 2 == 0) { neig = v + 1; } if (operation == 0) { a[v/2] = a[v] | a[neig]; }else{ a[v/2] = a[v] ^ a[neig]; } operation^=1; v/=2; } } public static void main(String args[]) throws Exception{ new Main().run(); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
e20f28399c3bd20a8b967c33abe96b4f
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class XeniaandBitOperations { public static class Node { int value; int sum; public Node(int v, int s) { value = v; sum = s; } } public static Node t[] = new Node[131077 * 4 + 5]; public static int max = 0; public static int a[]; public static int height=0; public static boolean operations[]; public static int getOperation(int v) { return height-((int) (Math.log(v)/Math.log(2))); } public static Node getValue(int v,Node n1,Node n2) { if(operations[getOperation(v)]) { return new Node(n1.value|n2.value, n1.sum+n2.sum); }else { return new Node(n1.value^n2.value, n1.sum+n2.sum); } } public static Node build(int v,int tl,int tr){ if(tl==tr) return t[v]=new Node(a[tl], a[tl]); int tm=(tl+tr)/2; Node l=build(2*v, tl, tm); Node r=build(2*v+1, tm+1, tr); // System.out.println(l.value+" "+r.value+" "+v); return t[v]=getValue(v, l, r); } public static Node update(int v,int l,int r,int tl,int tr,int value) { // System.out.println(v+" "+l+" "+r+" "+tl+" "+tr+" "+t[v].value); if(l>r && tr<a.length) return t[v]; if(l==tl&&r==tr) { return t[v]=new Node(value, value); } int tm=(tr+tl)/2; Node nl=update(2*v, l, Math.min(r, tm), tl, tm, value); Node nr=update(2*v+1,Math.max(l, tm+1) , r, tm+1, tr, value); // System.out.println(l+" "+r+" "+tl+" "+tr+" "+nl.value+" "+nr.value); return t[v]=getValue(v, nl, nr); } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); String st[] = reader.readLine().split(" "); int x =1<<Integer.parseInt(st[0]); int queres = Integer.parseInt(st[1]); st=reader.readLine().split(" "); a = new int[st.length]; for (int i = 0; i < st.length; i++) a[i] = Integer.parseInt(st[i]); max = (a.length) * 4; height=(int) (Math.log(a.length)/Math.log(2)); // System.out.println(height); operations=new boolean [height+1]; operations[0]=false; for(int i=1;i<operations.length;i++) operations[i]=!operations[i-1]; build(1, 0, a.length - 1); for (int i = 0; i < queres; i++) { st = reader.readLine().split(" "); int l = Integer.parseInt(st[0]); int r = Integer.parseInt(st[1]); System.out.println(update(1, l-1, l-1, 0, a.length-1, r).value); } // System.out.println(t[5].value); // System.out.println(update(1, 0, 0, 0, a.length-1, 4).value); // System.out.println(t[2].value); // System.out.println(query(1, 0, 3, 0, 3)); // System.out.println(update(1, 0, 0, 0, 3, 4)); // System.out.println(t[2]); // int queres = Integer.parseInt(reader.readLine()); // for (int i = 0; i < queres; i++) { // st = reader.readLine().split(" "); // int l = Integer.parseInt(st[0]); // int r = Integer.parseInt(st[1]); // // } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
6936f1e511577b69c61cb25a0ac271b6
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class XeniaandBitOperations { public static class Node { int value; int sum; public Node(int v, int s) { value = v; sum = s; } } public static Node t[] = new Node[131077 * 4 + 5]; public static int max = 0; public static int a[]; public static int height=0; public static boolean operations[]; public static int getOperation(int v) { return height-((int) (Math.log(v)/Math.log(2))); } public static Node getValue(int v,Node n1,Node n2) { if(operations[getOperation(v)]) { return new Node(n1.value|n2.value, n1.sum+n2.sum); }else { return new Node(n1.value^n2.value, n1.sum+n2.sum); } } public static Node build(int v,int tl,int tr){ if(tl==tr) return t[v]=new Node(a[tl], a[tl]); int tm=(tl+tr)/2; Node l=build(2*v, tl, tm); Node r=build(2*v+1, tm+1, tr); // System.out.println(l.value+" "+r.value+" "+v); return t[v]=getValue(v, l, r); } public static Node update(int v,int l,int r,int tl,int tr,int value) { // System.out.println(v+" "+l+" "+r+" "+tl+" "+tr+" "+t[v].value); if(l>r) return t[v]; if(l==tl&&r==tr) { return t[v]=new Node(value, value); } int tm=(tr+tl)/2; Node nl=update(2*v, l, Math.min(r, tm), tl, tm, value); Node nr=update(2*v+1,Math.max(l, tm+1) , r, tm+1, tr, value); // System.out.println(l+" "+r+" "+tl+" "+tr+" "+nl.value+" "+nr.value); return t[v]=getValue(v, nl, nr); } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); String st[] = reader.readLine().split(" "); int x =1<<Integer.parseInt(st[0]); int queres = Integer.parseInt(st[1]); st=reader.readLine().split(" "); a = new int[st.length]; for (int i = 0; i < st.length; i++) a[i] = Integer.parseInt(st[i]); max = (a.length) * 4; height=(int) (Math.log(a.length)/Math.log(2)); // System.out.println(height); operations=new boolean [height+1]; operations[0]=false; for(int i=1;i<operations.length;i++) operations[i]=!operations[i-1]; build(1, 0, a.length - 1); for (int i = 0; i < queres; i++) { st = reader.readLine().split(" "); int l = Integer.parseInt(st[0]); int r = Integer.parseInt(st[1]); System.out.println(update(1, l-1, l-1, 0, a.length-1, r).value); } // System.out.println(t[5].value); // System.out.println(update(1, 0, 0, 0, a.length-1, 4).value); // System.out.println(t[2].value); // System.out.println(query(1, 0, 3, 0, 3)); // System.out.println(update(1, 0, 0, 0, 3, 4)); // System.out.println(t[2]); // int queres = Integer.parseInt(reader.readLine()); // for (int i = 0; i < queres; i++) { // st = reader.readLine().split(" "); // int l = Integer.parseInt(st[0]); // int r = Integer.parseInt(st[1]); // // } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
e71ad142a15d1c6ea0baaac9310a36b1
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Integer.*; import static java.lang.Math.*; public class Main{ static class SegmentTree{ private long[] valores; private int izq[], der[], cotas[][], c; private int[] cuentas; private int N, altura[]; private long[] valoresIniciales; static int MAX_ALT=0; public SegmentTree(long[] valoresIniciales){ this.valoresIniciales = valoresIniciales; N=valoresIniciales.length; int n=N*2;valores=new long[n]; c=0; cotas=new int[n][2]; izq=new int[n]; der=new int[n]; MAX_ALT = (int) (Math.log(N)/Math.log(2)); altura = new int[n]; cuentas=new int[N+1]; initTree(0,N, 0); } private int initTree(int desde , int hasta, int alt){ int C = c++; cotas[C][0]=desde;cotas[C][1]=hasta; if(hasta-desde>1){ int p=(hasta+desde)/2; izq[C]=initTree(desde, p,alt+1); der[C]=initTree(p, hasta,alt+1); if((MAX_ALT-alt)%2==1){ valores[C]=valores[izq[C]]|valores[der[C]]; }else valores[C]=valores[izq[C]]^valores[der[C]]; } else valores[C]=valoresIniciales[desde]; altura[C]=alt; return C; } public void setValor(int index, long val){ int C = 0, i = 0; cuentas[C++]=i; for(;cotas[i][1]-cotas[i][0]>1;) if(cotas[izq[i]][0] <= index && cotas[izq[i]][1]>index)cuentas[C++]=(i=izq[i]); else cuentas[C++]=(i=der[i]); valores[i]=val; for(C=C-2;C>=0;C--){ i=cuentas[C]; long l=valores[izq[i]], r=valores[der[i]]; if((MAX_ALT-altura[i])%2==1){ valores[i]=l|r; }else valores[i]=l^r; } } public long getValor(int desde, int hasta ){ return getValor(0,desde,hasta); } public long getValor(int i, int desde, int hasta){ if(cotas[i][0]==desde&&cotas[i][1]==hasta)return valores[i]; if(desde>=cotas[izq[i]][0]&&hasta<=cotas[izq[i]][1])return getValor(izq[i], desde, hasta); if(desde>=cotas[der[i]][0]&&hasta<=cotas[der[i]][1])return getValor(der[i],desde, hasta); if((MAX_ALT-altura[i])%2==1){ return (getValor(izq[i], desde, cotas[izq[i]][1]) | getValor(der[i], cotas[der[i]][0], hasta)); }else return (getValor(izq[i], desde, cotas[izq[i]][1]) ^ getValor(der[i], cotas[der[i]][0], hasta)); } } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer (in.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int cant = (int) pow(2, n); long[] datos = new long[cant]; st = new StringTokenizer(in.readLine()); for(int i=0;i<cant;++i){ datos[i]=Integer.parseInt(st.nextToken()); } SegmentTree sg = new SegmentTree(datos); for(int i=0;i<m;++i){ st = new StringTokenizer(in.readLine()); int desde = Integer.parseInt(st.nextToken()); int hasta = Integer.parseInt(st.nextToken()); //Cada query sg.setValor(desde-1, hasta); System.out.println(sg.getValor(0, cant)); } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
dee454985287e584b128d1ed559407b3
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class D { BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; public void solve() throws IOException { int N = nextInt(); int M = nextInt(); int[][] A = new int[N+1][]; for(int i = 0; i <= N; i++){ A[i] = new int[ 1<<(N-i) ]; } for(int i = 0; i < (1<<N); i++){ A[0][i] = nextInt(); } for(int i = 1; i <= N; i++){ for(int j = 0; j < (1<<(N-i)); j++){ if( i % 2 == 1) A[i][j] = A[i-1][j*2] | A[i-1][j*2+1]; else A[i][j] = A[i-1][j*2] ^ A[i-1][j*2+1]; } } for(int m = 0; m < M; m++){ int P = nextInt()-1; int B = nextInt(); A[0][P] = B; for(int i = 1; i <= N; i++){ if( i % 2 == 1) A[i][ P>>i ] = A[i-1][ (P>>i)*2 ] | A[i-1][ (P>>i)*2 + 1 ]; else A[i][ P>>i ] = A[i-1][ (P>>i)*2 ] ^ A[i-1][ (P>>i)*2 + 1 ]; } // // A[0][P-1] = B; // for(int i = 1; i <= N; i++){ // for(int j = 0; j < (1<<(N-i)); j++){ // if( i % 2 == 1) // A[i][j] = A[i-1][j*2] | A[i-1][j*2+1]; // else // A[i][j] = A[i-1][j*2] ^ A[i-1][j*2+1]; // } // } out.println(A[N][0]); } } /** * @param args */ public static void main(String[] args) { new D().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
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
6d4d5cd9ec111e3ca11df32ec7233adc
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Mohammad Al-Najjar * @since 11/13/2014 */ public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int n = Integer.parseInt(tokenizer.nextToken()); int m = Integer.parseInt(tokenizer.nextToken()); int[] a = new int[1 << n]; tokenizer = new StringTokenizer(reader.readLine()); for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(tokenizer.nextToken()); } SegmentTreeRMQ st = new SegmentTreeRMQ(a); for (int i = 0; i < m; i++) { tokenizer = new StringTokenizer(reader.readLine()); int p = Integer.parseInt(tokenizer.nextToken()); int b = Integer.parseInt(tokenizer.nextToken()); st.update(p - 1, b); System.out.println(st.st[1]); } } public static class SegmentTreeRMQ { public int M, H, N; public int[] st; public SegmentTreeRMQ(int n) { N = n; M = Integer.highestOneBit(Math.max(N - 1, 1)) << 2; H = M >>> 1; st = new int[M]; Arrays.fill(st, 0, M, Integer.MAX_VALUE); } public SegmentTreeRMQ(int[] a) { N = a.length; M = Integer.highestOneBit(Math.max(N - 1, 1)) << 2; H = M >>> 1; st = new int[M]; for (int i = 0; i < N; i++) { st[H + i] = a[i]; } Arrays.fill(st, H + N, M, Integer.MAX_VALUE); for (int i = H - 1; i >= 1; i--) propagate(i); } public void update(int pos, int x) { st[H + pos] = x; for (int i = (H + pos) >>> 1; i >= 1; i >>>= 1) propagate(i); } private void propagate(int i) { int lev = Integer.numberOfTrailingZeros(H / Integer.highestOneBit(i)); if ((lev & 1) == 1) { st[i] = st[2 * i] | st[2 * i + 1]; } else { st[i] = st[2 * i] ^ st[2 * i + 1]; } } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
db8c31221a8ea72d4d6f9bd9715ae032
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public BufferedReader input; public PrintWriter output; public StringTokenizer in = new StringTokenizer(""); long tree []; long arr []; public static void main(String[] args) throws NumberFormatException, IOException { new Main(); } Main() throws NumberFormatException, IOException{ // input = new BufferedReader(new FileReader("input.txt")); input = new BufferedReader(new InputStreamReader(System.in)); output = new PrintWriter(System.out); // output = new PrintWriter(new FileWriter("output.txt")); int n = nextInt(); int m = nextInt(); int size = (int)Math.pow(2, n); arr = new long [size]; tree = new long [2*size]; for (int i=0; i<size; i++){ arr[i] = nextLong(); } build(1, 0, size-1, n); for (int i=0; i<m; i++){ int place = nextInt()-1; long value = nextLong(); update(1, 0, size-1, place, value, n); output.println(tree[1]); } output.close(); } private void update(int v, int tl, int tr, int place, long value, int lvl) { if (tl == tr){ tree[v] = value; } else { int tm = (tl + tr) / 2; if (place <= tm){ update(v*2, tl, tm, place, value, lvl-1); } else { update(v*2+1, tm+1, tr, place, value, lvl-1); } if (lvl % 2 == 0){ tree[v] = tree[v*2] ^ tree[v*2+1]; } else { tree[v] = tree[v*2] | tree[v*2+1]; } } } private void build(int v, int tl, int tr, int lvl) { if (tl == tr){ tree[v] = arr[tl]; } else { int tm = (tr + tl) / 2; build(2*v, tl, tm, lvl-1); build(2*v+1, tm+1, tr, lvl-1); if (lvl % 2 == 0){ tree[v] = tree[2*v] ^ tree[2*v+1]; } else { tree[v] = tree[2*v] | tree[2*v+1]; } } } private int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextString()); } private long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextString()); } private String nextString() throws IOException { while (!in.hasMoreTokens()){ String st = input.readLine(); in = new StringTokenizer(st); } return in.nextToken(); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
af31fccc02890ae70424ec5a1b6d298c
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class D { static Scanner in; static int next() throws Exception {return in.nextInt();}; // static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;} // static BufferedReader in; static PrintWriter out; public static void main(String[] args) throws Exception { in = new Scanner(System.in); // in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = next(); int leng = (int)Math.pow(2,n); int m = next(); int len = leng; int a[][] = new int[n+1][]; for (int i = 0;i <= n;i++) { a[i] = new int[leng]; leng /= 2; } for (int i = 0;i < len;i++) a[0][i] = next(); for (int i = 1;i <= n;i++) { for (int j = 0;j < a[i].length;j++) { if (i%2 == 1) { a[i][j] = a[i-1][2*j]|a[i-1][2*j+1]; } else a[i][j] = a[i-1][2*j]^a[i-1][2*j+1]; } } for (int i = 0;i < m;i++) { int p = next()-1, b = next(); a[0][p] = b; for (int j = 1;j <= n;j++) { p/=2; if (j%2 == 1) { a[j][p] = a[j-1][p*2]|a[j-1][p*2+1]; } else a[j][p] = a[j-1][p*2]^a[j-1][p*2+1]; } out.println(a[n][0]); } out.println(); out.close(); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
24cf88ecfc55f102ac09a3c96cd27889
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.PriorityQueue; import java.util.ArrayList; 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.math.BigInteger; import java.io.InputStream; import java.util.PriorityQueue; import java.util.HashMap; import java.util.Stack; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.TreeSet; import java.math.BigDecimal; import java.util.Comparator; import java.util.BitSet; import java.util.Random; import java.util.ArrayDeque; import java.math.*; public class Main{ public static void main(String []args)throws IOException{ InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); //BufferedReader x=new BufferedReader(new InputStreamReader(System.in)); OutputWriter outt = new OutputWriter(outputStream); StringBuilder out=new StringBuilder(); long start1=System.currentTimeMillis(); /*int n=in.readInt(); long mod=3046201; long arr[]=new long[n]; long fact[]=new long[3000001]; fact[0]=1; for(int i=1;i<3000001;i++){ fact[i]=fact[i-1]*i; fact[i]=fact[i]%mod; } for(int i=0;i<n;i++) arr[i]=in.readInt(); int q=in.readInt(); Tree root=initialise(arr,0,n-1); while(q-->0){ String qs=in.readString(); int l=in.readInt()-1; int r=in.readInt(); if(qs.equals("change")){ long diff=r-arr[l]; arr[l]=r; update(root,l,diff); } //else if(l==r-1) out.append("1\n"); else{r=r-1; long sum=getSum(root,l,r); // System.out.println(sum); int m=r-l+1; long a2=sum%m; long a1=m-a2; long b1=sum/m; long b2=b1+1; long denom=fact[(int)(m-a1)]; denom=denom*fact[(int)a1]; denom=denom%mod; denom=denom*(pow(fact[(int)b1],a1)); denom=denom%mod; denom=denom*(pow(fact[(int)b2],a2)); denom=denom%mod; long num=fact[(int)m]; num=num*fact[(int)sum]; num=num%mod; long num2=pow(denom,mod-2); long ans=num*num2; ans=ans%mod; // System.out.println("mm "+m+" a1 "+a1+" a2 "+a2+" b1 "+b1+" b2 "+b2); out.append(ans+"\n"); } } // boolean coins[]=new boolean[n]; // print(root); /*update_add(root,0,2); System.out.println("after update 0 2"); print(root); System.out.println("query====" +count(root,0,4)); System.out.println("query====" +count(root,0,1)); update_add(root,0,1); System.out.println("after update 0 1"); System.out.println("query====" +count(root,0,4)); System.out.println("query====" +count(root,0,1)); System.out.println("query====" +count(root,0,2)); System.out.println("query====" +count(root,2,2)); print(root); //for(int i=0;i) // outt.print(out); //outt.close();*/ /*for(int i=0;i<q;i++){ int type=in.readInt(); int a=in.readInt(); int b=in.readInt(); if(type==0){flip(root,a,b);} else{int count=count(root,a,b);out.append(count+"\n");} }*/ int k=in.readInt(); int m=in.readInt(); int N=(int)pow(2,k); long arr[]=new long[N]; for(int i=0;i<N;i++) arr[i]=in.readInt(); Tree root=initialise(arr,0,N-1); while(m-->0){ int p=in.readInt()-1; int b=in.readInt(); update(root,p,b); out.append(root.val+"\n"); } outt.print(out); outt.close(); } static void print(Tree root){ System.out.println("INTERVAL "+ root.l+" "+root.r); System.out.println("value"+ root.val); System.out.println("****************"); if(root.left!=null) print(root.left); if(root.right!=null) print(root.right); } static Tree initialise(long arr[],int lef,int righ){ if(lef==righ){return new Tree(lef,righ,null,null,arr[lef],0);} else{ int mid=(lef+righ)/2; Tree a=initialise(arr,lef,mid); Tree b=initialise(arr,mid+1,righ); int h=a.height+1; if(h%2==0) return new Tree(lef,righ,a,b,a.val^b.val,h); else return new Tree(lef,righ,a,b,a.val|b.val,h); } } static long getSum(Tree root,int qs,int qe){ if (qs <= root.l && qe >= root.r) return root.val; if (root.r < qs || root.l > qe) return 0; return (getSum(root.left,qs,qe)+getSum(root.right,qs,qe)); } static void update(Tree root,int i,int ch){ if(i==root.l&&i==root.r) {root.val=ch;return;} int mid=(root.l+root.r)/2; if(i>mid) update(root.right,i,ch); else update(root.left,i,ch); if(root.height%2==0) root.val=root.left.val^root.right.val; else root.val=root.left.val|root.right.val; } /* static Tree clone(Tree root){ return new Tree(root.l,root.r,root.left,root.right,root.val); }*/ static long pow(long n, long exp){ long prod = 1; while (exp > 0){ if ((exp & 1) != 0) {prod *= n;prod=prod;} n*=n;n=n; exp >>= 1; } return prod; } static long modExp(long b, long e, long m) { long remainder; long x = 1; while (e != 0) { remainder = e % 2; e= e/2; if (remainder == 1) x = (x * b) % m; b= (b * b) % m; // New base equal b^2 % m } return x; } } class Tree{ Tree left;Tree right; int l; int r; long val; int height; Tree(){l=0;r=0;val=0;} Tree(int lef,int righ,Tree a, Tree b,long data,int ht){l=lef;r=righ;val=data;left=a;right=b;height=ht;} } class IntegerUtils { public static long[] generateBinomialRow(int n, long module) { if (n < 0) return new long[0]; long[] result = generateReverse(n + 1, module); result[0] = 1; for (int i = 1; i <= n; i++) result[i] = result[i - 1] * (n - i + 1) % module * result[i] % module; return result; } public static long[] generateReverse(int upTo, long module) { long[] result = new long[upTo]; if (upTo > 1) result[1] = 1; for (int i = 2; i < upTo; i++) result[i] = (module - module / i * result[((int) (module % i))] % module) % module; return result; } public static long factorial(int n, long mod) { long result = 1; for (int i = 2; i <= n; i++) result = result * i % mod; return result % mod; } public static long binomialCoefficient(int n, int m, long mod) { if (m < 0 || m > n) return 0; if (2 * m > n) m = n - m; long result = 1; for (int i = n - m + 1; i <= n; i++) result = result * i % mod; return result * BigInteger.valueOf(factorial(m, mod)).modInverse(BigInteger.valueOf(mod)).longValue() % mod; } } class d{ int val;int p; d(){val=0;p=0;} d(int v,int par){val=v;p=par;} } class road{ int begin;int end; road(int i,int j){this.begin=i;this.end=j;} road(){begin=0;end=0;} } class song{ int band;int len; song(int i,int j){this.band=i;this.len=j;} song(){band=0;len=0;} } 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 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 String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public 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); } } 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
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
7cabfd9e68acc66ddf599a5797b83d4a
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { // System.out.println(4|5); // Scanner in = new Scanner(System.in); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[]s=in.readLine().split(" "); int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]); int total = 1 << n; ArrayList<Integer>[] list = new ArrayList[n + 1]; for (int i = 0; i < n + 1; i++) list[i] = new ArrayList<Integer>(); s=in.readLine().split(" "); for (int i = 0; i < total; i++) list[0].add(Integer.parseInt(s[i])); for (int i = 0; i < n; i++) { for (int j = 0; j < list[i].size(); j += 2) { int temp = list[i].get(j) | list[i].get(j + 1); if (i % 2 == 1) temp = list[i].get(j) ^ list[i].get(j + 1); // System.out.println(temp); list[i + 1].add(temp); } } // System.out.println(list[list.length-1].get(0)); for (int i = 0; i < m; i++) { s=in.readLine().split(" "); int pos = Integer.parseInt(s[0]) - 1; int value = Integer.parseInt(s[1]); int level = 0; list[0].set(pos, value); while (level < n) { if (pos % 2 == 0) { if (level % 2 == 0) value |= list[level].get(pos + 1); else value ^= list[level].get(pos + 1); } else { if (level % 2 == 0) value |= list[level].get(pos - 1); else value ^= list[level].get(pos - 1); } pos /= 2; level++; list[level].set(pos, value); } // System.out.println("cc"); System.out.println(value); } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
10c4b88eeaea53120ac428c4fd28e476
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.util.*; public class Main { static int[][] nums; public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); int M = in.nextInt(); nums = new int[N+1][]; nums[0] = new int[1<<N]; for (int i=0; i<nums[0].length; i++) nums[0][i] = in.nextInt(); for (int i=1; i<=N; i++) { nums[i] = new int[nums[i-1].length>>1]; for (int j=0; j<nums[i].length; j++) if ((i&1)==1) nums[i][j] = nums[i-1][j<<1] | nums[i-1][(j<<1)+1]; else nums[i][j] = nums[i-1][j<<1] ^ nums[i-1][(j<<1)+1]; //System.out.println(Arrays.toString(nums[i])); } for (int t=0; t<M; t++) { int p = in.nextInt()-1; int b = in.nextInt(); nums[0][p] = b; for (int i=1; i<=N; i++) { p>>=1; if ((i&1)==1) nums[i][p] = nums[i-1][p<<1] | nums[i-1][(p<<1)+1]; else nums[i][p] = nums[i-1][p<<1] ^ nums[i-1][(p<<1)+1]; } System.out.println(nums[N][0]); } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
7b86108614171f8e2f04af1644544604
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.StringTokenizer; public class Main { static boolean file = false; static HashMap<Integer, Integer> map; public static void main(String[] args) throws IOException { BufferedWriter out = new BufferedWriter(new OutputStreamWriter( System.out)); // code starts here if (file) { Reader.init(new FileInputStream(new File("test.in"))); } else Reader.init(System.in); map = new HashMap<Integer, Integer>(); int n = Reader.nextInt(); int m = Reader.nextInt(); int[] A = new int[(int) Math.pow(2, n)]; for (int i = 0; i < (int) Math.pow(2, n); i++) { A[i] = Reader.nextInt(); } // build segment treee int[] t = st_build(A.length, A); for (int i = 0; i < m; i++) { int p = Reader.nextInt() - 1; int val = Reader.nextInt(); t[map.get(p)]=val; st_update(t,A,map.get(p)); // A[p] = val; // t = st_build(A.length, A); System.out.println(t[1]); } // output out.close(); } public static int st_build_rec(int[] tree, int[] A, int currIndex, int L, int R) { if (L == R) { map.put(L, currIndex); tree[currIndex] = A[L]; return 1; } int leftChildIndexTree = 2 * currIndex; int rightChildIndexTree = 2 * currIndex + 1; int op = st_build_rec(tree, A, leftChildIndexTree, L, (L + R) / 2); st_build_rec(tree, A, rightChildIndexTree, (L + R) / 2 + 1, R); int leftChildValue = tree[leftChildIndexTree]; int rightChildValue = tree[rightChildIndexTree]; if (op == 1) { tree[currIndex] = leftChildValue | rightChildValue; return 2; } else { tree[currIndex] = leftChildValue ^ rightChildValue; return 1; } } public static int[] st_build(int N, int[] A) { int tree_len = (int) (2 * Math.pow(2, Math.log10(N) * 1.0 / Math.log10(2) * 1.0)); int[] t = new int[tree_len]; st_build_rec(t, A, 1, 0, A.length - 1); return t; } public static int st_rmq(int[] t, int[] A, int currIndex, int queryL, int queryR, int currL, int currR) { if (queryL > currR || queryR < currL) { return -1; } if (queryL <= currL && currR <= queryR) { return t[currIndex]; } int indexLeft = st_rmq(t, A, 2 * currIndex, queryL, queryR, currL, (currL + currR) / 2); int indexRight = st_rmq(t, A, 2 * currIndex + 1, queryL, queryR, (currL + currR) / 2 + 1, currR); if (indexLeft == -1) return indexRight; if (indexRight == -1) return indexLeft; int valueRight = A[indexRight]; int valueLeft = A[indexLeft]; return (valueRight < valueLeft) ? indexRight : indexLeft; } public static void st_update(int[] t, int[] A, int currIndex) { int parentIndex = currIndex / 2; int opr = 1; while (parentIndex >= 1) { int leftIndex = parentIndex * 2; int rightIndex = parentIndex * 2 + 1; int leftValue = t[leftIndex]; int rightValue = t[rightIndex]; if (opr == 1) { t[parentIndex] = leftValue | rightValue; opr = 2; } else { t[parentIndex] = leftValue ^ rightValue; opr = 1; } parentIndex /= 2; } } static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { // TODO add check for eof if necessary tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
67cb625096d3b31d1e70c07e61c7883f
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.util.*; import java.io.*; public class cfa { static long mod = 1000000009; public static void main(String[] args) throws IOException { // Scanner input = new Scanner(new File("input.txt")); // PrintWriter out = new PrintWriter(new File("output.txt")); input.init(System.in); PrintWriter out = new PrintWriter((System.out)); int n = input.nextInt(), m = input.nextInt(); int[][] data = new int[n+1][(1<<n)]; for(int i = 0; i<(1<<n); i++) data[0][i] = input.nextInt(); int count = (1<<n); for(int i = 0; i<n; i++) { count /= 2; for(int j = 0; j<count; j++) { if((i&1) == 0) data[i+1][j] = data[i][2*j] | data[i][2*j+1]; else data[i+1][j] = data[i][2*j] ^ data[i][2*j+1]; } } for(int i = 0; i<m; i++) { int p = input.nextInt()-1, b = input.nextInt(); data[0][p] = b; int at = p; for(int j = 0; j<n; j++) { if(j%2 == 0) { data[j+1][at/2] = at%2 == 0 ? (data[j][at] | data[j][at+1]) : (data[j][at] | data[j][at-1]); } else { data[j+1][at/2] = at%2 == 0 ? (data[j][at] ^ data[j][at+1]) : (data[j][at] ^ data[j][at-1]); } at = at/2; } out.println(data[n][0]); } out.close(); } static long pow(long x, long p) { if (p == 0) return 1; if ((p & 1) > 0) { return (x * pow(x, p - 1)) % mod; } long sqrt = pow(x, p / 2); return (sqrt * sqrt) % mod; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static class input { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { // TODO add check for eof if necessary tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static String nextLine() throws IOException { return reader.readLine(); } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
6d86b1432f377dd48f208efa3e336bab
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class XeniaandBitOperations { static int[] tree; static int[] a; static void build(int x, int y, int node, int operation) { if (x == y) { tree[node] = a[x]; return; } int mid = (x + y) / 2; build(x, mid, 2 * node, operation ^ 1); build(mid + 1, y, 2 * node + 1, operation ^ 1); if (operation == 1) tree[node] = tree[2 * node] | tree[2 * node + 1]; else tree[node] = tree[2 * node] ^ tree[2 * node + 1]; } static void update(int x, int y, int index, int val, int node, int operation) { if (index < x || index > y) return; if (x == y) { tree[node] = val; a[index] = val; return; } int mid = (x + y) / 2; update(x, mid, index, val, 2 * node, operation ^ 1); update(mid + 1, y, index, val, 2 * node + 1, operation ^ 1); if (operation == 1) tree[node] = tree[2 * node] | tree[2 * node + 1]; else tree[node] = tree[2 * node] ^ tree[2 * node + 1]; } public static void main(String[] args) throws IOException { BufferedReader buf = new BufferedReader( new InputStreamReader(System.in)); StringTokenizer str = new StringTokenizer(buf.readLine()); int n = Integer.parseInt(str.nextToken()); int m = Integer.parseInt(str.nextToken()); a = new int[1 << n]; int operation = n % 2; int h = n + 2; tree = new int[1 << h]; StringBuilder ans = new StringBuilder(""); str = new StringTokenizer(buf.readLine()); for (int i = 0; i < a.length; i++) a[i] = Integer.parseInt(str.nextToken()); build(0, a.length - 1, 1, operation); while (m-- > 0) { str = new StringTokenizer(buf.readLine()); int index = Integer.parseInt(str.nextToken())-1; int val = Integer.parseInt(str.nextToken()); update(0, a.length - 1, index, val, 1, operation); ans.append(tree[1] + "\n"); } System.out.print(ans); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
8418ac0edf0d34e8e4b601cc03064a39
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class D { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; int n = nextInt(); int m = nextInt(); int len = 1<< n; int[] a = new int[len]; for(int i = 0; i < len;i++) a[i] = nextInt(); Fast_SegmentTree seg = new Fast_SegmentTree(len); boolean ex = false; for(int i = n; i > 1;i--) ex = !ex; seg.build(a , ex); StringBuilder str = new StringBuilder(); for(int i = 0; i < m;i++) { int p = nextInt()-1; int b = nextInt(); int pre = seg.get(p, p, ex); int newV = seg.update(p, b, ex); // str.append(seg.get(0, n-1, ex)+"\n"); str.append(newV+"\n"); // seg.update(p, pre, ex); } System.out.print(str); } static BufferedReader reader; static StringTokenizer tokenizer; 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 (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } } class Fast_SegmentTree { int n; int[] t; public Fast_SegmentTree(int MAXN) { n = MAXN; t = new int[4*MAXN]; } //---------------------------------------------------- // ************* Customization Section *************** //---------------------------------------------------- final int IDENTITY = 0; // function to apply on the tree public int func(int a ,int b ,boolean ex) { if(ex) return a^b; else return a|b; } //---------------------------------------------------- // ************* Public Interfaces *************** //---------------------------------------------------- public void build(int[] a , boolean ex) { build(a , 1 , 0 , n-1 , ex); } public int get(int l , int r ,boolean ex) { return get(1, 0, n-1, l, r,ex); } public int update (int pos, int new_val , boolean ex) { return update(1, 0, n-1, pos, new_val,ex); } //---------------------------------------------------- // ************* Actual Implementation *************** //---------------------------------------------------- /** * "Main" should call this method by * @param a = array to build tree for * @param v = 1 * @param tl = 0 * @param tr = n-1 */ private void build (int a[], int v, int tl, int tr ,boolean ex) { if (tl == tr) t[v] = a[tl]; else { int tm = ((tl + tr) >> 1); build (a, (v<<1) , tl, tm , !ex); build (a, ((v<<1)|1) , tm+1, tr , !ex); t[v] = func(t[(v<<1)] , t[((v<<1)|1)] , ex); } } /** * "Main" should call this method by * @param v = 1 * @param tl = 0 * @param tr = n-1 * @param l = left of segment want to get * @param r = right of segment want to get */ private int get (int v, int tl, int tr, int l, int r, boolean ex) { if (l > r) return IDENTITY; if (l == tl && r == tr) return t[v]; int tm = ((tl + tr) >> 1); return func( get ((v<<1), tl, tm, l, Math.min(r,tm) , !ex) , get ( ((v<<1)|1) , tm+1, tr, Math.max(l,tm+1), r , !ex) , ex); } private int update (int v, int tl, int tr, int pos, int new_val, boolean ex) { if (tl == tr) return t[v] = new_val; else { int tm = ((tl + tr) >> 1); if (pos <= tm) update ( (v<<1), tl, tm, pos, new_val , !ex); else update ( ((v<<1)|1) , tm+1, tr, pos, new_val , !ex); return t[v] = func(t[v<<1] , t[(v<<1)|1] , ex); } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
b294997b469962fef349423981da7b00
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.*; import java.util.*; public class BinaryAssignments { public static void main(String[] args) throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(rd.readLine()); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); A = new int[(1 << n)]; tree = new int[(1<<(n+1))+1]; orOrXor = new boolean[(1<<(n+1))+1]; st = new StringTokenizer(rd.readLine()); for (int i = 0; i < (1 << n); i++) A[i] = Integer.parseInt(st.nextToken()); build(1, 0, (1 << n) - 1); for(int i=0; i<m; i++){ st = new StringTokenizer(rd.readLine()); int index = Integer.parseInt(st.nextToken()), value = Integer.parseInt(st.nextToken()); update(1, 0, (1<<n)-1, index-1, value); pw.println(tree[1]); } pw.flush(); } static int build(int v, int a, int b) { if (a == b) { tree[v] = A[a]; orOrXor[v] = false; return tree[v]; } int left = build(2 * v, a, (a + b) / 2); int right = build(2 * v + 1, (a + b) / 2 + 1, b); tree[v] = orOrXor[2 * v] ? (left ^ right) : (left | right); orOrXor[v] = !orOrXor[2 * v]; return tree[v]; } static void update(int v, int a, int b, int index, int value) { if(a==b){ tree[v] = value; return; } if(index <= (a+b)/2) update(2*v, a, (a+b)/2, index, value); else update(2*v+1, (a+b)/2+1, b, index, value); tree[v] = orOrXor[2*v]? (tree[2*v] ^ tree[2*v+1]) : (tree[2*v] | tree[2*v+1]); } static boolean[] orOrXor; static int[] tree; static int n, m; static int[] A; }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
57b72eaadb737e92e53c680efc6ab69c
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.InputStreamReader; import java.io.PrintWriter; import static java.lang.Math.*; import java.util.ArrayList; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author pttrung */ public class C { public static long Mod = 1000000009; public static void main(String[] args) { Scanner in = new Scanner(new InputStreamReader(System.in)); int n = in.nextInt(); int m = in.nextInt(); Node root = new Node(0, (1 << n) - 1, (n % 2 != 0)); for (int i = 0; i < 1 << n; i++) { add(root , i , in.nextInt()); } //System.out.println(root.value); PrintWriter out = new PrintWriter(System.out); for(int i = 0; i < m ; i++){ int index = in.nextInt() - 1; int val = in.nextInt(); add(root , index,val); out.println(root.value); } out.close(); } public static void add(Node pa , int index , int value){ if(pa.min == pa.max && pa.min == index){ pa.value = value; // System.out.println(pa.value); return ; } int mid = (pa.min + pa.max)/2; Node node; if(mid >= index){ if(pa.left != null){ node = pa.left; }else{ node = new Node(pa.min, mid, !pa.or); pa.left = node; } }else { if(pa.right != null){ node = pa.right; }else{ node = new Node(mid + 1 , pa.max , !pa.or); pa.right = node; } } add(node , index , value); if(pa.left != null && pa.right != null){ if(pa.or){ pa.value = pa.left.value | pa.right.value; }else{ pa.value = pa.left.value ^ pa.right.value; } //System.out.println(pa.value); } } static class Node { int value; int min, max; Node left, right; boolean or; public Node(int min, int max, boolean or) { this.min = min; this.max = max; this.or = or; } } static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); //System.out.println(val); if (b % 2 == 0) { return val * val % Mod; } else { return val * val * a % Mod; } } static void check(Point a, Point b, ArrayList<Point> p, Point[] rec, int index) { for (int i = 0; i < 4; i++) { int m = (i + index) % 4; int j = (i + 1 + index) % 4; Point k = intersect(minus(b, a), minus(rec[m], rec[j]), minus(rec[m], a)); if (k.x >= 0 && k.x <= 1 && k.y >= 0 && k.y <= 1) { Point val = new Point(k.x * minus(b, a).x, k.x * minus(b, a).y); p.add(add(val, a)); // System.out.println(a + " " + b + " " + rec[i] + " " + rec[j]); // System.out.println(add(val, a)); } } } static Point intersect(Point a, Point b, Point c) { double D = cross(a, b); if (D != 0) { return new Point(cross(c, b) / D, cross(a, c) / D); } return null; } static Point convert(Point a, double angle) { double x = a.x * cos(angle) - a.y * sin(angle); double y = a.x * sin(angle) + a.y * cos(angle); return new Point(x, y); } static Point minus(Point a, Point b) { return new Point(a.x - b.x, a.y - b.y); } static Point add(Point a, Point b) { return new Point(a.x + b.x, a.y + b.y); } static double cross(Point a, Point b) { return a.x * b.y - a.y * b.x; } static class Point { double x, y; Point(double x, double y) { this.x = x; this.y = y; } @Override public String toString() { return "Point: " + x + " " + y; } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
c4da9b051e4e3f5da3ff1be1bc3f57f4
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.*; import java.util.*; public class D { int[] segt, seq; int n, m; void update(int index, int lvl, int st, int end, int id, int val){ if(st==end){ segt[index]=val; return; } int mid = (st+end)>>1; if(id<=mid) update(index<<1, lvl+1, st, mid, id, val); else update(index<<1|1, lvl+1, mid+1, end, id, val); if((lvl&1) != (n&1)) segt[index] = segt[index*2] | segt[index*2 + 1]; else segt[index] = segt[index*2] ^ segt[index*2 + 1]; } void build(int index, int lvl, int st, int end){ if(st==end){ segt[index] = seq[st]; return; } int mid = (st+end)>>1; build(index*2, lvl+1, st, mid); build(index*2 + 1, lvl+1, mid+1, end); if((lvl&1) != (n&1)) segt[index] = segt[index*2] | segt[index*2 + 1]; else segt[index] = segt[index*2] ^ segt[index*2 + 1]; } void run() throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String[] toks = bf.readLine().trim().split("[ ]+"); n = Integer.parseInt(toks[0]); m = Integer.parseInt(toks[1]); toks = bf.readLine().trim().split("[ ]+"); seq = new int[1<<n|1]; segt = new int[1<<(n+1)|1]; for(int i=1; i<=1<<n; i++) seq[i] = Integer.parseInt(toks[i-1]); build(1, 0, 1, 1<<n); // for(int i=1; i<segt.length; i++) System.out.print(segt[i] + ", "); // System.out.println(); for(int i=0; i<m; i++){ toks = bf.readLine().trim().split("[ ]+"); int p = Integer.parseInt(toks[0]); int b = Integer.parseInt(toks[1]); update(1, 0, 1, 1<<n, p, b); System.out.println(segt[1]); } } public static void main(String[] args) throws IOException { new D().run(); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
afce597dd356beddd83e458d0078debe
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.*; import java.util.*; public class D { int[] segt, seq; int n, m; void update(int index, int lvl, int st, int end, int id, int val){ if(st==end){ segt[index]=val; return; } int mid = (st+end)>>1; if(id<=mid) update(index<<1, lvl+1, st, mid, id, val); else update(index<<1|1, lvl+1, mid+1, end, id, val); if((lvl&1) != (n&1)) segt[index] = segt[index*2] | segt[index*2 + 1]; else segt[index] = segt[index*2] ^ segt[index*2 + 1]; } void build(int index, int lvl, int st, int end){ if(st==end){ segt[index] = seq[st]; return; } int mid = (st+end)>>1; build(index*2, lvl+1, st, mid); build(index*2 + 1, lvl+1, mid+1, end); if((lvl&1) != (n&1)) segt[index] = segt[index*2] | segt[index*2 + 1]; else segt[index] = segt[index*2] ^ segt[index*2 + 1]; } void run() throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String[] toks = bf.readLine().trim().split("[ ]+"); n = Integer.parseInt(toks[0]); m = Integer.parseInt(toks[1]); toks = bf.readLine().trim().split("[ ]+"); seq = new int[1<<n|1]; segt = new int[1<<(n+1)|1]; for(int i=1; i<=1<<n; i++) seq[i] = Integer.parseInt(toks[i-1]); build(1, 0, 1, 1<<n); // for(int i=1; i<segt.length; i++) System.out.print(segt[i] + ", "); // System.out.println(); for(int i=0; i<m; i++){ toks = bf.readLine().trim().split("[ ]+"); int p = Integer.parseInt(toks[0]); int b = Integer.parseInt(toks[1]); update(1, 0, 1, 1<<n, p, b); System.out.println(segt[1]); } } public static void main(String[] args) throws IOException { new D().run(); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
eb2fbae8869c992bfb19a9ab7ba291a2
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.*; import java.util.*; import java.awt.geom.*; public class Main { static BufferedReader br = new BufferedReader( new InputStreamReader(System.in) ); static StringTokenizer st = new StringTokenizer(""); static String next() throws Exception { while ( !st.hasMoreTokens() ) st = new StringTokenizer( br.readLine() ); return st.nextToken(); } public static void main(String [] asda) throws Exception { PrintWriter out = new PrintWriter( new BufferedOutputStream(System.out) ); // int n = Integer.parseInt( next() ); int N = 1 << n; int M = Integer.parseInt( next() ); int size = 1; while ( N > 0 ) { size += N; N >>= 1; } N = 1 << n; tree = new int [size]; for (int i = 0; i < N; i++) { tree[size - N + i] = Integer.parseInt( next() ); } for (int i = 0; i < N; i+=2) { build((size - N + i) >> 1, 0); } while (M-- > 0) { int i = Integer.parseInt( next() ); int j = Integer.parseInt( next() ); tree[ size - N + i - 1 ] = j; build( (size - N + i - 1) >> 1, 0 ); // out.println( Arrays.toString(tree) ); out.println( tree[1] ); } out.flush(); } static int tree []; static void build(int N, int op) { if ( N == 0 ) return; if ( (op&1) == 0 ) tree[N] = tree[N << 1] | tree[N*2 + 1]; else tree[N] = tree[N << 1] ^ tree[N*2 + 1]; build(N >> 1, op + 1); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
eab263f9e9ef4f6df3821bf45773d8cd
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.*; import java.util.*; import java.awt.geom.*; public class Main { static BufferedReader br = new BufferedReader( new InputStreamReader(System.in) ); static StringTokenizer st = new StringTokenizer(""); static String next() throws Exception { while ( !st.hasMoreTokens() ) st = new StringTokenizer( br.readLine() ); return st.nextToken(); } public static void main(String [] asda) throws Exception { PrintWriter out = new PrintWriter( new BufferedOutputStream(System.out) ); // int n = Integer.parseInt( next() ); int N = 1 << n; int M = Integer.parseInt( next() ); int size = 1; while ( N > 0 ) { size += N; N >>= 1; } N = 1 << n; tree = new int [size]; for (int i = 0; i < N; i++) { tree[size - N + i] = Integer.parseInt( next() ); } for (int i = 0; i < N; i+=2) { build((size - N + i) >> 1, 0); } while (M-- > 0) { int i = Integer.parseInt( next() ); int j = Integer.parseInt( next() ); tree[ size - N + i - 1 ] = j; build( (size - N + i - 1) >> 1, 0 ); // out.println( Arrays.toString(tree) ); out.println( tree[1] ); } out.flush(); } static int tree []; static void build(int N, int op) { if ( N == 0 ) return; if ( (op&1) == 0 ) tree[N] = tree[N << 1] | tree[N*2 + 1]; else tree[N] = tree[N << 1] ^ tree[N*2 + 1]; build(N >> 1, op + 1); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
1571af25b9415346a9960b3a54e444f1
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.*; import java.util.*; public class CodeForces339D { int[] segmentTree, sequence; int n, m; void update(int index, int lvl, int st, int end, int id, int val) { if (st == end) { segmentTree[index] = val; return; } int mid = (st + end) >> 1; if (id <= mid) update(index << 1, lvl + 1, st, mid, id, val); else update(index << 1 | 1, lvl + 1, mid + 1, end, id, val); if ((lvl & 1) != (n & 1)) segmentTree[index] = segmentTree[index * 2] | segmentTree[index * 2 + 1]; else segmentTree[index] = segmentTree[index * 2] ^ segmentTree[index * 2 + 1]; } void build(int index, int lvl, int st, int end) { if (st == end) { segmentTree[index] = sequence[st]; return; } int mid = (st + end) >> 1; build(index * 2, lvl + 1, st, mid); build(index * 2 + 1, lvl + 1, mid + 1, end); if ((lvl & 1) != (n & 1)) segmentTree[index] = segmentTree[index * 2] | segmentTree[index * 2 + 1]; else segmentTree[index] = segmentTree[index * 2] ^ segmentTree[index * 2 + 1]; } void run() throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String[] toks = bf.readLine().trim().split("[ ]+"); n = Integer.parseInt(toks[0]); m = Integer.parseInt(toks[1]); toks = bf.readLine().trim().split("[ ]+"); sequence = new int[1 << n | 1]; segmentTree = new int[1 << (n + 1) | 1]; for (int i = 1; i <= 1 << n; i++) sequence[i] = Integer.parseInt(toks[i - 1]); build(1, 0, 1, 1 << n); for (int i = 0; i < m; i++) { toks = bf.readLine().trim().split("[ ]+"); int p = Integer.parseInt(toks[0]); int b = Integer.parseInt(toks[1]); update(1, 0, 1, 1 << n, p, b); System.out.println(segmentTree[1]); } } public static void main(String[] args) throws IOException { new CodeForces339D().run(); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
1b2f380c7c25b3e5a8bf452624b3a179
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.*; import java.util.Arrays; //import java.util.*; public class xeniabit { public static void update(int array[],int x1,int x2){ array[(array.length/2)+x1-1]=x2; } public static void or1(int array[],int start){ int a = start; while(a>(start)/2){ array[a]=array[a*2]|array[(a*2)+1]; a--; } } public static void xor1(int arrayx[],int startx){ int ax = startx; while(ax>(startx)/2){ arrayx[ax]=arrayx[ax*2]^arrayx[(ax*2)+1]; ax--; } } public static void or(int n,int [] array){ if(n==1){ //array[1]=array[2] | array[3]; //System.out.println(Arrays.toString(array)+" or at n=1"); return; } else{ array[n/2]=array[(n/2)*2] | array[((n/2)*2)+1]; //System.out.println(Arrays.toString(array)+" or"); xor(n/2,array); } } public static void xor(int n, int [] array){ if(n==1){ //array[1]=array[2]^array[3]; //System.out.println(Arrays.toString(array)+" xor at n=1"); return; } else{ array[n/2]=array[(n/2)*2]^array[((n/2)*2)+1]; //System.out.println(Arrays.toString(array)+" xor"); or(n/2,array); } } public static void main(String[] args)throws IOException { BufferedReader bf = new BufferedReader (new InputStreamReader (System.in)); String [] order = bf.readLine().split(" "); int len = (int)Math.pow(2, Integer.parseInt(order[0])+1); int tests = Integer.parseInt(order[1]); String [] origin = bf.readLine().split(" "); int [] arr = new int [len]; //System.out.println(Arrays.toString(arr)); for(int t = 0;t<origin.length;t++)arr[(len/2)+t]=Integer.parseInt(origin[t]); boolean flag=true; String [] line = bf.readLine().split(" "); int n1 = Integer.parseInt(line[0]); int n2 = Integer.parseInt(line[1]); update(arr,n1,n2); int j = (arr.length/2)-1; while(j>0){ if(flag){ //System.out.println(Arrays.toString(arr)+" or"); or1(arr,j); flag= !flag; } else{ //System.out.println(Arrays.toString(arr)+" xor"); xor1(arr,j); flag= !flag; } j=j/2; } //System.out.println(Arrays.toString(arr)); System.out.println(arr[1]); for(int i=1; i<tests; i++){ line = bf.readLine().split(" "); n1 = Integer.parseInt(line[0]); n2 = Integer.parseInt(line[1]); update(arr,n1,n2); or((arr.length/2)+n1-1,arr); System.out.println(arr[1]); } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
1449c48d360e1d2f0092d29782ba514b
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
//package round197; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class D { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(); int[] a = na(1<<n); SegmentTreeRMQ st = new SegmentTreeRMQ(a); for(int i = 0;i < m;i++){ int p = ni(), b = ni(); st.update(p-1, b); out.println(st.st[1]); } } public class SegmentTreeRMQ { public int M, H, N; public int[] st; public SegmentTreeRMQ(int n) { N = n; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; st = new int[M]; Arrays.fill(st, 0, M, Integer.MAX_VALUE); } public SegmentTreeRMQ(int[] a) { N = a.length; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; st = new int[M]; for(int i = 0;i < N;i++){ st[H+i] = a[i]; } Arrays.fill(st, H+N, M, Integer.MAX_VALUE); for(int i = H-1;i >= 1;i--)propagate(i); } public void update(int pos, int x) { st[H+pos] = x; for(int i = (H+pos)>>>1;i >= 1;i >>>= 1)propagate(i); } private void propagate(int i) { int lev = Integer.numberOfTrailingZeros(H/Integer.highestOneBit(i)); if((lev&1) == 1){ st[i] = st[2*i] | st[2*i+1]; }else{ st[i] = st[2*i] ^ st[2*i+1]; } } } void run() throws Exception { // int n = 17, m = 99999; // Random gen = new Random(); // StringBuilder sb = new StringBuilder(); // sb.append(n + " "); // sb.append(m + " "); // for(int i = 0;i < 1<<n;i++){ // sb.append(gen.nextInt(1000000000) + " "); // } // for(int i = 0;i < m;i++){ // sb.append(gen.nextInt(1<<n)+1 + " "); // sb.append(gen.nextInt(1000000000) + " "); // } // INPUT = sb.toString(); is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().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
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
f7dd8b08023413fdecf9f1c001ecf853
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.DataInputStream; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.TreeSet; public class ProblemA1 { static class Node{ int value; Node left, right, parent; public Node(int a) { value = a; } @Override public String toString() { return "" + value; } } public static void main(String[] args) throws Exception { Parserdoubt77771212 s = new Parserdoubt77771212(System.in); PrintWriter out = new PrintWriter(System.out); int n = s.nextInt(); int m = s.nextInt(); Node a[] = new Node[1 << n]; ArrayList<Node> tree = new ArrayList<Node>(); for (int i = 0; i < a.length; i++) { a[i] = new Node(s.nextInt()); tree.add(a[i]); } int xor = 0; while(tree.size() > 1){ ArrayList<Node> next = new ArrayList<Node>(); for (int i = 0; i < tree.size(); i+=2) { if(xor == 1){ Node left = tree.get(i); Node right = tree.get(i + 1); Node node = new Node(left.value ^ right.value); node.left = left; node.right = right; left.parent = node; right.parent = node; next.add(node); } else { Node left = tree.get(i); Node right = tree.get(i + 1); Node node = new Node(left.value | right.value); node.left = left; node.right = right; left.parent = node; right.parent = node; next.add(node); } } tree = next; xor ^= 1; } for (int i = 0; i < m; i++) { int ix = s.nextInt() - 1; int val = s.nextInt(); int res = -1; a[ix].value = val; Node curr = a[ix].parent; xor = 0; while(curr != null){ if(xor == 1){ res = curr.value = curr.left.value ^ curr.right.value; } else { res = curr.value = curr.left.value | curr.right.value; } xor ^= 1; curr = curr.parent; } out.println(res); } out.close(); } } class Parserdoubt77771212 { final private int BUFFER_SIZE = 1 << 17; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parserdoubt77771212(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString() throws Exception { StringBuffer sb=new StringBuffer(""); byte c = read(); while (c <= ' ') c = read(); do { sb.append((char)c); c=read(); }while(c>' '); return sb.toString(); } public char nextChar() throws Exception { byte c=read(); while(c<=' ') c= read(); return (char)c; } public int nextInt() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } public long nextLong() throws Exception { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
f35a6c1a9469f5a1bd7243d6aaf5c5a6
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.util.Scanner; /** * User: maestro * Date: 13.09.13 * Time: 20:23 */ public class Main { static void countFor(long[][] array, int row, int col, int step) { long a = array[row - 1][col]; long b = array[row - 1][col + step]; array[row][col] = (row % 2 == 0) ? (a ^ b) : (a | b); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int count = 1 << n; long[][] arry = new long[n+1][count]; int m = in.nextInt(); for (int i=0; i<count; i+=2) { arry[0][i] = in.nextLong(); arry[0][i+1] = in.nextLong(); arry[1][i] = arry[0][i] | arry[0][i+1]; } for (int i=2; i<=n; i++) { int prevStep = 1 << (i - 1); int step = prevStep << 1; for (int j=0; j < count; j+=step) { countFor(arry, i, j, prevStep); } } for (int j=0; j < m; j++) { int place = in.nextInt() - 1; arry[0][place] = in.nextLong(); if (place % 2 != 0) place--; for (int i = 1; i <= n; i++) { int prevStep = 1 << (i - 1); int step = prevStep << 1; place = (place / step) * step; countFor(arry, i, place, prevStep); } System.out.println(arry[n][0]); } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
6137c14b141e14d1d9c566a1618396b8
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; /** * Works good for CF * @author cykeltillsalu */ public class D { //some local config static boolean test = false; static String testDataFile = "testdata.txt"; static String feedFile = "feed.txt"; CompetitionType type = CompetitionType.CF; private static String ENDL = "\n"; // solution private void solve() throws Throwable { int n = iread(), q = iread(); int sz = 1 << n, cnt = 0; while(sz > 0){ sz /=2; cnt ++; } int[][] values = new int[cnt][1<<n]; for (int i = 0; i < 1 << n; i++) { values[0][i] = iread(); } int x = values[0].length; int level = 0; boolean even = true; while(x > 1){ for (int i = 0; i < x/2; i++) { if(even){ values[level + 1][i] = values[level][i*2] | values[level][i*2+1]; } else { values[level + 1][i] = values[level][i*2] ^ values[level][i*2+1]; } } level ++; x/=2; even = !even; } for (int k = 0; k < q; k++) { int index = iread() - 1, p = iread(); values[0][index] = p; x = values[0].length; level = 0; even = true; while(x > 1){ int other; if(index %2 == 0){ other = index + 1; } else { other = index - 1; } if(even){ p = p | values[level][other]; } else { p = p ^ values[level][other]; } values[level+1][index/2] = p; level ++; x/=2; index /= 2; even = !even; } out.write(p + "\n"); } out.flush(); } public int iread() throws Exception { return Integer.parseInt(wread()); } public double dread() throws Exception { return Double.parseDouble(wread()); } public long lread() throws Exception { return Long.parseLong(wread()); } public String wread() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return ""; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) throws Throwable { if(test){ //run all cases from testfile: BufferedReader testdataReader = new BufferedReader(new FileReader(testDataFile)); String readLine = testdataReader.readLine(); int casenr = 0; out: while (true) { BufferedWriter w = new BufferedWriter(new FileWriter(feedFile)); if(!readLine.equalsIgnoreCase("input")){ break; } while (true) { readLine = testdataReader.readLine(); if(readLine.equalsIgnoreCase("output")){ break; } w.write(readLine + "\n"); } w.close(); System.out.println("Answer on case "+(++casenr)+": "); new D().solve(); System.out.println("Expected answer: "); while (true) { readLine = testdataReader.readLine(); if(readLine == null){ break out; } if(readLine.equalsIgnoreCase("input")){ break; } System.out.println(readLine); } System.out.println("----------------"); } testdataReader.close(); } else { // run on server new D().solve(); } out.close(); } public D() throws Throwable { if (test) { in = new BufferedReader(new FileReader(new File(feedFile))); } } InputStreamReader inp = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(inp); static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); enum CompetitionType {CF, OTHER}; }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
5a0ff505c1694b95bce9626175616f6d
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; import sun.security.provider.certpath.OCSP.RevocationStatus; public class D { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } long NextLong() { String n = inputParser.nextToken(); long val = Long.parseLong(n); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public static void main(String [] argv) { String filePath=null; if(argv.length>0)filePath=argv[0]; new D(filePath); } public D(String inputFile) { openInput(inputFile); StringBuilder sb = new StringBuilder(); readNextLine(); int NN=NextInt(),M=NextInt(); int N=(int) Math.pow(2, NN); long [][] a = new long[NN+1][]; a[0]=new long[N]; readNextLine(); for(int i=0; i<N; i++) { a[0][i]=NextLong(); } for(int i=1; i<=NN; i++) { a[i]=new long[(int) Math.pow(2, NN-i)]; for(int j=0; j<a[i-1].length; j+=2) if(i%2==1)a[i][j/2]=a[i-1][j]|a[i-1][j+1]; else a[i][j/2]=a[i-1][j]^a[i-1][j+1]; } for(int i=0; i<M; i++) { readNextLine(); int x=NextInt()-1; long b=NextLong(); a[0][x]=b; for(int j=1; j<=NN; j++) { x>>=1; if(j%2==1)a[j][x]=a[j-1][x<<1]|a[j-1][(x<<1)+1]; else a[j][x]=a[j-1][x<<1]^a[j-1][(x<<1)+1]; } sb.append(a[NN][0]+"\n"); } System.out.println(sb); closeInput(); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
c4f5a759a8c16b33c40557e8c10adcad
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.*; import java.util.*; public class fourth { static long fast_power(long a,long n,long m) { if(n==1) { return a%m; } if(n%2==1) { long power = fast_power(a,(n-1)/2,m)%m; return ((a%m) * ((power*power)%m))%m; } long power = fast_power(a,n/2,m)%m; return (power*power)%m; } public static void main(String arr[]) { Scanner sc= new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int k = 1<<n; int a[][] = new int[n+1][k]; for(int i=0;i<k;i++) { a[0][i] = sc.nextInt(); } int len=k/2; int op = 0; for(int i=1;i<n+1;i++) { for(int j=0;j<len;j++) { if(op==0) a[i][j] = a[i-1][j*2] | a[i-1][j*2+1]; else a[i][j] = a[i-1][j*2]^a[i-1][j*2+1]; } op = (op+1)%2; len = len/2; } len=k; for(int i=0;i<m;i++) { int p = sc.nextInt(); int b = sc.nextInt(); a[0][p-1]=b; int next = (p-1)/2; op=0; for(int j=1;j<n+1;j++) { if(op==0) a[j][next] = a[j-1][next*2] | a[j-1][next*2+1]; else a[j][next] = a[j-1][next*2] ^ a[j-1][next*2+1]; op = (op+1)%2; next = next/2; } System.out.println(a[n][0]); } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
d3c69bde85dd3c3afc2a10f07b71df3a
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class D { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void solve() throws IOException { int n = readInt(); int m = readInt(); int[] a = readArr(1<<n); int[] t = new int[(1<<(n+1)) + 1]; boolean xor = n % 2 == 0; build(a,t,1,0,(1<<n)-1,xor); for(int i = 0; i < m; i++) { int p = readInt()-1; int b = readInt(); int temp = a[p]; update(t,1,0,(1<<n)-1,p,b, xor); out.println(t[1]); // update(t,1,0,(1<<n)-1,p,temp,xor); } } private void update(int[] t, int v, int l, int r, int p, int b, boolean xor) { if(l == r) { t[v] = b; return; } int tm = (l+r)/2; if(p > tm) { update(t, 2*v+1, tm+1, r, p, b, !xor); } else { update(t, 2*v, l, tm, p, b, !xor); } t[v] = xor ? t[2*v] ^ t[2*v+1] : t[2*v] | t[2*v+1]; } private void build(int[] a, int[] t, int v, int l, int r, boolean xor) { if(l == r) { t[v] = a[l]; return; } int tm = (l+r)/2; build(a,t,2*v,l, tm, !xor); build(a, t, 2*v + 1, tm+1, r, !xor); t[v] = xor ? t[2*v] ^ t[2*v+1] : t[2*v] | t[2*v+1]; } 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 D().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
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
87408af0be49af67dca34697512f913e
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.util.Scanner; public class D { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); long[][] mas = new long[n + 1][]; mas[0] = new long[(int) Math.pow(2, n)]; for (int i = 0; i < Math.pow(2, n); i++) { mas[0][i] = sc.nextLong(); } for (int i = 1; i < n + 1; i++) { mas[i] = new long[mas[i - 1].length / 2]; if (i % 2 == 0) { for (int j = 0; j < mas[i].length; j++) { mas[i][j] = mas[i - 1][2 * j] ^ mas[i - 1][2 * j + 1]; } } else { for (int j = 0; j < mas[i].length; j++) { mas[i][j] = mas[i - 1][2 * j] | mas[i - 1][2 * j + 1]; } } } StringBuilder sb = new StringBuilder(); for (int i=0; i<m; i++){ int index = sc.nextInt()-1; long b = sc.nextLong(); mas[0][index] = b; index/=2; for (int j=1; j<n+1; j++){ if (j % 2 == 0) { mas[j][index] = mas[j - 1][2 * index] ^ mas[j - 1][2 * index + 1]; } else{ mas[j][index] = mas[j - 1][2 * index] | mas[j - 1][2 * index + 1]; } index/=2; } sb.append(mas[n][0]); sb.append('\n'); } System.out.println(sb); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
ff98fd9f1ff112605f2be8d97af1578a
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int d = in.nextInt(); int n = (1 << d); int m = in.nextInt(); int[][] list = new int[d + 1][n]; for(int i = 0; i < n; i++) { list[0][i] = in.nextInt(); } for(int i = 1; i <= d; i++) { for(int j = 0; j < n / (1 << i); j++) { if(i % 2 == 0) { list[i][j] = list[i-1][2*j] ^ list[i-1][2*j + 1]; } else { list[i][j] = list[i-1][2*j] | list[i-1][2*j + 1]; } } } for(int i = 0; i < m; i++) { int p = in.nextInt() - 1; int b = in.nextInt(); list[0][p] = b; for(int j = 1; j <= d; j++) { p /= 2; if(j % 2 == 0) { list[j][p] = list[j-1][2*p] ^ list[j-1][2*p + 1]; } else { list[j][p] = list[j-1][2*p] | list[j-1][2*p + 1]; } } System.out.println(list[d][0]); } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
5cc94e33c7dc3fe9ba8d89e9534251e1
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class D { private void solve() { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner( // "2 4\n" + // "1 6 3 5\n" + // "1 4\n" + // "3 4\n" + // "1 2\n" + // "1 2\n"); int n = sc.nextInt(); int m = sc.nextInt(); int _2_n = 1 << n; int[][] s = new int[n + 1][_2_n]; for (int i = 0; i < _2_n; i++) { s[0][i] = sc.nextInt(); } int[] p = new int[m]; int[] b = new int[m]; for (int i = 0; i < m; i++) { p[i] = sc.nextInt() - 1; b[i] = sc.nextInt(); } for (int i = 1; i <= n; i++) { int k = 1 << (n - i); for (int j = 0; j < k; j++) { int x = s[i-1][j<<1]; int y = s[i-1][(j<<1)|1]; s[i][j] = (i & 1) == 1 ? (x | y) : (x ^ y); } } for (int i = 0; i < m; i++) { int pp = p[i]; s[0][pp] = b[i]; for (int j = 1; j <= n; j++) { int x = s[j-1][pp&~1]; int y = s[j-1][pp|1]; pp >>= 1; s[j][pp] = (j & 1) == 1 ? (x | y) : (x ^ y); } System.out.println(s[n][0]); } } public static void main(String[] args) { D solver = new D(); solver.solve(); } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
a838b79af1afb5d63f040fe92d540978
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.*; import java.util.*; public class R197_D2_D { public static void main(String[] args) throws Exception { InputReader in = new InputReader(System.in); int n = in.readInt(); int m = in.readInt(); int[][] all = new int[n + 1][1 << n]; for (int i = 0; i < (1 << n); i++) { all[0][i] = in.readInt(); } int curr = 1 << n; for (int i = 1; i <= n; i++) { curr /= 2; for (int j = 0; j < curr; j++) { if (i % 2 == 1) { all[i][j] = all[i - 1][j * 2] | all[i - 1][j * 2 + 1]; } else { all[i][j] = all[i - 1][j * 2] ^ all[i - 1][j * 2 + 1]; } } } for (int i = 0; i < m; i++) { int index = in.readInt() - 1; int num = in.readInt(); all[0][index] = num; for (int j = 1; j <= n; j++) { int nw = index / 2; if (j % 2 == 1){ all[j][nw] = all[j - 1][nw * 2] | all[j - 1][nw * 2 + 1]; }else all[j][nw] = all[j - 1][nw * 2] ^ all[j - 1][nw * 2 + 1]; index = nw; } System.out.println(all[n][0]); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private 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 String readString() { 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; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { 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 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, readInt()); 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, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
6696d1bba195aaa0a47847e57c193243
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class D { private static int N; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] nums = new int[1 << N]; for (int i = 0; i < nums.length; i++) nums[i] = Integer.parseInt(st.nextToken()); SegmentTree seg = new SegmentTree(nums); StringBuilder out = new StringBuilder(); for (int i = 0; i < m; i++) { st = new StringTokenizer(br.readLine()); int p = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); seg.updateNode(p - 1, b); out.append(seg.tree[1]).append('\n'); } System.out.print(out); } private static class SegmentTree { int[] tree; int length; boolean oper; public SegmentTree(int[] arr) { length = arr.length; int h = N + 2; this.tree = new int[1 << h]; oper = (N % 2) == 1; build(1, 1, length, arr, oper); } public void updateNode(int targetNode, int val) { update_Node(1, 1, length, targetNode + 1, val, oper); } private void build(int currNode, int start, int end, int[] arr, boolean or) { if (start == end) tree[currNode] = arr[start - 1]; else { int left = currNode * 2, right = currNode * 2 + 1, mid = (start + end) / 2; build(left, start, mid, arr, !or); build(right, mid + 1, end, arr, !or); tree[currNode] = calculateFunction(tree[left], tree[right], or); } } // update only one node private void update_Node(int currNode, int start, int end, int TARGET_NODE, int UPDATE_VAL, boolean or) { if (TARGET_NODE < start || TARGET_NODE > end) return; if (start == end && start == TARGET_NODE) { tree[currNode] = UPDATE_VAL; return; } int left = currNode * 2, right = currNode * 2 + 1, mid = (start + end) / 2; update_Node(left, start, mid, TARGET_NODE, UPDATE_VAL, !or); update_Node(right, mid + 1, end, TARGET_NODE, UPDATE_VAL, !or); tree[currNode] = calculateFunction(tree[left], tree[right], or); } private int calculateFunction(int a, int b, boolean or) { return or ? (a | b) : (a ^ b); } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
2274dae6ffe810f1cd906a6aef85c7c6
train_002.jsonl
1377531000
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; import static java.lang.Math.*; @SuppressWarnings("unused") public class round197D { static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer st = new StringTokenizer(""); static int nextInt() throws Exception { return Integer.parseInt(next()); } static String next() throws Exception { while (true) { if (st.hasMoreTokens()) { return st.nextToken(); } String s = br.readLine(); if (s == null) { return null; } st = new StringTokenizer(s); } } public static void build(int [] tree, int size){ int loop = (int) (log10(size) / log10(2)); int cur = size; int up = tree.length; for(int i = 0 ; i < loop ; ++i){ for(int j = cur ; j < up ; j += 2){ if(i % 2 == 0){ tree[j / 2] = tree[j] | tree[j + 1]; }else{ tree[j / 2] = tree[j] ^ tree[j + 1]; } } up = cur; cur /= 2; } } public static void update(int [] tree, int p, int b, int size){ int cur = size + p - 1; tree[cur] = b; int level = 0; while(cur > 1){ if(level % 2 == 0){ if(cur % 2 == 0){ tree[cur / 2] = tree[cur] | tree[cur + 1]; }else{ tree[cur / 2] = tree[cur] | tree[cur - 1]; } }else{ if(cur % 2 == 0){ tree[cur / 2] = tree[cur] ^ tree[cur + 1]; }else{ tree[cur / 2] = tree[cur] ^ tree[cur - 1]; } } level++; cur /= 2; } } public static void main(String[] args)throws Exception { int n = nextInt(); int m = nextInt(); int [] tree = new int [1 << (n + 1)]; int idx = 1 << n; for(int i = 0 ; i < 1 << n ; ++i){ tree[idx++] = nextInt(); } //System.out.println(Arrays.toString(tree)); build(tree, 1 << n); //System.out.println(Arrays.toString(tree)); for(int i = 0 ; i < m ; ++i){ int p = nextInt(); int b = nextInt(); update(tree, p, b, 1 << n); //System.out.println(Arrays.toString(tree)); System.out.println(tree[1]); } } }
Java
["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"]
2 seconds
["1\n3\n3\n3"]
NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Java 6
standard input
[ "data structures", "trees" ]
40d1ea98aa69865143d44432aed4dd7e
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai &lt; 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi &lt; 230) — the i-th query.
1,700
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
standard output
PASSED
30e1001a1b3ac98c7672fcbce7fe0ca3
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.InputMismatchException; import java.util.StringTokenizer; public class E { static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } BigInteger nextBigInteger() { try { return new BigInteger(nextLine()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } } public static void main(String[] args) { FastReader fr = new FastReader(); FastWriter fw = new FastWriter(); String s = fr.nextLine(); StringBuilder sb = new StringBuilder(); if (s.length() <= 3) { System.out.println(s.charAt(0)); return; } for (int i = 0; i <= s.length() / 2; i += 2) { char a = s.charAt(i); char b = s.charAt(i + 1); char c = s.charAt(s.length() - i - 1); char d = s.charAt(s.length() - i - 2); if (i + 1 >= s.length() - i - 2) { if (s.length() % 4 != 0) sb.append(a); break; } if (a == c || a == d) sb.append(a); else if (b == c || b == d) sb.append(b); } int n = sb.length() - 1; if (s.length() % 4 == 0) n = sb.length(); for (int i = n - 1; i >= 0; i--) sb.append(sb.charAt(i)); System.out.println(sb); } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
56fbdd77eb6cc88c0b06ab1ab2b2bc76
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String s = br.readLine(); int low=0,high=s.length()-1; StringBuilder sb = new StringBuilder(); while(high-low>2){ if(s.charAt(low) == s.charAt(high)) { sb.append(s.charAt(low)); low++; high--; } else if(s.charAt(low) == s.charAt(high-1)){ sb.append(s.charAt(low)); low++; high-=2; } else{ sb.append(s.charAt(low+1)); low+=2; if(s.charAt(low+1) == s.charAt(high))high--; else high-=2; } } int i=sb.length()-1; if(low<=high) sb.append(s.charAt(low)); while(i>=0)sb.append(sb.charAt(i--)); out.println(sb.toString()); out.close(); } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
d37695630074e41fc7fdcc52e08afb09
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String s = br.readLine(); int low=0,high=s.length()-1; StringBuilder sb = new StringBuilder(); while(high-low>2){ if(s.charAt(low) == s.charAt(high)) { sb.append(s.charAt(low)); low++; high--; } else if(s.charAt(low) == s.charAt(high-1)){ sb.append(s.charAt(low)); low++; high-=2; } else{ sb.append(s.charAt(low+1)); if(s.charAt(low+1) == s.charAt(high)){ low+=2; high--; } else{ low+=2; high-=2; } } } int i=sb.length()-1; if(low<=high) sb.append(s.charAt(low)); while(i>=0)sb.append(sb.charAt(i--)); out.println(sb.toString()); out.close(); } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
5301cdda616f7b65467a4d782a63d57e
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class subsseqs { public static void main(String[] Args){ FastReader scan=new FastReader(); String s=scan.next(); int n=s.length(); boolean[] v=new boolean[n]; int req=n/2; int i=0; int j=n-1; while(i<j){ if(i+1<j-1){ if(s.charAt(i)==s.charAt(j)){ v[i]=true; v[j]=true; } else if(s.charAt(i+1)==s.charAt(j)){ v[i+1]=true; v[j]=true; } else if(s.charAt(i)==s.charAt(j-1)){ v[i]=true; v[j-1]=true; } else{ v[i+1]=true; v[j-1]=true; } i+=2; j-=2; } else{ break; } } if(req%2!=0){ v[i]=true; } StringBuilder ans=new StringBuilder(); for(i=0;i<n;i++){ if(v[i]){ ans.append(s.charAt(i)); } } System.out.println(ans); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
990e045c1688921ae0497168139e9961
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); char [] s = sc.next().toCharArray() ; int l = 0 , r = s.length - 1 ; Stack<Character> left = new Stack<>() ; Stack<Character> right = new Stack<>() ; while (l < r) { if(s[l] == s[r]) { left.add(s[l++]) ; right.add(s[r--]) ; } else if(s[l + 1] == s[r]) { l++ ; if(l == r) left.add(s[l++]); else { left.add(s[l++]); right.add(s[r--]); } } else if(s[l] == s[r - 1]) { r -- ; if(l == r) left.add(s[l++]); else { left.add(s[l++]); right.add(s[r--]); } } else if(s[l + 1] == s[r - 1]) { l++ ; r -- ; if(l == r) left.add(s[l++]); else { left.add(s[l++]); right.add(s[r--]); } } } while (!right.isEmpty()) left.add(right.pop()) ; while (!left.isEmpty()) right.add(left.pop()) ; while (!right.isEmpty()) out.print(right.pop().charValue()); out.flush(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
35943b8436b8b6cd02953efad1d82ab5
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; /** * Created by sourav.p on . */ public class SolveA { private static long mod = 998244353; public static void main(String[] args) { Scanner in = new Scanner(System.in); char str[] = in.next().toCharArray(); if(str.length <=3) { System.out.println(str[0]); return; } ArrayList<Character> list = new ArrayList<>(); int i=0, j = str.length - 1; while(j-i >= 3) { if(str[i] == str[j]) { list.add(str[i]); i++; j--; } else if(str[i] == str[j-1]) { list.add(str[i]); i++; j-=2; } else if(str[i+1] == str[j]) { list.add(str[j]); i+=2; j--; } else { list.add(str[j-1]); j-=2; i+=2; } } int len = list.size() * 2; if(j >= i) { len++; } char ans[] = new char[len]; int k =0; for(int x = 0; x<list.size(); x++) { ans[k++] = list.get(x); } if(j >= i) { ans[k++] = str[i]; } for(int x = list.size() - 1; x>=0; x--) { ans[k++] = list.get(x); } System.out.println(new String(ans)); } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
d99a513bf1fda69301ad8a5508329e29
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStreamReader; import java.util.ArrayList; public class E1178 { public static void main(String[] args) throws Exception { // BufferedReader br = new BufferedReader(new FileReader("F:/books/input.txt")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int i=0,j=s.length()-1; StringBuilder sb = new StringBuilder(); Character c = null; while(i<=j) { if(i>=j-1) { c = s.charAt(i); i++;j--; } else { char w1 = s.charAt(i); char w2 = s.charAt(i+1); char x1 = s.charAt(j); char x2 = s.charAt(j-1); if(w1==x1) { sb.append(w1); i++; j--; } else if(w1==x2) { sb.append(w1); i++; j-=2; } else if(w2==x1) { sb.append(w2); i+=2; j--; } else { i++; j--; } } } System.out.println(sb.toString()+((c!=null)?c:"")+sb.reverse().toString()); } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
ce86ca9e48cdec298fa3e3a940654f96
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.io.*; import java.util.*; public class TaskE { void run() { FastReader in = new FastReader(System.in); // FastReader in = new FastReader(new FileInputStream("input.txt")); PrintWriter out = new PrintWriter(System.out); // PrintWriter out = new PrintWriter(new FileOutputStream("output.txt")); String s = in.next(); int n = s.length(); if (n < 4) { out.println(s.charAt(0)); out.close(); return; } Set<Integer> set = new HashSet<>(); int i = n % 2; int j = n - 1; while (set.size() < n / 2) { if (s.charAt(i) == s.charAt(j)) { set.add(i); set.add(j); } else if (s.charAt(i) == s.charAt(j - 1)) { set.add(i); set.add(j - 1); } else if (s.charAt(i + 1) == s.charAt(j)) { set.add(i + 1); set.add(j); } else if (s.charAt(i + 1) == s.charAt(j - 1)) { set.add(i + 1); set.add(j - 1); } i += 2; j -= 2; } for (int k = 0; k < n; k++) { if (set.contains(k)) out.print(s.charAt(k)); } out.println(); out.close(); } class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } Integer nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } Double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(nextLine()); return st.nextToken(); } String nextLine() { String x = ""; try { x = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return x; } } public static void main(String[] args) { new TaskE().run(); } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
84d63c02f54424da01e81e779651b614
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author null */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, Input in, PrintWriter out) { try { char[] s = in.readWord().toCharArray(); int n = s.length; StringBuilder buf = new StringBuilder(); int p1 = 0; int p2 = n - 1; while (p1 + 3 < p2 - 3) { boolean found = false; for (int x1 = 0; x1 < 3 && !found; x1++) { for (int y1 = 0; y1 < 3 && !found; y1++) { if (s[p1 + x1] == s[p2 - y1]) { for (int x2 = x1 + 1; x2 < 4 && !found; x2++) { for (int y2 = y1 + 1; y2 < 4 && !found; y2++) { if (s[p1 + x2] == s[p2 - y2]) { found = true; buf.append(s[p1 + x1]).append(s[p1 + x2]); } } } } } } p1 += 4; p2 -= 4; } out.print(buf.toString()); String max = ""; int[] b = new int[7]; for (b[0] = 0; b[0] <= 1; b[0]++) { for (b[1] = 0; b[1] <= 1; b[1]++) { for (b[2] = 0; b[2] <= 1; b[2]++) { for (b[3] = 0; b[3] <= 1; b[3]++) { for (b[4] = 0; b[4] <= 1; b[4]++) { for (b[5] = 0; b[5] <= 1; b[5]++) { for (b[6] = 0; b[6] <= 1; b[6]++) { StringBuilder str = new StringBuilder(); for (int i = p1; i <= p2; i++) { if (b[i - p1] == 1) { str.append(s[i]); } } String l = str.toString(); String r = str.reverse().toString(); if (l.equals(r) && l.length() > max.length()) { max = l; } } } } } } } } out.print(max); out.print(buf.reverse().toString()); out.println(); } catch (Exception e) { throw new RuntimeException(e); } } } static class Input { public final BufferedReader reader; private String line = ""; private int pos = 0; public Input(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private boolean isSpace(char ch) { return ch <= 32; } public String readWord() throws IOException { skip(); int start = pos; while (pos < line.length() && !isSpace(line.charAt(pos))) { pos++; } return line.substring(start, pos); } private void skip() throws IOException { while (true) { if (pos >= line.length()) { line = reader.readLine(); pos = 0; } while (pos < line.length() && isSpace(line.charAt(pos))) { pos++; } if (pos < line.length()) { return; } } } } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
c7039285a6f89bc941ce15e2525b875a
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.util.*; import java.io.*; public class EE { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out); StringBuilder stringBuilder = new StringBuilder(); String input = scanner.next(); char[] str = input.toCharArray(); int N= str.length; int a = 0, b = N-1; while(b-a >= 3) { if (str[a] == str[b]) { stringBuilder.append(str[a]); a++; b--; } else { if (str[a + 1] == str[b]) { stringBuilder.append(str[b]); a+=2; b--; } else if (str[a] == str[b-1]) { stringBuilder.append(str[a]); a++; b-=2; } else if (str[b-1] == str[a+1]) { stringBuilder.append(str[a+1]); a+=2; b-=2; } } } String f = stringBuilder.toString(); String s = stringBuilder.reverse().toString(); out.println(f + str[a] + s); out.flush(); } public static class Pair { int a, b; public Pair(int aa, int bb) {a =aa; b = bb;} } 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; } } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output