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
ee3986940f561057e8ae85bf8c3c589f
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class D { static Scanner scn = new Scanner(System.in); public static void main(String[] args) { int n = scn.nextInt(); int k = scn.nextInt(); long[] arr = new long[n]; long aPlusB = and(0, 1) + or(0, 1); long bPlusC = and(1, 2) + or(1, 2); long aPlusC = and(0, 2) + or(0, 2); long sum = aPlusB + bPlusC + aPlusC; sum /= 2; arr[0] = sum - bPlusC; arr[1] = sum - aPlusB; arr[2] = sum - aPlusC; for (int i = 3; i < n; i++) { arr[i] = and(0, i) + or(0, i) - arr[0]; } Arrays.sort(arr); System.out.println("finish " + arr[k - 1]); System.out.flush(); } static int and(int l, int r) { System.out.println("and " + ++l + " " + ++r); System.out.flush(); return scn.nextInt(); } static int or(int l, int r) { System.out.println("or " + ++l + " " + ++r); System.out.flush(); return scn.nextInt(); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
3802492c7c514d7e4144bcdeacca2cb3
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
// coached by kaiboy import java.io.*; import java.util.*; public class CF1556D extends PrintWriter { CF1556D() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1556D o = new CF1556D(); o.main(); o.flush(); } int and(int i, int j) { println("and " + (i + 1) + " " + (j + 1)); return sc.nextInt(); } int or(int i, int j) { println("or " + (i + 1) + " " + (j + 1)); return sc.nextInt(); } int solve(int a01, int a02, int a12, int o01, int o02, int o12) { if (a01 == 1 && a02 == 1) return 7; if (o01 == 0 && o02 == 0) return 0; if (a01 == 1) return 3; if (a02 == 1) return 5; if (a12 == 1) return 6; if (o01 == 0) return 4; if (o02 == 0) return 2; return 1; } void main() { int n = sc.nextInt(); int k = sc.nextInt(); int[] aa = new int[n]; int a01 = and(0, 1); int a02 = and(0, 2); int a12 = and(1, 2); int o01 = or(0, 1); int o02 = or(0, 2); int o12 = or(1, 2); for (int h = 0; h < 30; h++) { int b = solve(a01 >> h & 1, a02 >> h & 1, a12 >> h & 1, o01 >> h & 1, o02 >> h & 1, o12 >> h & 1); aa[0] |= (b >> 0 & 1) << h; aa[1] |= (b >> 1 & 1) << h; aa[2] |= (b >> 2 & 1) << h; } for (int i = 3; i < n; i++) aa[i] = and(0, i) ^ or(0, i) ^ aa[0]; aa = Arrays.stream(aa).boxed().sorted().mapToInt($->$).toArray(); println("finish " + aa[k - 1]); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
8963dadc36a5e5aab26a07185799c25a
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.List; import java.util.*; public class realfast implements Runnable { private static final int INF = (int) 1e9; long in= 1000000007; long fac[]= new long[1000001]; long inv[]=new long[1000001]; public void solve() throws IOException { Scanner in = new Scanner(System.in); int n= in.nextInt(); int k =in.nextInt(); int or[]=new int[n+1]; int and[]=new int[n+1]; for(int i=2;i<=n;i++) { System.out.println("or "+1+" "+i); System.out.flush(); or[i]= in.nextInt(); } for(int i=2;i<=n;i++) { System.out.println("and "+1+" "+i); System.out.flush(); and[i]= in.nextInt(); } System.out.println("and "+2+" "+3); System.out.flush(); int val = in.nextInt(); int pal =1<<30; pal= or[2]; for(int i =2;i<=n;i++) { pal =pal&or[i]; } int arr[]=new int[n]; for(int j =0;j<30;j++) { int kl =1<<j; if((kl&pal)!=0) { boolean check = true; for(int i=2;i<=n;i++) { if((kl&and[i])!=0) { arr[0]= arr[0]|kl; check = false; break; } } if(check) { if((val&kl)==0) { arr[0]= arr[0]|kl; } } } } for(int i=2;i<=n;i++) { for(int j = 0;j<30;j++) { int d = 1<<j; if((d&arr[0])!=0) { if((and[i]&d)!=0) { arr[i-1]= arr[i-1]|d; } } else { if((or[i]&d)!=0) { arr[i-1]= arr[i-1]|d; } } } } Arrays.sort(arr); System.out.println("finish "+arr[k-1]); System.out.flush(); } public long query(long seg[] , int left, int right , int index, int l , int r) { long inf = 100000000; inf = inf*inf; if(left>=l&&right<=r) { return seg[index]; } if(l>right||left>r) return inf; int mid = left+(right-left)/2; return Math.min(query(seg,left,mid,2*index+1,l,r),query(seg,mid+1,right,2*index+2,l,r)); } public int value (int seg[], int left , int right ,int index, int l, int r) { if(left>right) { return -100000000; } if(right<l||left>r) return -100000000; if(left>=l&&right<=r) return seg[index]; int mid = left+(right-left)/2; int val = value(seg,left,mid,2*index+1,l,r); int val2 = value(seg,mid+1,right,2*index+2,l,r); return Math.max(val,val2); } public int gcd(int a , int b ) { if(a<b) { int t =a; a=b; b=t; } if(a%b==0) return b ; return gcd(b,a%b); } public long pow(long n , long p,long m) { if(p==0) return 1; long val = pow(n,p/2,m);; val= (val*val)%m; if(p%2==0) return val; else return (val*n)%m; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int u ; int v; edge(int u, int v) { this.u=u; this.v=v; } public int compareTo(edge e) { return this.v-e.v; } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
a6db5ab5cb0522cf22c1643b01001bbc
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
//some updates in import stuff import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; //key points learned //max space ever that could be alloted in a program to pass in cf //int[][] prefixSum = new int[201][200_005]; -> not a single array more!!! //never allocate memory again again to such bigg array, it will give memory exceeded for sure //believe in your fucking solution and keep improving it!!! (sometimes) public class Main{ static int mod = (int) (Math.pow(10, 9)+7); static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 }; static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 }; static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; static final double eps = 1e-10; static List<Integer> primeNumbers = new ArrayList<>(); public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); //code below int n = sc.nextInt(); int k = sc.nextInt(); //1 and 2 //1 and 3 //2 and 3 //get the number, then 1 and 4, 1 and 5, and keep adding them to sorted list for sure //this should be the technique we should be trying to use for sure boss! //let's solve this problem as fast as we can for sure now! No? //manually do the labor no? //let's solve this problem for sure System.out.println("and " + (1) + " " + (2)); int fone = sc.nextInt(); System.out.println("or " + (1) + " " + (2)); int ftwo = sc.nextInt(); System.out.println("and " + (1) + " " + (3)); int sone = sc.nextInt(); System.out.println("or " + (1) + " " + (3)); int stwo = sc.nextInt(); System.out.println("and " + (2) + " " + (3)); int tone = sc.nextInt(); System.out.println("or " + (2) + " " + (3)); int ttwo = sc.nextInt(); int fnum = 0; int val = 1; for(int i= 0; i < 32; i++){ if(getBit(fone, i) == 1 || getBit(sone, i) == 1){ fnum += val; }else{ if(getBit(ftwo, i) == 0 || getBit(stwo, i) == 0){ //nothing adds, but moves on }else{ if(getBit(ttwo, i) == 0){ fnum += val; } } } val = val * 2; } ArrayList<Integer> allNum = new ArrayList<>(); allNum.add(fnum); int snum = 0; val = 1; for(int i = 0; i < 32; i++){ if(getBit(fone, i) == 1){ snum += val; val = val * 2; continue; } if(getBit(ftwo, i) == 0){ val = val * 2; continue; } //now if both are not true, - that means it has 1 for sure if(getBit(fnum, i) == 0){ snum += val; val = val * 2; continue; } val = val * 2; } allNum.add(snum); int tnum = 0; val = 1; // System.out.println(fnum); // System.out.println(sone); // System.out.println(stwo); for(int i = 0; i < 32; i++){ if(getBit(sone, i) == 1){ tnum += val; val = val * 2; continue; } if(getBit(stwo, i) == 0){ val = val * 2; continue; } //now if both are not true, - that means it has 1 for sure if(getBit(fnum, i) == 0){ // System.out.println("hey"); // System.out.println(val); tnum += val; val = val * 2; continue; } val = val * 2; } allNum.add(tnum); for(int j= 3; j < n; j++){ System.out.println("and " + (1) + " " + (j + 1)); int cone = sc.nextInt(); System.out.println("or " + (1) + " " + (j + 1)); int ctwo = sc.nextInt(); int cnum = 0; val = 1; for(int i = 0; i < 32; i++){ if(getBit(cone, i) == 1){ cnum += val; val = val * 2; continue; } if(getBit(ctwo, i) == 0){ val = val * 2; continue; } //now if both are not true, - that means it has 1 for sure if(getBit(fnum, i) == 0){ // System.out.println("hey"); // System.out.println(val); cnum += val; val = val * 2; continue; } val = val * 2; } allNum.add(cnum); } Collections.sort(allNum); System.out.println("finish " + allNum.get(k - 1)); //simply do this portion right out.close(); } //i should write a function, that takes a number, and ask for the position, and return the set bit at that point //it would work in logn for sure! for each query, 32logn10^4 simple no? public static int getBit(int num, int i){ int mask = 1 << i; int bit = (num & mask) > 0 ? 1 : 0; return bit; } //new stuff to learn (whenever this is need for them, then only) //Lazy Segment Trees //Persistent Segment Trees //Square Root Decomposition //Geometry & Convex Hull //High Level DP -- yk yk //String Matching Algorithms //Heavy light Decomposition //Updation Required //Fenwick Tree - both are done (sum) //Segment Tree - both are done (min, max, sum) //-----CURRENTLY PRESENT-------// //Graph //DSU //powerMODe //power //Segment Tree (work on this one) //Prime Sieve //Count Divisors //Next Permutation //Get NCR //isVowel //Sort (int) //Sort (long) //Binomial Coefficient //Pair //Triplet //lcm (int & long) //gcd (int & long) //gcd (for binomial coefficient) //swap (int & char) //reverse //primeExponentCounts //Fast input and output //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //GRAPH (basic structure) public static class Graph{ public int V; public ArrayList<ArrayList<Integer>> edges; //2 -> [0,1,2] (current) Graph(int V){ this.V = V; edges = new ArrayList<>(V+1); for(int i= 0; i <= V; i++){ edges.add(new ArrayList<>()); } } public void addEdge(int from , int to){ edges.get(from).add(to); edges.get(to).add(from); } } //DSU (path and rank optimised) public static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; Arrays.fill(rank, 1); Arrays.fill(parent,-1); this.n = n; } public int find(int curr){ if(parent[curr] == -1) return curr; //path compression optimisation return parent[curr] = find(parent[curr]); } public void union(int a, int b){ int s1 = find(a); int s2 = find(b); if(s1 != s2){ //union by size if(rank[s1] < rank[s2]){ parent[s1] = s2; rank[s2] += rank[s1]; }else{ parent[s2] = s1; rank[s1] += rank[s2]; } } } } //with mod public static long powerMOD(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ x %= mod; res %= mod; res = (res * x)%mod; } // y must be even now y = y >> 1; // y = y/2 x%= mod; x = (x * x)%mod; // Change x to x^2 } return res%mod; } //without mod public static long power(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ res = (res * x); } // y must be even now y = y >> 1; // y = y/ x = (x * x); } return res; } public static class segmentTree{ //so let's make a constructor function for this bad boi for sure!!! public long[] arr; public long[] tree; //COMPLEXITY (normal segment tree, stuff) //build -> O(n) //query -> O(logn) //update -> O(logn) //update-range -> O(n) (worst case) //simple iteration and stuff for sure public segmentTree(long[] arr){ int n = arr.length; this.arr = new long[n]; for(int i= 0; i < n; i++){ this.arr[i] = arr[i]; } tree = new long[4*n + 1]; } //pretty basic idea if you read the code once //first make child node once //then form the parent node using them public void buildTree(int s, int e, int index){ if(s == e){ tree[index] = arr[s]; return; } //recursive case int mid = (s + e)/2; buildTree(s, mid, 2 * index); buildTree(mid + 1, e, 2*index + 1); //the condition we want from children be like this tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //definitely index based 0 query!!! //only int index = 1!! //baaki everything is simple as fuck public long query(int s, int e, int qs , int qe, int index){ //complete overlap if(s >= qs && e <= qe){ return tree[index]; } //no overlap if(qe < s || qs > e){ return Long.MAX_VALUE; } //partial overlap int mid = (s + e)/2; long left = query( s, mid , qs, qe, 2*index); long right = query( mid + 1, e, qs, qe, 2*index + 1); return min(left, right); } //updates are pretty cool //point update and range update!!! public void updateNode(int s, int e, int i, long increment, int index){ //case where I is out of bounds if(i < s || i > e){ return; } if(s == e){ //making increment tree[index] += increment; return; } //otherwise int mid = (s + e)/2; updateNode(s, mid, i, increment, 2 * index); updateNode(mid + 1, e, i, increment, 2 * index + 1); tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //gonna do range updates for sure now!! //let's do this bois!!! (solve this problem for sure) public void updateRange(int s, int e, int l, int r, long increment, int index){ //out of bounds if(l > e || r < s){ return; } //leaf node if(s == e){ tree[index] += increment; } //recursive case int mid = (s + e)/2; updateRange(s, mid, l, r, increment, 2 * index); updateRange(mid + 1, e, l, r, increment, 2 * index); tree[index] = min(tree[2 * index], tree[2 * index + 1]); } } //prime sieve public static void primeSieve(int n){ BitSet bitset = new BitSet(n+1); for(long i = 0; i < n ; i++){ if (i == 0 || i == 1) { bitset.set((int) i); continue; } if(bitset.get((int) i)) continue; primeNumbers.add((int)i); for(long j = i; j <= n ; j+= i) bitset.set((int)j); } } //number of divisors public static int countDivisors(long number){ if(number == 1) return 1; List<Integer> primeFactors = new ArrayList<>(); int index = 0; long curr = primeNumbers.get(index); while(curr * curr <= number){ while(number % curr == 0){ number = number/curr; primeFactors.add((int) curr); } index++; curr = primeNumbers.get(index); } if(number != 1) primeFactors.add((int) number); int current = primeFactors.get(0); int totalDivisors = 1; int currentCount = 2; for (int i = 1; i < primeFactors.size(); i++) { if (primeFactors.get(i) == current) { currentCount++; } else { totalDivisors *= currentCount; currentCount = 2; current = primeFactors.get(i); } } totalDivisors *= currentCount; return totalDivisors; } //primeExponentCounts public static int primeExponentsCount(int n) { if (n <= 1) return 0; int sqrt = (int) Math.sqrt(n); int remainingNumber = n; int result = 0; for (int i = 2; i <= sqrt; i++) { while (remainingNumber % i == 0) { result++; remainingNumber /= i; } } //in case of prime numbers this would happen if (remainingNumber > 1) { result++; } return result; } //now adding next permutation function to java hehe public static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } //finding the value of NCR in O(RlogN) time and O(1) space public static long getNcR(int n, int r) { long p = 1, k = 1; if (n - r < r) r = n - r; if (r != 0) { while (r > 0) { p *= n; k *= r; long m = __gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } //is vowel function public static boolean isVowel(char c) { return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U'); } //to sort the array with better method public static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } //sort long public static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } //for calculating binomialCoeff public static int binomialCoeff(int n, int k) { int C[] = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } //Pair with int int public static class Pair{ public int a; public int b; public int hashCode; Pair(int a , int b){ this.a = a; this.b = b; this.hashCode = Objects.hash(a, b); } @Override public String toString(){ return a + " -> " + b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair that = (Pair) o; return a == that.a && b == that.b; } @Override public int hashCode() { return this.hashCode; } } //Triplet with int int int public static class Triplet{ public int a; public int b; public int c; Triplet(int a , int b, int c){ this.a = a; this.b = b; this.c = c; } @Override public String toString(){ return a + " -> " + b; } } //Shortcut function public static long lcm(long a , long b){ return a * (b/gcd(a,b)); } //let's make one for calculating lcm basically public static int lcm(int a , int b){ return (a * b)/gcd(a,b); } //int version for gcd public static int gcd(int a, int b){ if(b == 0) return a; return gcd(b , a%b); } //long version for gcd public static long gcd(long a, long b){ if(b == 0) return a; return gcd(b , a%b); } //for ncr calculator(ignore this code) public static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } //swapping two elements in an array public static void swap(int[] arr, int left , int right){ int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //for char array public static void swap(char[] arr, int left , int right){ char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //reversing an array public static void reverse(int[] arr){ int left = 0; int right = arr.length-1; while(left <= right){ swap(arr, left,right); left++; right--; } } public static long expo(long a, long b, long mod) { long res = 1; while (b > 0) { if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second a = (a * a) % mod; b = b >> 1; } return res; } //SOME EXTRA DOPE FUNCTIONS public static long mminvprime(long a, long b) { return expo(a, b - 2, b); } public static long mod_add(long a, long b, long m) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; } public static long mod_sub(long a, long b, long m) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; } public static long mod_mul(long a, long b, long m) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } public static long mod_div(long a, long b, long m) { a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m; } //O(n) every single time remember that public static long nCr(long N, long K , long mod){ long upper = 1L; long lower = 1L; long lowerr = 1L; for(long i = 1; i <= N; i++){ upper = mod_mul(upper, i, mod); } for(long i = 1; i <= K; i++){ lower = mod_mul(lower, i, mod); } for(long i = 1; i <= (N - K); i++){ lowerr = mod_mul(lowerr, i, mod); } // out.println(upper + " " + lower + " " + lowerr); long answer = mod_mul(lower, lowerr, mod); answer = mod_div(upper, answer, mod); return answer; } // long[] fact = new long[2 * n + 1]; // long[] ifact = new long[2 * n + 1]; // fact[0] = 1; // ifact[0] = 1; // for (long i = 1; i <= 2 * n; i++) // { // fact[(int)i] = mod_mul(fact[(int)i - 1], i, mod); // ifact[(int)i] = mminvprime(fact[(int)i], mod); // } //ifact is basically inverse factorial in here!!!!!(imp) public static long combination(long n, long r, long m, long[] fact, long[] ifact) { long val1 = fact[(int)n]; long val2 = ifact[(int)(n - r)]; long val3 = ifact[(int)r]; return (((val1 * val2) % m) * val3) % m; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
2f1e33407bda87f26ac88074160df788
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class B { static FastScanner fs = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); public static int Ask(int type, int i, int j) { ++i; ++j; if (type == 1) out.println("or " + i + " " + j); else out.println("and " + i + " " + j); out.flush(); int resp = fs.nextInt(); return resp; } public static void solve() { int n = fs.nextInt(); int k = fs.nextInt(); long a[] = new long[n]; long x = Ask(1, 0, 1) + Ask(2, 0, 1); long y = Ask(1, 0, 2) + Ask(2, 0, 2); long z = Ask(1, 1, 2) + Ask(2, 1, 2); a[0] = (x + y + z) / 2 - z; a[1] = (x + y + z) / 2 - y; a[2] = (x + y + z) / 2 - x; for (int i = 3; i < n; ++i) { a[i] = Ask(1, i - 1, i) + Ask(2, i - 1, i) - a[i - 1]; } sort(a); out.println("finish " + a[k - 1]); out.flush(); } public static void main(String[] args) { int T = 1; while (T-- > 0) { solve(); } out.close(); } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
86d60c8bab4b5eb10907b2544b469136
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef {static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //static boolean prime[]; //static void sieveOfEratosthenes(int n) //{ // prime = new boolean[n+1]; // for (int i = 0; i <= n; i++) // prime[i] = true; // for (int p = 2; p * p <= n; p++) // { // // If prime[p] is not changed, then it is a // // prime // if (prime[p] == true) // { // // Update all multiples of p // for (int i = p * p; i <= n; i += p) // prime[i] = false; // } // } //} public static void main (String[] args) throws java.lang.Exception { FastReader scan = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int n = scan.nextInt(); int k = scan.nextInt(); ArrayList<Integer> ans = new ArrayList<>(); for(int i=2;i<=n;i++){ pw.println("or "+1+" "+i); pw.flush(); int x = scan.nextInt(); pw.println("and "+1+" "+i); pw.flush(); int y = scan.nextInt(); ans.add(x+y); } pw.println("or "+2+" "+3); pw.flush(); int x= scan.nextInt(); pw.println("and "+2+" "+3); pw.flush(); int y= scan.nextInt(); int sum_2_3 = x+y; int diff_2_3 = ans.get(0)-ans.get(1); int b1 = (sum_2_3+diff_2_3)/2; int a1 = (ans.get(0)-b1); ans.add(2*a1); Collections.sort(ans); pw.println("finish "+(ans.get(k-1)-a1)); pw.flush(); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
1eaba7b8dd8634426f342c13b328072e
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.awt.*; public class Main //public class Solution { public static void solve() { Scanner scn = new Scanner(System.in); int testcase = 1; //testcase = scn.nextInt() ; for(int testcases =1 ; testcases <= testcase ;testcases++) { ArrayList<Long> l= new ArrayList<>(); int n= scn.nextInt() ;int k = scn.nextInt() ; System.out.println("and 1 2"); long a = scn.nextLong(); System.out.println("or 1 2"); long b = scn.nextLong(); System.out.println("and 2 3"); long c = scn.nextLong(); System.out.println("or 2 3"); long d = scn.nextLong(); System.out.println("and 1 3"); long e = scn.nextLong(); System.out.println("or 1 3"); long f = scn.nextLong(); long s1 =a+b ; long s2 =c+d ; long s3 =e+f; long sum = s1+s2+s3; sum =sum/2 ; long fir = sum-s2 ; long sec = sum-s3; long thir = sum-s1 ; l.add(fir);l.add(sec) ;l.add(thir) ; for(int i =4; i <= n ;i++) { System.out.println("and 1 "+(i)); long and = scn.nextLong(); System.out.println("or 1 "+(i)); long or = scn.nextLong(); l.add(and+or-fir); } Collections.sort(l) ; System.out.println("finish "+l.get(k-1)); } // test case end loop } // solve fn ends public static void main (String[] args) throws java.lang.Exception { solve() ; } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
9289d40c47c755b1294c0514ec78e931
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); DTakeAGuess solver = new DTakeAGuess(); solver.solve(1, in, out); out.close(); } static class DTakeAGuess { InputReader in; OutputWriter out; public void solve(int testNumber, InputReader in, OutputWriter out) { this.in = in; this.out = out; int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; int s12 = add(1, 2) + or(1, 2); int s13 = add(1, 3) + or(1, 3); int s23 = add(2, 3) + or(2, 3); a[0] = (s12 + s13 - s23) / 2; a[1] = s13 - a[0]; a[2] = s23 - a[1]; for (int i = 3; i < n; i++) { int s = add(1, i + 1) + or(1, i + 1); a[i] = s - a[0]; } Arrays.sort(a); finish(a[k - 1]); } int add(int x, int y) { out.println("and " + x + " " + y); out.flush(); return in.nextInt(); } int or(int x, int y) { out.println("or " + x + " " + y); out.flush(); return in.nextInt(); } void finish(int x) { out.println("finish " + x); out.flush(); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
77b26ca380b823da3e39f38d3a4fb7e0
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.*; import java.io.*; public class CF { private static FS sc = new FS(); private static class FS { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) {} return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } private static class extra { static int[] intArr(int size) { int[] a = new int[size]; for(int i = 0; i < size; i++) a[i] = sc.nextInt(); return a; } static long[] longArr(int size) { long[] a = new long[size]; for(int i = 0; i < size; i++) a[i] = sc.nextLong(); return a; } static long intSum(int[] a) { long sum = 0; for(int i = 0; i < a.length; i++) { sum += a[i]; } return sum; } static long longSum(long[] a) { long sum = 0; for(int i = 0; i < a.length; i++) { sum += a[i]; } return sum; } static LinkedList[] graphD(int vertices, int edges) { LinkedList<Integer>[] temp = new LinkedList[vertices+1]; for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>(); for(int i = 0; i < edges; i++) { int x = sc.nextInt(); int y = sc.nextInt(); temp[x].add(y); } return temp; } static LinkedList[] graphUD(int vertices, int edges) { LinkedList<Integer>[] temp = new LinkedList[vertices+1]; for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>(); for(int i = 0; i < edges; i++) { int x = sc.nextInt(); int y = sc.nextInt(); temp[x].add(y); temp[y].add(x); } return temp; } static void printG(LinkedList[] temp) { for(LinkedList<Integer> aa:temp) System.out.println(aa); } static long cal(long val, long pow) { if(pow == 0) return 1; long res = cal(val, pow/2); long ret = (res*res)%mod; if(pow%2 == 0) return ret; return (val*ret)%mod; } static long gcd(long a, long b) { return b == 0 ? a:gcd(b, a%b); } } static int mod = (int) 1e9 + 7; // static int mod = (int) 998244353; //static int max = (int) 1e6;//, sq = 316; static LinkedList<Integer>[] temp; static double ans; public static void main(String[] args) { // int t = sc.nextInt(); int t = 1; StringBuilder ret = new StringBuilder(); // int k = 1; while(t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); ArrayList<Integer> arr = new ArrayList<>(); System.out.println("and 1 2"); int a0A = sc.nextInt(); System.out.println("or 1 2"); int a0O = sc.nextInt(); System.out.println("and 2 3"); int a1A = sc.nextInt(); System.out.println("or 2 3"); int a1O = sc.nextInt(); System.out.println("and 1 3"); int a2A = sc.nextInt(); System.out.println("or 1 3"); int a2O = sc.nextInt(); int a01 = a0A + a0O, a12 = a1A + a1O, a02 = a2A + a2O; int a1 = (a01+a12-a02)/2; int a0 = a01-a1; int a2 = a12-a1; arr.add(a1); arr.add(a2); arr.add(a0); int s = 4; while(n-- > 3) { System.out.println("and 1 " + s); int and = sc.nextInt(); System.out.println("or 1 " + s); int or = sc.nextInt(); int sum = and + or; int as = sum-a0; arr.add(as); s++; } Collections.sort(arr); System.out.println("finish " + arr.get(k-1)); // System.out.println(arr); } System.out.println(ret); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
fd1be63cd2b86f504ee7f89010db999c
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
// Generated by Code Flattener. // https://plugins.jetbrains.com/plugin/9979-idea-code-flattener import java.io.*; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Solution solution = new ASolution(); boolean local = System.getProperty("ONLINE_JUDGE") == null && !solution.isInteractive(); String input = local ? "input.txt" : null; solution.in = new MyScanner(input); solution.out = MyWriter.of(null); solution.bm = new Benchmark(); solution.al = new Algorithm(); solution.run(); solution.close(); } private abstract static class Solution { public MyScanner in; public MyWriter out; public Benchmark bm; public Algorithm al; public void init() { } public abstract void solve(); protected boolean isMultiTest() { return true; } public void run() { init(); if (isMultiTest()) { int t = in.nextInt(); for (int i = 0; i < t; i++) { solve(); } } else { solve(); } } public void close() { out.close(); } public boolean isInteractive() { return false; } } private static class ASolution extends Solution { int ans01 = -1; int ans02 = -1; int sum(int i, int j) { if (i == 0 && j == 1 && ans01 != -1) return ans01; if (i == 0 && j == 2 && ans02 != -1) return ans02; out.println("or " + (i + 1) + " " + (j + 1)); out.flush(); int or = in.nextInt(); out.println("and " + (i + 1) + " " + (j + 1)); out.flush(); int and = in.nextInt(); int sum = or + and; if (i == 0 && j == 1) ans01 = sum; if (i == 0 && j == 2) ans02 = sum; return sum; } public void solve() { int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; a[0] = (int) (((long) sum(0, 1) + sum(0, 2) - sum(1, 2)) / 2); for (int i = 1; i < n; i++) { a[i] = sum(0, i) - a[0]; } al.sort(a); out.println("finish " + a[k - 1]); } @Override public boolean isInteractive() { return true; } @Override protected boolean isMultiTest() { return false; } } private static class MyScanner { private final BufferedReader br; private StringTokenizer st; public MyScanner(String fileName) { if (fileName != null) { try { File file = new File(getClass().getClassLoader().getResource(fileName).getFile()); br = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } else { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() { try { String line = br.readLine(); if (line == null) { throw new RuntimeException("empty line"); } st = null; return line; } catch (IOException e) { throw new RuntimeException(e); } } } private static class Benchmark { } private static class Algorithm { public void sort(int[] arr) { List<Integer> tmp = Arrays.stream(arr).boxed().sorted().collect(Collectors.toList()); for (int i = 0; i < arr.length; i++) { arr[i] = tmp.get(i); } } } private static class MyWriter extends PrintWriter { public static MyWriter of(String fileName) { if (fileName != null) { try { return new MyWriter(new FileWriter(fileName)); } catch (IOException e) { throw new RuntimeException(e); } } else { return new MyWriter(new BufferedOutputStream(System.out)); } } public MyWriter(FileWriter fileWriter) { super(fileWriter); } public MyWriter(OutputStream out) { super(out); } } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
379d93377aad44197fe77d805cc6aa2b
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.*; import java.io.*; public class Sol{ /* ->check n=1, int overflow , array bounds , all possibilites(dont stuck on 1 approach) ->Problem = Observation(constraints(m<=n/3 or k<=min(100,n)) + Thinking + Technique (seg_tree,binary lift,rmq,bipart,dp,connected comp etc) ->solve or leave it (- tutorial improves you in minimal way -) */ public static void main (String []args) { //precomp(); int times=1;while(times-->0){solve();}out.close();} static void solve(){ int n=ni();int k=ni(); int union[]=new int[n+1]; int inter[]=new int[n+1]; //union[i]=Ai | A(i-1) for(int i=2;i<=n;i++){ System.out.println("or "+1+" "+i); System.out.flush(); union[i]=ni(); System.out.println("and "+1+" "+i); System.out.flush(); inter[i]=ni(); } int a[]=new int[n+1]; System.out.println("or "+2+" "+3); System.out.flush(); int su=ni(); a[1]=find(union[2],su,inter[2],inter[3]); union[1]=a[1];inter[1]=a[1]; ArrayList<Integer> al=new ArrayList<Integer>();al.add(a[1]); for(int i=2;i<=n;i++){ a[i]=get(a[1],union[i],inter[i]);al.add(a[i]); } //for(int i=1;i<=n;i++){out.print(a[i]+" ");}out.println(); Collections.sort(al); int ans=al.get(k-1); System.out.println("finish "+ans); System.out.flush(); return; } static int[] binary(int n){ int p[]=new int[31]; for(int i=0;i<=30;i++){p[i]=n%2;n/=2;}return p; } static int find(int union1,int union2,int inter1,int inter2){ int p[]=new int[31]; int ans=0; int u1[]=binary(union1);int u2[]=binary(union2); int i1[]=binary(inter1);int i2[]=binary(inter2); for(int i=0;i<=30;i++){p[i]=(i1[i] | i2[i]); if(u1[i]==1 && u2[i]==0){p[i]=1;} } for(int i=30;i>=0;i--){ans=2*ans+p[i];} return ans; } static int get(int a,int union,int inter){ int p[]=new int[31]; int ans=0; int u1[]=binary(union);int i1[]=binary(inter); int num[]=binary(a); for(int i=0;i<=30;i++){p[i]=i1[i];if(u1[i]==1 && i1[i]==0 && num[i]==0)p[i]=1;} for(int i=30;i>=0;i--){ans=2*ans+p[i];}return ans; } //-----------------Utility-------------------------------------------- static long gcd(long a,long b){if(b==0)return a; return gcd(b,a%b);} static int Max=Integer.MAX_VALUE; static long mod=1000000007; //static int v(char c){return (int)(c-'a');} public static long power(long x, long y ) { //0^0 = 1 long res = 1L; x = x%mod; while(y > 0) { if((y&1)==1) res = (res*x)%mod; y >>= 1; x = (x*x)%mod; } return res; } static class Pair implements Comparable<Pair>{ int id;int value;Pair next; public Pair(int id,int value) { this.id=id;this.value=value;next=null; } @Override public int compareTo(Pair p){return Long.compare(value,p.value);} } //----------------------I/O--------------------------------------------- static InputStream inputStream = System.in; static OutputStream outputStream = System.out; static FastReader in=new FastReader(inputStream); static PrintWriter out=new PrintWriter(outputStream); static class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //Only for Integer Input static int ni() { try { boolean in = false; int res = 0; for (;;) { int b = System.in.read() - '0'; if (b >= 0) { in = true; res = 10 * res + b; } else if (in) return res; } } catch (IOException e) { throw new Error(e); } } /*static int ni(){return in.nextInt();}*/ static long nl(){return in.nextLong();} static double nd(){return in.nextDouble();} static String ns(){return in.nextLine();} }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
b339b6bb551a278dd081cf0e3c115792
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //int cases = Integer.parseInt(br.readLine()); //o:while(cases-- > 0) { String[] str = br.readLine().split(" "); int n = Integer.parseInt(str[0]); int k = Integer.parseInt(str[1]); int[] a = new int[n]; System.out.println("and 1 2"); System.out.flush(); int and12 = Integer.parseInt(br.readLine()); System.out.println("or 1 2"); System.out.flush(); int or12 = Integer.parseInt(br.readLine()); System.out.println("and 2 3"); System.out.flush(); int and23 = Integer.parseInt(br.readLine()); System.out.println("or 2 3"); System.out.flush(); int or23 = Integer.parseInt(br.readLine()); System.out.println("and 1 3"); System.out.flush(); int and13 = Integer.parseInt(br.readLine()); System.out.println("or 1 3"); System.out.flush(); int or13 = Integer.parseInt(br.readLine()); a[0] = and12 | and13 | (or12 & ~or23); a[1] = and12 | and23 | (or12 & ~or13); a[2] = and23 | and13 | (or13 & ~or12); for (int i = 3; i < n; i++) { System.out.println("and 1 " + (i + 1)); System.out.flush(); int and1i = Integer.parseInt(br.readLine()); System.out.println("or 1 " + (i + 1)); System.out.flush(); int or1i = Integer.parseInt(br.readLine()); a[i] = and1i ^ or1i ^ a[0]; } Arrays.sort(a); System.out.println("finish " + a[k - 1]); //} } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
7ce11c01baf90c760a0df589f9a1340c
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.io.*; import static java.util.Map.Entry.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { static long mod=(long) (1e9+7); public static void main (String[] args) throws Exception { final long mod1=(long) 1e9+7; Reader s=new Reader(); PrintWriter pt=new PrintWriter(System.out); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); // int T=Integer.parseInt(br.readLine()); // int T=s.nextInt(); // System.out.println(T); int T=1; ol:while(T-->0) { int n=s.nextInt(); int k=s.nextInt(); System.out.println("and 1 2"); int a12=s.nextInt(); System.out.println("or 1 2"); int o12=s.nextInt(); System.out.println("and 1 3"); int a13=s.nextInt(); System.out.println("or 1 3"); int o13=s.nextInt(); System.out.println("and 2 3"); int a23=s.nextInt(); System.out.println("or 2 3"); int o23=s.nextInt(); long sum=(0l+a12+a13+a23+o12+o23+o13)/2; long s12=a12+o12; long s23=a23+o23; long s13=a13+o13; long arr[]=new long[n]; arr[0]=sum-s23; arr[1]=sum-s13; arr[2]=sum-s12; // System.out.println(arr[0]+" "+arr[1]+" "+arr[2]); for(int i=3;i<n;i++) { System.out.println("or 1 "+(i+1)); int o=s.nextInt(); System.out.println("and 1 "+(i+1)); int a=s.nextInt(); arr[i]=0l+a+o-arr[0]; } sort(arr, 0, n-1); System.out.println("finish "+arr[k-1]); } pt.close(); } /** * Seive * * @param n length * @param factors factors[num] is smallest prime divisor of num * @param ar list of primes */ static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar) { factors[1]=1; int p; for(p = 2; p*p <=n; p++) { if(factors[p] == 0) { ar.add(p); factors[p]=p; for(int i = p*p; i <= n; i += p) if(factors[i]==0) factors[i] = p; } } for(;p<=n;p++){ if(factors[p] == 0) { factors[p] = p; ar.add(p); } } } static int binarySearch(int arr[], int x) { int l = 0, r = arr.length - 1; while (l <= r) { int m = l + (r - l) / 2; // Check if x is present at mid if (arr[m] == x) return m; // If x greater, ignore left half if (arr[m] < x) l = m + 1; // If x is smaller, ignore right half else r = m - 1; } // if we reach here, then element was // not present return -1; } public static int getFreq(int arr[], int n) { int k=0; for(int i=0;i<arr.length;i++) { if(arr[i]==n) k++; } return k; } public static void primeFactors(int n) { // Print the number of 2s that divide n HashMap<Integer, Integer> hm=new HashMap<Integer, Integer>(); while (n%2==0) { hm.put(2, hm.getOrDefault(2, 0)+1); n/=2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { n /= i; hm.put(i, hm.getOrDefault(i, 0)+1); } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) hm.put(n, hm.getOrDefault(n, 0)+1); } static boolean isPartition(int arr[], int n) { int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; boolean part[][]=new boolean[sum/2+1][n+1]; // initialize top row as true for (i = 0; i <= n; i++) part[0][i] = true; // initialize leftmost column, except part[0][0], as false for (i = 1; i <= sum / 2; i++) part[i][0] = false; // Fill the partition table in bottom up manner for (i = 1; i <= sum / 2; i++) { for (j = 1; j <= n; j++) { part[i][j] = part[i][j - 1]; if (i >= arr[j - 1]) part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } } return part[sum / 2][n]; } static int setBit(int S, int j) { return S | 1 << j; } static int clearBit(int S, int j) { return S & ~(1 << j); } static int toggleBit(int S, int j) { return S ^ 1 << j; } static boolean isOn(int S, int j) { return (S & 1 << j) != 0; } static int turnOnLastZero(int S) { return S | S + 1; } static int turnOnLastConsecutiveZeroes(int S) { return S | S - 1; } static int turnOffLastBit(int S) { return S & S - 1; } static int turnOffLastConsecutiveBits(int S) { return S & S + 1; } static int lowBit(int S) { return S & -S; } static int setAll(int N) { return (1 << N) - 1; } static int modulo(int S, int N) { return (S & N - 1); } //S%N, N is a power of 2 static boolean isPowerOfTwo(int S) { return (S & S - 1) == 0; } static boolean isWithin(long x, long y, long d, long k) { return x*k*x*k + y*k*y*k <= d*d; } static long modFact(long n, long p) { if (n >= p) return 0; long result = 1; for (int i = 1; i <= n; i++) result = (result * i) % p; return result; } static int sum(int[] arr, int n) { int inc[]=new int[n+1]; int dec[]=new int[n+1]; inc[0] = arr[0]; dec[0] = arr[0]; for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[j] > arr[i]) { dec[i] = max(dec[i], inc[j] + arr[i]); } else if (arr[i] > arr[j]) { inc[i] = max(inc[i], dec[j] + arr[i]); } } } return max(inc[n - 1], dec[n - 1]); } static long nc2(long a) { return a*(a-1)/2; } public static int numberOfprimeFactors(int n) { // Print the number of 2s that divide n HashSet<Integer> hs = new HashSet<Integer>(); while (n%2==0) { hs.add(2); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { hs.add(i); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) hs.add(n); return hs.size(); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static void reverse(int arr[],int start, int end) { int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } static void reverse(long arr[],int start, int end) { long temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int p2(int n) { int k=0; while(n>1) { if(n%2!=0) return k; n/=2; k++; } return k; } static boolean isp2(int n) { while(n>1) { if(n%2==1) return false; n/=2; } return true; } static int binarySearch(int arr[], int first, int last, int key){ int mid = (first + last)/2; while( first <= last ){ if ( arr[mid] < key ){ first = mid + 1; }else if ( arr[mid] == key ){ return mid; }else{ last = mid - 1; } mid = (first + last)/2; } return -1; } static void print(int a[][]) { for(int i=0;i<a.length;i++) { for(int j=0;j<a[0].length;j++) System.out.print(a[i][j]+" "); System.out.println(); } } static int max (int x, int y) { return (x > y)? x : y; } static int search(Pair[] p, Pair pair) { int l=0, r=p.length; while (l <= r) { int m = l + (r - l) / 2; if (p[m].compareTo(pair)==0) return m; if (p[m].compareTo(pair)<0) l = m + 1; else r = m - 1; } return -1; } static void pa(int a[]) { for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } static void pa(long a[]) { for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } static void reverseArray(int arr[], int start, int end) { int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } static boolean isPalindrome(String s) { int l=s.length(); for(int i=0;i<l/2;i++) { if(s.charAt(i)!=s.charAt(l-i-1)) return false; } return true; } static long nc2(long n, long m) { return (n*(n-1)/2)%m; } static long c(long a) { return a*(a+1)/2; } static int next(int[] arr, int target) { int start = 0, end = arr.length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to right side if target is // greater. if (arr[mid] < target) { start = mid + 1; } // Move left side. else { ans = mid; end = mid - 1; } } return ans; } static int prev(Pair[] arr, int target) { int start = 0, end = arr.length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to left side if target is // lesser. if (arr[mid].a > target) { end = mid - 1; } // Move right side. else { ans = mid; start = mid + 1; } } return ans; } static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return power(n, p-2, p); } static long nCrModP(long n, long r, long p) { if(r>n) return 0; if (r == 0) return 1; long[] fac = new long[(int) (n+1)]; fac[0] = 1; for (int i = 1 ;i <= n; i++) fac[i] = fac[i-1] * i % p; return (fac[(int) n]* modInverse(fac[(int) r], p) % p * modInverse(fac[(int) (n-r)], p) % p) % p; } static String reverse(String str) { return new StringBuffer(str).reverse().toString(); } static long fastpow(long x, long y, long m) { if (y == 0) return 1; long p = fastpow(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } static boolean isPerfectSquare(long l) { return Math.pow((long)Math.sqrt(l),2)==l; } static void merge(long[] arr, int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long [n1]; long R[] = new long [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() static void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } static void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int [n1]; int R[] = new int [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() static void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } static class Pair implements Comparable<Pair>{ int a; int b; Pair(int a,int b){ this.a=a; this.b=b; } public int compareTo(Pair p){ if(a>p.a) return 1; if(a==p.a) return (b-p.b); return -1; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[128]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
c5a4a6ce568d8f78a8bbde2ca215dca3
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.*; // import java.lang.*; import java.io.*; // THIS TEMPLATE MADE BY AKSH BANSAL. public class Solution { 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; } } private static boolean[] isPrime; private static void primes(){ int num = (int)1e6; // PRIMES FROM 1 TO NUM isPrime = new boolean[num]; for (int i = 2; i< isPrime.length; i++) { isPrime[i] = true; } for (int i = 2; i< Math.sqrt(num); i++) { if(isPrime[i] == true) { for(int j = (i*i); j<num; j = j+i) { isPrime[j] = false; } } } } static void sort(int a[]){ // int -> long ArrayList<Integer> arr=new ArrayList<>(); // Integer -> Long for(int i=0;i<a.length;i++) arr.add(a[i]); Collections.sort(arr); for(int i=0;i<a.length;i++) a[i]=arr.get(i); } private static long gcd(long a, long b){ if(b==0)return a; return gcd(b,a%b); } private static long pow(long x,long y){ if(y==0)return 1; long temp = pow(x, y/2); if(y%2==1){ return x*temp*temp; } else{ return temp*temp; } } static PrintWriter out; static FastReader sc ; public static void main(String[] args) throws IOException { sc = new FastReader(); out = new PrintWriter(System.out); // primes(); // ________________________________ int n = sc.nextInt(); int k = sc.nextInt(); ArrayList<Long> arr =new ArrayList<>(); long x12 = 0; long x23 = 0; long x13 = 0; print("and "+1+" "+2); x12+=sc.nextInt(); print("or "+1+" "+2); x12+=sc.nextInt(); print("and "+2+" "+3); x23+=sc.nextInt(); print("or "+2+" "+3); x23+=sc.nextInt(); print("and "+1+" "+3); x13+=sc.nextInt(); print("or "+1+" "+3); x13+=sc.nextInt(); long a = (x12+x13+x23)/2 - x23; arr.add(a); arr.add(x12-a); arr.add(x13-a); n-=3; long cur = 4; while(n-->0){ long x =0; print("and "+1+" "+cur); x+=sc.nextInt(); print("or "+1+" "+cur); x+=sc.nextInt(); cur++; arr.add(x-a); } Collections.sort(arr); print("finish "+ arr.get(k-1)); /* * 1 2 3 4 */ // ________________________________ out.flush(); } static void print(String s){ out.println(s); out.flush(); } public static int solver() { int res = 0; return res; } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
2db1c5cff13ade162719ed5c4a442e6a
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
//package codechef; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Set; public class cp_2 { static int mod=(int)1e9+7; // static Reader sc=new Reader(); static FastReader sc=new FastReader(System.in); public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //FastReader sc=new FastReader(); // int t=sc.nextInt(); // while(t-->0) // { int n=sc.nextInt(); int k=sc.nextInt(); int ab=0,bc=0,ac=0; out.println("or"+" "+1+" "+2); out.flush(); ab+=sc.nextInt(); out.println("and"+" "+1+" "+2); out.flush(); ab+=sc.nextInt(); out.println("or"+" "+2+" "+3); out.flush(); bc+=sc.nextInt(); out.println("and"+" "+2+" "+3); out.flush(); bc+=sc.nextInt(); out.println("or"+" "+1+" "+3); out.flush(); ac+=sc.nextInt(); out.println("and"+" "+1+" "+3); out.flush(); ac+=sc.nextInt(); int a=(ab-bc+ac)/2; int b=(ab+bc-ac)/2; int c=(bc+ac-ab)/2; ArrayList<Integer> finalArr=new ArrayList<Integer>(); finalArr.add(a); finalArr.add(b); finalArr.add(c); for(int i=4;i<=n;i++) { int sum=0; out.println("or"+" "+1+" "+i); out.flush(); sum+=sc.nextInt(); out.println("and"+" "+1+" "+i); out.flush(); sum+=sc.nextInt(); finalArr.add(sum-a); } Collections.sort(finalArr); out.println("finish "+finalArr.get(k-1)); // } out.flush(); out.close(); System.gc(); } /* ...SOLUTION ENDS HERE...........SOLUTION ENDS HERE... */ static void swap(int arr[],int i,int j) { int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } static boolean check(String num,String x) { int i=0,pos=0; while(i<num.length() && pos<x.length()) { if(num.charAt(i)==x.charAt(pos)) pos++; i++; } if(pos==x.length()) return true; return false; } static boolean util(int a,int b,int c) { if(b>a)util(b, a, c); while(c>=a) { c-=a; if(c%b==0) return true; } return (c%b==0); } static boolean check(int arr[]) { for (int i = 1; i < arr.length; i++) { if(arr[i-1]>arr[i]) return false; } return true; } static void flag(boolean flag) { out.println(flag ? "YES" : "NO"); out.flush(); } static ArrayList<Long> luckNums; static void luckyNum(long x,long p10) { luckNums.add(x); if(x>(long)1e10) return; luckyNum(x+4*p10, p10*10); luckyNum(x+7*p10, p10*10); } /* Map<Long,Long> map=new HashMap<>(); for(int i=0;i<n;i++) { if(!map.containsKey(a[i])) map.put(a[i],1); else map.replace(a[i],map.get(a[i])+1); } Set<Map.Entry<Long,Long>> hmap=map.entrySet(); for(Map.Entry<Long,Long> data : hmap) { } Iterator<Integer> it = set.iterator(); while(it.hasNext()) { int x=it.next(); } */ static void print(int a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print(long a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print_int(ArrayList<Integer> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void print_long(ArrayList<Long> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static int LowerBound(int a[], int x) { // x is the target value or key int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } static int lowerIndex(int arr[], int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } static int UpperBound(int a[], int x) {// x is the key or target value int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } static class DisjointUnionSets { int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } // Creates n sets with single item in each void makeSet() { for (int i = 0; i < n; i++) parent[i] = i; } int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } // Unites the set that includes x and the set // that includes x void union(int x, int y) { int xRoot = find(x), yRoot = find(y); if (xRoot == yRoot) return; if (rank[xRoot] < rank[yRoot]) parent[xRoot] = yRoot; else if (rank[yRoot] < rank[xRoot]) parent[yRoot] = xRoot; else // if ranks are the same { parent[yRoot] = xRoot; rank[xRoot] = rank[xRoot] + 1; } } } // static class countClass{ // int cnt; // public countClass() { // this.cnt=0; // // TODO Auto-generated constructor stub // } // } static class Graph { int v; ArrayList<Integer> list[]; Graph(int v) { this.v=v; list=new ArrayList[v+1]; for(int i=1;i<=v;i++) list[i]=new ArrayList<Integer>(); } void addEdge(int a, int b) { this.list[a].add(b); } } // static class GraphMap{ // Map<String,ArrayList<String>> graph; // GraphMap() { // // TODO Auto-generated constructor stub // graph=new HashMap<String,ArrayList<String>>(); // // } // void addEdge(String a,String b) // { // if(graph.containsKey(a)) // this.graph.get(a).add(b); // else { // this.graph.put(a, new ArrayList<>()); // this.graph.get(a).add(b); // } // } // } // static void dfsMap(GraphMap g,HashSet<String> vis,String src,int ok) // { // vis.add(src); // // if(g.graph.get(src)!=null) // { // for(String each:g.graph.get(src)) // { // if(!vis.contains(each)) // { // dfsMap(g, vis, each, ok+1); // } // } // } // // cnt=Math.max(cnt, ok); // } static double sum[]; static double cnt; static void DFS(Graph g, boolean[] visited, int u,double path) { visited[u]=true; sum[u]=0; int k=0; for(int i=0;i<g.list[u].size();i++) { int v=g.list[u].get(i); if(!visited[v]) { DFS(g, visited, v,path+1); sum[u]+=sum[v]; k++; } } if(k!=0) sum[u]=sum[u]/(double)k +1; } static class Pair { int x,y; Pair(int x,int y) { this.x=x; this.y=y; } } static long sum_array(int a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static long sum_array(long a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void reverse_array(int a[]) { int n=a.length; int i,t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static void reverse_array(long a[]) { int n=a.length; int i; long t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static long modInverse(long a, long m) { long g = gcd(a, m); return power(a, m - 2, m); } static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m); if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } static class FastReader{ byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()); StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static PrintWriter out=new PrintWriter(System.out); static int int_max=Integer.MAX_VALUE; static int int_min=Integer.MIN_VALUE; static long long_max=Long.MAX_VALUE; static long long_min=Long.MIN_VALUE; }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
01fbea80ce9b4dfbb7079c1f2a1178db
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; // Created by @thesupremeone on 29/08/21 public class D { HashMap<String, Integer> cache = new HashMap<>(); String interact(String query, boolean getResponse) throws IOException { if(localJudge!=null){ localJudge.setName(query); if(getResponse) return localJudge.getName(); }else { println(query); out.flush(); if(getResponse) return getLine(); } return null; } int query(boolean or, int start, int end) throws IOException { int small = Math.min(start, end); int big = Math.max(start, end); start = small; end = big; String symbol = or ? "or" : "and"; String query = symbol+" "+start+" "+end; if(cache.containsKey(query)) return cache.get(query); String response = interact(query, true); int result = Integer.parseInt(response); cache.put(query, result); return result; } void result(int result) throws IOException { interact("finish "+result, false); } void fillBits(int i, int j) throws IOException{ int or = query(true, i, j); int and = query(false, i, j); int index = 0; int mask = 1; while (index<=30){ boolean andSet = (mask&and)!=0; boolean orSet = (mask&or)!=0; if(bitSet[i][index]==0){ bitSet[j][index] = orSet ? 1 : 0; }else if(bitSet[i][index]==1){ bitSet[j][index] = andSet ? 1 : 0; }else if(bitSet[j][index]==0){ bitSet[i][index] = orSet ? 1 : 0; }else if(bitSet[j][index]==1){ bitSet[i][index] = andSet ? 1 : 0; }else if(!orSet){ bitSet[j][index] = 0; bitSet[i][index] = 0; }else if(andSet){ bitSet[j][index] = 1; bitSet[i][index] = 1; } index++; mask<<=1; } } int getNumber(int[] arr){ int mask = 1; int number = 0; int index = 0; while (index<=30){ if(arr[index]==1){ number ^= mask; } mask<<=1; index++; } return number; } int[][] bitSet; void solve() throws IOException { if(localJudge!=null) localJudge.setDaemon(true); int n = getInt(); int k = getInt(); int queries = 2*n; if(localJudge!=null) localJudge.setPriority(queries); bitSet = new int[n+1][31]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= 30; j++) { bitSet[i][j] = 2; } } fillBits(1, 2); fillBits(1, 3); fillBits(2, 3); fillBits(1, 2); for (int j = 4; j <= n; j++) { fillBits(1, j); } Integer[] numbers = new Integer[n]; for (int i = 0; i < n; i++) numbers[i] = getNumber(bitSet[i+1]); Arrays.sort(numbers); result(numbers[k-1]); } public static void main(String[] args) throws Exception { if (isOnlineJudge()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); new D().solve(); out.flush(); } else { localJudge = new Thread(); in = new BufferedReader(new FileReader("input.txt")); out = new BufferedWriter(new FileWriter("output.txt")); localJudge.start(); new D().solve(); out.flush(); localJudge.suspend(); } } static boolean isOnlineJudge(){ try { return System.getProperty("ONLINE_JUDGE")!=null || System.getProperty("LOCAL")==null; }catch (Exception e){ return true; } } // Fast Input & Output static Thread localJudge = null; static BufferedReader in; static StringTokenizer st; static BufferedWriter out; static String getLine() throws IOException{ return in.readLine(); } static String getToken() throws IOException{ if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(getLine()); return st.nextToken(); } static int getInt() throws IOException { return Integer.parseInt(getToken()); } static long getLong() throws IOException { return Long.parseLong(getToken()); } static void print(Object s) throws IOException{ out.write(String.valueOf(s)); } static void println(Object s) throws IOException{ out.write(String.valueOf(s)); out.newLine(); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
b9c30b1e021f4b53ed87e60f5ab02f6b
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
// \(≧▽≦)/ import java.io.*; import java.util.*; public class tank { static final FastScanner fs = new FastScanner(); //static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int t = 1; while(t-- > 0) run_case(); //System.out.println((1 << 30)); //out.close(); } static void run_case() { int n = fs.nextInt(), k = fs.nextInt(); int[] a = new int[n]; int[] ini = new int[6]; ini[0] = ask(1, 2, "and"); ini[1] = ask(1, 2, "or"); ini[2] = ask(1, 3, "and"); ini[3] = ask(1, 3, "or"); ini[4] = ask(3, 2, "and"); ini[5] = ask(3, 2, "or"); for (int j = 0; j < 31; j++) { if((ini[0] & (1 << j)) == (1 << j)) { a[0] |= (1 << j); a[1] |= (1 << j); }else { if((ini[1] & (1 << j)) == (1 << j)) { if((ini[5] & (1 << j)) == (1 << j) && (ini[3] & (1 << j)) == 0) { a[1] |= (1 << j); }else if((ini[5] & (1 << j)) == 0 && (ini[3] & (1 << j)) == (1 << j)) { a[0] |= (1 << j); } else if((ini[5] & (1 << j)) == (1 << j) && (ini[3] & (1 << j)) == (1 << j)) { if((ini[4] & (1 << j)) == (1 << j) && (ini[2] & (1 << j)) == 0) { a[1] |= (1 << j); }else if((ini[4] & (1 << j)) == 0 && (ini[2] & (1 << j)) == (1 << j)) { a[0] |= (1 << j); } } } } } for (int j = 0; j < 31; j++) { if((ini[2] & (1 << j)) == (1 << j)) { a[2] |= (1 << j); }else { if((a[0] & (1 << j)) == 0 && (ini[3] & (1 << j)) == (1 << j)) { a[2] |= (1 << j); } } } int x, y; for (int i = 3; i < n; i++) { x = ask(1, i + 1, "and"); y = ask(1, i + 1, "or"); for (int j = 0; j < 31; j++) { if((x & (1 << j)) == (1 << j)) { a[i] |= (1 << j); }else { if((a[0] & (1 << j)) == 0 && (y & (1 << j)) == (1 << j)) { a[i] |= (1 << j); } } } } ruffleSort(a); // for(int i: a) System.out.println(i + " "); // System.out.println(); System.out.println("finish " + a[k - 1]); } static void ruffleSort(int[] a) { int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n), temp=a[i]; a[i]=a[oi]; a[oi]=temp; } Arrays.sort(a); } static int ask(int i, int j, String q) { System.out.println(q + " " + i + " " + j); int k = fs.nextInt(); System.out.flush(); return k; } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } String nextLine(){ try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return ""; } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
66a8515899eab395396aa33ba7cc6947
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
public class Main { public static void main(String[] args) { new Main(); } public Main() { FastScanner fs = new FastScanner(); java.io.PrintWriter out = new java.io.PrintWriter(System.out); solve(fs, out); out.flush(); } public void solve(FastScanner fs, java.io.PrintWriter out) { int n = fs.nextInt(), k = fs.nextInt(); int[] a = new int[n]; { int a12 = sum(0, 1, fs, out), a13 = sum(0, 2, fs, out), a23 = sum(1, 2, fs, out); a[0] = a12 + a13 - a23 >> 1; a[1] = a12 - a[0]; a[2] = a13 - a[0]; } for (int i = 3;i < n;++ i) { a[i] = sum(0, i, fs, out) - a[0]; } Arrays.sort(a); out.println("finish " + a[k - 1]); } int sum(int x, int y, FastScanner fs, java.io.PrintWriter out){ out.println("or " + (x + 1) + " " + (y + 1)); out.flush(); int sum = fs.nextInt(); out.println("and " + (x + 1) + " " + (y + 1)); out.flush(); sum += fs.nextInt(); return sum; } final int MOD = 998_244_353; int plus(int n, int m) { int sum = n + m; if (sum >= MOD) sum -= MOD; return sum; } int minus(int n, int m) { int sum = n - m; if (sum < 0) sum += MOD; return sum; } int times(int n, int m) { return (int)((long)n * m % MOD); } int divide(int n, int m) { return times(n, IntMath.pow(m, MOD - 2, MOD)); } int[] fact, invf; void calc(int len) { len += 2; fact = new int[len]; invf = new int[len]; fact[0] = fact[1] = invf[0] = invf[1] = 1; for (int i = 2;i < fact.length;++ i) fact[i] = times(fact[i - 1], i); invf[len - 1] = divide(1, fact[len - 1]); for (int i = len - 1;i > 1;-- i) invf[i - 1] = times(i, invf[i]); } int comb(int n, int m) { if (n < m) return 0; return times(fact[n], times(invf[n - m], invf[m])); } } class FastScanner { private final java.io.InputStream in = System.in; private final byte[] buffer = new byte[8192]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) return true; ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } return buflen > 0; } private byte readByte() { return hasNextByte() ? buffer[ptr++ ] : -1; } private static boolean isPrintableChar(byte c) { return 32 < c || c < 0; } private static boolean isNumber(int c) { return '0' <= c && c <= '9'; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++ ; return hasNextByte(); } public String next() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); byte b; while (isPrintableChar(b = readByte())) sb.appendCodePoint(b); return sb.toString(); } public final char nextChar() { if (!hasNext()) throw new java.util.NoSuchElementException(); return (char)readByte(); } public final long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; try { byte b = readByte(); if (b == '-') { while (isNumber(b = readByte())) n = n * 10 + '0' - b; return n; } else if (!isNumber(b)) throw new NumberFormatException(); do n = n * 10 + b - '0'; while (isNumber(b = readByte())); } catch (java.util.NoSuchElementException e) {} return n; } public final int nextInt() { if (!hasNext()) throw new java.util.NoSuchElementException(); int n = 0; try { byte b = readByte(); if (b == '-') { while (isNumber(b = readByte())) n = n * 10 + '0' - b; return n; } else if (!isNumber(b)) throw new NumberFormatException(); do n = n * 10 + b - '0'; while (isNumber(b = readByte())); } catch (java.util.NoSuchElementException e) {} return n; } public double nextDouble() { return Double.parseDouble(next()); } } class Arrays { public static void sort(final int[] array) { sort(array, 0, array.length); } public static void sort(final int[] array, int fromIndex, int toIndex) { if (toIndex - fromIndex <= 512) { java.util.Arrays.sort(array, fromIndex, toIndex); return; } sort(array, fromIndex, toIndex, 0, new int[array.length]); } private static final void sort(int[] a, final int from, final int to, final int l, final int[] bucket) { if (to - from <= 512) { java.util.Arrays.sort(a, from, to); return; } final int BUCKET_SIZE = 256; final int INT_RECURSION = 4; final int MASK = 0xff; final int shift = l << 3; final int[] cnt = new int[BUCKET_SIZE + 1]; final int[] put = new int[BUCKET_SIZE]; for (int i = from; i < to; i++) ++ cnt[(a[i] >>> shift & MASK) + 1]; for (int i = 0; i < BUCKET_SIZE; i++) cnt[i + 1] += cnt[i]; for (int i = from; i < to; i++) { int bi = a[i] >>> shift & MASK; bucket[cnt[bi] + put[bi]++] = a[i]; } for (int i = BUCKET_SIZE - 1, idx = from; i >= 0; i--) { int begin = cnt[i]; int len = cnt[i + 1] - begin; System.arraycopy(bucket, begin, a, idx, len); idx += len; } final int nxtL = l + 1; if (nxtL < INT_RECURSION) { sort(a, from, to, nxtL, bucket); if (l == 0) { int lft, rgt; lft = from - 1; rgt = to; while (rgt - lft > 1) { int mid = lft + rgt >> 1; if (a[mid] < 0) lft = mid; else rgt = mid; } reverse(a, from, rgt); reverse(a, rgt, to); } } } public static void sort(final long[] array) { sort(array, 0, array.length); } public static void sort(final long[] array, int fromIndex, int toIndex) { if (toIndex - fromIndex <= 512) { java.util.Arrays.sort(array, fromIndex, toIndex); return; } sort(array, fromIndex, toIndex, 0, new long[array.length]); } private static final void sort(long[] a, final int from, final int to, final int l, final long[] bucket) { final int BUCKET_SIZE = 256; final int LONG_RECURSION = 8; final int MASK = 0xff; final int shift = l << 3; final int[] cnt = new int[BUCKET_SIZE + 1]; final int[] put = new int[BUCKET_SIZE]; for (int i = from; i < to; i++) ++ cnt[(int) ((a[i] >>> shift & MASK) + 1)]; for (int i = 0; i < BUCKET_SIZE; i++) cnt[i + 1] += cnt[i]; for (int i = from; i < to; i++) { int bi = (int) (a[i] >>> shift & MASK); bucket[cnt[bi] + put[bi]++] = a[i]; } for (int i = BUCKET_SIZE - 1, idx = from; i >= 0; i--) { int begin = cnt[i]; int len = cnt[i + 1] - begin; System.arraycopy(bucket, begin, a, idx, len); idx += len; } final int nxtL = l + 1; if (nxtL < LONG_RECURSION) { sort(a, from, to, nxtL, bucket); if (l == 0) { int lft, rgt; lft = from - 1; rgt = to; while (rgt - lft > 1) { int mid = lft + rgt >> 1; if (a[mid] < 0) lft = mid; else rgt = mid; } reverse(a, from, rgt); reverse(a, rgt, to); } } } public static void reverse(int[] array) { reverse(array, 0, array.length); } public static void reverse(int[] array, int fromIndex, int toIndex) { for (-- toIndex;fromIndex < toIndex;++ fromIndex, -- toIndex) { int swap = array[fromIndex]; array[fromIndex] = array[toIndex]; array[toIndex] = swap; } } public static void reverse(long[] array) { reverse(array, 0, array.length); } public static void reverse(long[] array, int fromIndex, int toIndex) { for (-- toIndex;fromIndex < toIndex;++ fromIndex, -- toIndex) { long swap = array[fromIndex]; array[fromIndex] = array[toIndex]; array[toIndex] = swap; } } public static void shuffle(int[] array) { java.util.Random rnd = new java.util.Random(); for (int i = 0;i < array.length;++ i) { int j = rnd.nextInt(array.length - i) + i; int swap = array[i]; array[i] = array[j]; array[j] = swap; } } public static void shuffle(long[] array) { java.util.Random rnd = new java.util.Random(); for (int i = 0;i < array.length;++ i) { int j = rnd.nextInt(array.length - i) + i; long swap = array[i]; array[i] = array[j]; array[j] = swap; } } } class IntMath { public static int gcd(int a, int b) { while (a != 0) if ((b %= a) != 0) a %= b; else return a; return b; } public static int gcd(int... array) { int ret = array[0]; for (int i = 1; i < array.length; ++i) ret = gcd(ret, array[i]); return ret; } public static long gcd(long a, long b) { while (a != 0) if ((b %= a) != 0) a %= b; else return a; return b; } public static long gcd(long... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret = gcd(ret, array[i]); return ret; } public static long lcm(long a, long b) { return a / gcd(a, b) * b; } public static int pow(int a, int b) { int ans = 1; for (int mul = a; b > 0; b >>= 1, mul *= mul) if ((b & 1) != 0) ans *= mul; return ans; } public static long pow(long a, long b) { long ans = 1; for (long mul = a; b > 0; b >>= 1, mul *= mul) if ((b & 1) != 0) ans *= mul; return ans; } public static int pow(int a, long b, int mod) { if (b < 0) b = b % (mod - 1) + mod - 1; long ans = 1; for (long mul = a; b > 0; b >>= 1, mul = mul * mul % mod) if ((b & 1) != 0) ans = ans * mul % mod; return (int)ans; } public static int pow(long a, long b, int mod) { return pow((int)(a % mod), b, mod); } public static int floorsqrt(long n) { return (int)Math.sqrt(n + 0.1); } public static int ceilsqrt(long n) { return n <= 1 ? (int)n : (int)Math.sqrt(n - 0.1) + 1; } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
17a6f5a516b271b6120c1a70e64e644b
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.stream.IntStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; import java.io.IOException; import java.util.Random; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); DTakeAGuess solver = new DTakeAGuess(); solver.solve(1, in, out); out.close(); } } static class DTakeAGuess { Debug debug = new Debug(false); FastInput in; FastOutput out; public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.ri(); int k = in.ri(); this.in = in; this.out = out; int[] and = new int[n]; int[] or = new int[n]; int[] xor = new int[n]; for (int i = 1; i < n; i++) { and[i] = and(0, i); or[i] = or(0, i); xor[i] = and[i] ^ or[i]; } debug.debug("xor", xor); int a12 = and(1, 2); int o12 = or(1, 2); int x12 = a12 ^ o12; int x0 = 0; int one = 0; int zero = (1 << 30) - 1; for (int j = 1; j < n; j++) { one |= and[j]; zero &= or[j]; } for (int j = 0; j < 30; j++) { if (Bits.get(one, j) == 1) { x0 |= 1 << j; } else if (Bits.get(zero, j) == 0) { } else { if (Bits.get(a12, j) == 0) { x0 |= 1 << j; } } } int[] val = new int[n]; for (int i = 0; i < n; i++) { val[i] = x0 ^ xor[i]; } debug.debug("val", val); int[] indices = IntStream.range(0, n).toArray(); SortUtils.quickSort(indices, (i, j) -> Integer.compare(val[i], val[j]), 0, n); int kth = val[indices[k - 1]]; out.append("finish ").append(kth).println().flush(); } public int and(int a, int b) { out.append("and ").append(a + 1).append(' ').append(b + 1).println().flush(); return in.ri(); } public int or(int a, int b) { out.append("or ").append(a + 1).append(' ').append(b + 1).println().flush(); return in.ri(); } } static class Bits { private Bits() { } public static int get(int x, int i) { return (x >>> i) & 1; } } static interface IntegerComparator { public int compare(int a, int b); } static class SequenceUtils { public static void swap(int[] data, int i, int j) { int tmp = data[i]; data[i] = data[j]; data[j] = tmp; } } static class Debug { private boolean offline; private PrintStream out = System.err; static int[] empty = new int[0]; public Debug(boolean enable) { offline = enable && System.getSecurityManager() == null; } public Debug debug(String name, Object x) { return debug(name, x, empty); } public Debug debug(String name, Object x, int... indexes) { if (offline) { if (x == null || !x.getClass().isArray()) { out.append(name); for (int i : indexes) { out.printf("[%d]", i); } out.append("=").append("" + x); out.println(); } else { indexes = Arrays.copyOf(indexes, indexes.length + 1); if (x instanceof byte[]) { byte[] arr = (byte[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof short[]) { short[] arr = (short[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof boolean[]) { boolean[] arr = (boolean[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof char[]) { char[] arr = (char[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof int[]) { int[] arr = (int[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof float[]) { float[] arr = (float[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof double[]) { double[] arr = (double[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof long[]) { long[] arr = (long[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else { Object[] arr = (Object[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } } } return this; } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int ri() { return readInt(); } public int readInt() { boolean rev = false; skipBlank(); if (next == '+' || next == '-') { rev = next == '-'; next = read(); } int val = 0; while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } return rev ? val : -val; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private static final int THRESHOLD = 32 << 10; private OutputStream writer; private StringBuilder cache = new StringBuilder(THRESHOLD * 2); private static Field stringBuilderValueField; private char[] charBuf = new char[THRESHOLD * 2]; private byte[] byteBuf = new byte[THRESHOLD * 2]; static { try { stringBuilderValueField = StringBuilder.class.getSuperclass().getDeclaredField("value"); stringBuilderValueField.setAccessible(true); } catch (Exception e) { stringBuilderValueField = null; } stringBuilderValueField = null; } public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } private void afterWrite() { if (cache.length() < THRESHOLD) { return; } flush(); } public FastOutput(OutputStream writer) { this.writer = writer; } public FastOutput append(char c) { cache.append(c); afterWrite(); return this; } public FastOutput append(int c) { cache.append(c); afterWrite(); return this; } public FastOutput append(String c) { cache.append(c); afterWrite(); return this; } public FastOutput println() { return append('\n'); } public FastOutput flush() { try { if (stringBuilderValueField != null) { try { byte[] value = (byte[]) stringBuilderValueField.get(cache); writer.write(value, 0, cache.length()); } catch (Exception e) { stringBuilderValueField = null; } } if (stringBuilderValueField == null) { int n = cache.length(); if (n > byteBuf.length) { //slow writer.write(cache.toString().getBytes(StandardCharsets.UTF_8)); // writer.append(cache); } else { cache.getChars(0, n, charBuf, 0); for (int i = 0; i < n; i++) { byteBuf[i] = (byte) charBuf[i]; } writer.write(byteBuf, 0, n); } } writer.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { writer.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class RandomWrapper { private Random random; public static final RandomWrapper INSTANCE = new RandomWrapper(); public RandomWrapper() { this(new Random()); } public RandomWrapper(Random random) { this.random = random; } public RandomWrapper(long seed) { this(new Random(seed)); } public int nextInt(int l, int r) { return random.nextInt(r - l + 1) + l; } } static class SortUtils { private static final int THRESHOLD = 8; private SortUtils() { } public static void insertSort(int[] data, IntegerComparator cmp, int l, int r) { for (int i = l + 1; i <= r; i++) { int j = i; int val = data[i]; while (j > l && cmp.compare(data[j - 1], val) > 0) { data[j] = data[j - 1]; j--; } data[j] = val; } } public static void quickSort(int[] data, IntegerComparator cmp, int f, int t) { if (t - f <= THRESHOLD) { insertSort(data, cmp, f, t - 1); return; } SequenceUtils.swap(data, f, RandomWrapper.INSTANCE.nextInt(f, t - 1)); int l = f; int r = t; int m = l + 1; while (m < r) { int c = cmp.compare(data[m], data[l]); if (c == 0) { m++; } else if (c < 0) { SequenceUtils.swap(data, l, m); l++; m++; } else { SequenceUtils.swap(data, m, --r); } } quickSort(data, cmp, f, l); quickSort(data, cmp, m, t); } } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
4af9c085edd6b66c3e2ecd06ddadf92a
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class CF_1556_D{ //SOLUTION BEGIN void pre() throws Exception{} void solve(int TC) throws Exception{ int N = ni(), K = ni(); // int N = AR.length-1; int AB = or(1, 2), AC = or(1, 3), BC = or(2,3); int ab = and(1, 2), ac = and(1, 3), bc = and(2,3); // dbg(AB, AC, BC, ab, ac, bc); int[] A = new int[1+N]; A[1] |= ((AB&AC) & (~BC))|(ab | ac); A[2] = A[1]^AB^ab; A[3] = A[1]^AC^ac; for(int i = 4; i<= N; i++){ int X = and(1, i)^or(1, i); A[i] = A[1]^X; } Arrays.sort(A, 1, 1+N); finish(A[K]); } int[] AR = new int[]{0,1,6,4,2,3,5,4}; int or(int i, int j) throws Exception{ pni("or", i, j); // return AR[i] | AR[j]; return ni(); } int and(int i, int j) throws Exception{ pni("and", i, j); // return AR[i] & AR[j]; return ni(); } void finish(int x){ pni("finish", x); } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} void exit(boolean b){if(!b)System.exit(0);} static void dbg(Object... o){System.err.println(Arrays.deepToString(o));} final long IINF = (long)1e17; final int INF = (int)1e9+2; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8; static boolean multipleTC = false, memory = true, fileIO = false; FastReader in;PrintWriter out; void run() throws Exception{ long ct = System.currentTimeMillis(); if (fileIO) { in = new FastReader(""); out = new PrintWriter(""); } else { in = new FastReader(); out = new PrintWriter(System.out); } //Solution Credits: Taranpreet Singh int T = multipleTC? ni():1; pre(); for (int t = 1; t <= T; t++) solve(t); out.flush(); out.close(); System.err.println(System.currentTimeMillis() - ct); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new CF_1556_D().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 28).start(); else new CF_1556_D().run(); } int[][] make(int n, int e, int[] from, int[] to, boolean f){ int[][] g = new int[n][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = to[i]; if(f)g[to[i]][--cnt[to[i]]] = from[i]; } return g; } int[][][] makeS(int n, int e, int[] from, int[] to, boolean f){ int[][][] g = new int[n][][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0}; if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1}; } return g; } int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));} int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;} long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object... o){for(Object oo:o)out.print(oo+" ");} void pn(Object... o){for(int i = 0; i< o.length; i++)out.print(o[i]+(i+1 < o.length?" ":"\n"));} void pni(Object... o){for(Object oo:o)out.print(oo+" ");out.println();out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
ce2ca50b67080e8bf0066827a06366b4
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.*;import java.io.*;import java.math.*; public class Main { public static void process()throws IOException { int n = ni(); int k = ni(); int[]ans=new int[n+1]; int aorb=or(1, 2); // a+b int aorc=or(1, 3); // a+c int and=aorb&aorc; // a+(b.c) int aandb=and(1, 2); // a.b int aandc=and(1, 3); //a.c int and2=aandb&aandc; //a.(b.c) int xor=and2^and; // a^(b.c) int bc=and(2, 3); // b.c ans[1]=xor^bc; ans[2]=(aorb^aandb)^ans[1]; ans[3]=(aorc^aandc)^ans[1]; for(int i=4;i<=n;i++) { int curr = or(1, i) ^ and(1, i); ans[i]=curr^ans[1]; } Arrays.sort(ans); pn("finish "+ans[k]); } static int or(int i, int j)throws IOException{ pni("or "+i+" "+j); int x = ni(); return x; } static int and(int i, int j)throws IOException{ pni("and "+i+" "+j); int x = ni(); return x; } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} int t=1; // t=ni(); while(t-- > 0) {process();} out.flush();out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;} static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
600d64e8f3d1ed616ef909ccd350dfc4
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
//package deltixs2021; import java.io.*; import java.util.ArrayDeque; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Queue; public class D { InputStream is; FastWriter out; String INPUT = ""; void solve() { int n = ni(), K = ni(); long[] a = new long[3]; int p = 0; for(int i = 0;i < 3;i++){ for(int j = i+1;j < 3;j++){ long s = 0; out.println("or " + (i+1) + " " + (j+1)); out.flush(); s += nl(); out.println("and " + (i+1) + " " + (j+1)); out.flush(); s += nl(); a[p++] = s; } } long sum = (a[0] + a[1] + a[2]) / 2; long[] b = new long[n]; b[0] = sum - a[2]; b[1] = sum - a[1]; b[2] = sum - a[0]; for(int i = 3;i < n;i++){ long s = 0; out.println("or " + 1 + " " + (i+1)); out.flush(); s += nl(); out.println("and " + 1 + " " + (i+1)); out.flush(); s += nl(); b[i] = s - b[0]; } b = radixSort(b); out.println("finish " + b[K-1]); out.flush(); } public static long[] radixSort(long[] f){ return radixSort(f, f.length); } public static long[] radixSort(long[] f, int n) { long[] to = new long[n]; { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>16&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>16&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>32&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>32&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>48&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>48&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } return f; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new FastWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for(int i = 0;i < n;i++)a[i] = nl(); return a; } 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[][] nmi(int n, int m) { int[][] map = new int[n][]; for(int i = 0;i < n;i++)map[i] = na(m); return map; } private int ni() { return (int)nl(); } 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(); } } public static class FastWriter { private static final int BUF_SIZE = 1<<13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter(){out = null;} public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if(ptr == BUF_SIZE)innerflush(); return this; } public FastWriter write(char c) { return write((byte)c); } public FastWriter write(char[] s) { for(char c : s){ buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if(x == Integer.MIN_VALUE){ return write((long)x); } if(ptr + 12 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if(x == Long.MIN_VALUE){ return write("" + x); } if(ptr + 21 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if(x < 0){ write('-'); x = -x; } x += Math.pow(10, -precision)/2; // if(x < 0){ x = 0; } write((long)x).write("."); x -= (long)x; for(int i = 0;i < precision;i++){ x *= 10; write((char)('0'+(int)x)); x -= (int)x; } return this; } public FastWriter writeln(char c){ return write(c).writeln(); } public FastWriter writeln(int x){ return write(x).writeln(); } public FastWriter writeln(long x){ return write(x).writeln(); } public FastWriter writeln(double x, int precision){ return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for(int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for(long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte)'\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for(char[] line : map)write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c){ return writeln(c); } public FastWriter println(int x){ return writeln(x); } public FastWriter println(long x){ return writeln(x); } public FastWriter println(double x, int precision){ return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } public void trnz(int... o) { for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" "); System.out.println(); } // print ids which are 1 public void trt(long... o) { Queue<Integer> stands = new ArrayDeque<>(); for(int i = 0;i < o.length;i++){ for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x)); } System.out.println(stands); } public void tf(boolean... r) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } public void tf(boolean[]... b) { for(boolean[] r : b) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } System.out.println(); } public void tf(long[]... b) { if(INPUT.length() != 0) { for (long[] r : b) { for (long x : r) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } System.out.println(); } } public void tf(long... b) { if(INPUT.length() != 0) { for (long x : b) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
2681a30d9e0c4d9cd3cfa480508584fe
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class TakeAGuess { static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) { int N = sc.nextInt(); int K = sc.nextInt()-1; int[] a = new int[N]; int[] b = new int[N-1]; int c = query(0,2,0)+query(0,2,1); for( int i = 0; i < N-1; i++ ) { b[i] = query(i,i+1,0)+query(i,i+1,1); } a[0] = (b[0]-b[1]+c)/2; a[1] = b[0]-a[0]; a[2] = -(b[0]-b[1]-c)/2; for( int i = 3; i < N; i++ ) { a[i] = b[i-1]-a[i-1]; } Arrays.sort(a); answer_query(a[K]); } static void answer_query(int ans) { pw.print("finish"); pw.print(' '); pw.println(ans); pw.flush(); } static int query(int i, int j, int k) { i++; j++; pw.print( k == 0 ? "or" : "and" ); pw.print(' '); pw.print(i); pw.print(' '); pw.println(j); pw.flush(); return sc.nextInt(); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
eb6742783df6f65b1625c53ff395b13a
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.*; import java.io.*; public class D { static FastScanner fs = new FastScanner(); static PrintWriter pw = new PrintWriter(System.out); static StringBuilder sb = new StringBuilder(""); static final long INF = (long) 10e12; public static void main(String[] args) { int n = fs.nextInt(), k = fs.nextInt(); int[] A = new int[n]; int o12, o23, o31, a12, a23, a31; System.out.println("or " + 1 + " " + 2); o12 = fs.nextInt(); System.out.println("or " + 2 + " " + 3); o23 = fs.nextInt(); System.out.println("or " + 3 + " " + 1); o31 = fs.nextInt(); System.out.println("and " + 1 + " " + 2); a12 = fs.nextInt(); System.out.println("and " + 2 + " " + 3); a23 = fs.nextInt(); System.out.println("and " + 3 + " " + 1); a31 = fs.nextInt(); for (int i = 0; i < 30; i++) { if ((a12 >> i & 1) == 1) { A[0] += 1 << i; A[1] += 1 << i; if ((a23 >> i & 1) == 1) { A[2] += 1 << i; } } else if ((o12 >> i & 1) == 0) { if ((o23 >> i & 1) == 1) { A[2] += 1 << i; } } else { if ((a23 >> i & 1) == 1) { A[1] += 1 << i; A[2] += 1 << i; } if ((a31 >> i & 1) == 1) { A[0] += 1 << i; A[2] += 1 << i; } if ((o23 >> i & 1) == 0) { A[0] += 1 << i; } if ((o31 >> i & 1) == 0) { A[1] += 1 << i; } } } for (int i = 3; i < n; i++) { int o, a; System.out.println("or " + 1 + " " + (i+1)); o = fs.nextInt(); System.out.println("and " + 1 + " " + (i+1)); a = fs.nextInt(); int x = o ^ a; A[i] = x ^ A[0]; } sort(A); k--; System.out.println("finish " + A[k]); } static void sort(int[] a) { ArrayList<Integer> al = new ArrayList<>(); for (int i : a) al.add(i); Collections.sort(al); for (int i = 0; i < a.length; i++) a[i] = al.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() {while (!st.hasMoreTokens()) try {st = new StringTokenizer(br.readLine());} catch (IOException e) {}return st.nextToken();} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble() {return Double.parseDouble(next());} } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
47511800dd9ac86f18ea9ed7f6b28d7d
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class A4 { void solve() { int n = cint(); int k = cint(); long sum1 = getSum(1, 2); long sum2 = getSum(1, 3); long sum3 = getSum(2, 3); long[] res = new long[n]; res[0] = (sum1 - sum3 + sum2) / 2; res[2] = sum2 - res[0]; res[1] = sum3 - res[2]; for (int i = 3; i < n; i++) { long sum = getSum(1, i+1); res[i] = sum - res[0]; } Arrays.sort(res); out.println("finish " + res[k-1]); } long getSum(int a, int b) { return and(a, b) + or(a, b); } long and(int a, int b) { out.println("and " + a + " " + b); out.flush(); return in.nextInt(); } long or(int a, int b) { out.println("or " + a + " " + b); out.flush(); return in.nextInt(); } // // static long[] X = new long[]{5, 3, 3, 10, 1}; // // long and(int a, int b) { // return X[a-1] & X[b-1]; // } // // long or(int a, int b) { // return X[a-1] | X[b-1]; // } public static void main(String... args) { // int t = in.nextInt(); // in.nextLine(); // for (int test = 0; test < t; test++) { new A4().solve(); // } } static final Scanner in = new Scanner(System.in); static final PrintStream out = System.out; static int cint() { return in.nextInt(); } static long clong() { return in.nextLong(); } static String cstr() { return in.nextLine(); } static int[] carr_int(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } return a; } static long[] carr_long(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = in.nextLong(); } return a; } static void cout(int... a) { for (int i = 0; i < a.length; i++) { if (i != 0) { out.print(' '); } out.print(a[i]); } out.println(); } static void cout(long... a) { for (int i = 0; i < a.length; i++) { if (i != 0) { out.print(' '); } out.print(a[i]); } out.println(); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
32eb798cff6564d115a283c0fd872cb5
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader s=new FastReader(); int t=1; while(t-->0) { int n=s.nextInt(); int k=s.nextInt(); int aband,abor,acand,bcand,acor; System.out.println("and 1 2"); System.out.flush(); aband=s.nextInt(); System.out.println("or 1 2"); System.out.flush(); abor=s.nextInt(); System.out.println("and 1 3"); System.out.flush(); acand=s.nextInt(); System.out.println("and 2 3"); System.out.flush(); bcand=s.nextInt(); System.out.println("or 1 3"); System.out.flush(); acor=s.nextInt(); int a=0,b=0,c=0; for(int i=0;i<31;i++) { int power=1<<i; if((aband&power)==0 && (abor&power)!=0) { if((acand&power)!=0 && (bcand&power)==0) a+=power; else if((acand&power)==0 && (bcand&power)!=0) b+=power; else if((acor&power)!=0) a+=power; else b+=power; } } a+=aband; b+=aband; for(int p=0;p<31;p++) { int power=1<<p; if((acand&power)!=0) c+=power; else { if((a&power)!=0) continue; if((acor&power)!=0) c+=power; } } ArrayList<Integer> arr=new ArrayList<>(); arr.add(a); arr.add(b); arr.add(c); for(int i=4;i<=n;i++) { int and,or; System.out.println("and 1 "+i); System.out.flush(); and=s.nextInt(); System.out.println("or 1 "+i); System.out.flush(); or=s.nextInt(); int newnum=0; for(int p=0;p<31;p++) { int power=1<<p; if((and&power)!=0) newnum+=power; else { if((a&power)!=0) continue; if((or&power)!=0) newnum+=power; } } arr.add(newnum); } Collections.sort(arr); System.out.println("finish "+arr.get(k-1)); System.out.flush(); } } } class M { public final long mod=(long)1e9+7; public final long inf=(long)1e18; public static long max(long a,long b) { return ((a>b)?a:b); } public static long min(long a,long b) { return ((a<b)?a:b); } public static long gcd(long a, long b) { return (b>0)? gcd (b, a % b) : a; } } class SparseTable { long[][] rmq; public SparseTable(long a[],int n ) { rmq = new long[32 - Integer.numberOfLeadingZeros(n)][]; rmq[0] = a.clone(); for (int i = 1; i < rmq.length; i++) { rmq[i] = new long[n - (1 << i) + 1]; for (int j = 0; j < rmq[i].length; j++) rmq[i][j] = M.gcd(rmq[i - 1][j], rmq[i - 1][j + (1 << (i - 1))]); } } public long gcd(int i, int j) { int k = 31 - Integer.numberOfLeadingZeros(j - i + 1); return M.gcd(rmq[k][i], rmq[k][j - (1 << k) + 1]); } } class DSU { static final int N=200000; int parent[]=new int[N],sz[]=new int[N]; DSU(int n) { for(int i=1;i<=n;i++) {sz[i]=1;parent[i]=i;} } public int find(int u) { return parent[u] = ((parent[u] == u) ? u : find(parent[u])); } public void merge(int u,int v) { sz[find(u)]+=sz[find(v)]; parent[find(v)]=u; } public long getsize(int a) { return sz[find(a)]; } } class Pair { Long arr[]=new Long[2]; Pair(Long a,Long b) { arr[0]=a; arr[1]=b; } public Long get(Long id) { return arr[(int)(long)id]; } } class sortDefault implements Comparator<Pair> { @Override public int compare(Pair o1, Pair o2) { return (int)(o1.get(0L)-o2.get(0L)); } } class Triplet { long arr[]=new long[3]; Triplet(long a,long b,long c) { this.arr[0]=a; this.arr[1]=b; this.arr[2]=c; } public long getValue(int id) { return arr[id]; } } class sortDefaultT implements Comparator<Triplet> { @Override public int compare(Triplet a, Triplet b) { if(a.getValue(0)!=b.getValue(0)) return (int)a.getValue(0)-(int)b.getValue(0); if(a.getValue(1)!=b.getValue(1)) return (int)a.getValue(1)-(int)b.getValue(1); if(a.getValue(2)!=b.getValue(2)) return (int)a.getValue(2)-(int)b.getValue(2); return 0; } } class BS { public int lowerBound(ArrayList<Long> a, int low, int high, Long element) { while (low < high) { int middle = low + (high - low) / 2; if (element > a.get(middle)) { low = middle + 1; } else { high = middle; } } return low; } public int upperBound(ArrayList<Long> a, int low, int high, Long element) { while (low < high) { int middle = low + (high - low) / 2; if (a.get(middle) > element) { high = middle; } else { low = middle + 1; } } return low; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
3be40c36f269c80d598dc428c04989d3
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //static final long mod=(long)1e9+7; /*static final long mod=998244353L; public static long pow(long a,long p) { long res=1; while(p>0) { if(p%2==1) { p--; res*=a; res%=mod; } else { a*=a; a%=mod; p/=2; } } return res; }*/ /*static class Pair { int u,v; Pair(int u,int v) { this.u=u; this.v=v; } }*/ /*static class Pair implements Comparable<Pair> { int v,l; Pair(int v,int l) { this.v=v; this.l=l; } public int compareTo(Pair p) { return l-p.l; } }*/ /*static long gcd(long a,long b) { if(b%a==0) return a; return gcd(b%a,a); } public static void dfs(int u,ArrayList<Integer> edge[],boolean vis[]) { vis[u]=true; for(int v:edge[u]) { if(!vis[v]) dfs(v,edge,vis); } } static class DSU { int par[],rank[],n; DSU(int n) { this.n=n; par=new int[n+1]; rank=new int[n+1]; for(int i=1;i<=n;i++) par[i]=i; } public void union(int u,int v) { u=find(u); v=find(v); if(u==v) return; if(rank[u]>rank[v]) par[v]=u; else if(rank[u]<rank[v]) par[u]=v; else { rank[v]++; par[u]=v; } } public int find(int u) { if(u==par[u]) return u; return par[u]=find(par[u]); } } static class Edge { int v,ind; long w; Edge(int v,int w,int ind) { this.ind=ind; this.v=v; this.w=1L*w; } } static class Pair implements Comparable<Pair> { int u,v; Pair(int u,int v) { this.u=u; this.v=v; } public int compareTo(Pair p) { if(this.u!=p.u) return this.u-p.u; return p.v-this.v; } }*/ public static void main(String args[])throws Exception { FastReader fs=new FastReader(); PrintWriter pw=new PrintWriter(System.out); //int tc=fs.nextInt(); int tc=1; while(tc-->0) { int n=fs.nextInt(); int k=fs.nextInt(); --k; pw.println("or 1 2"); pw.flush(); int fo=fs.nextInt(); pw.println("or 2 3"); pw.flush(); int so=fs.nextInt(); pw.println("or 1 3"); pw.flush(); int to=fs.nextInt(); pw.println("and 1 2"); pw.flush(); int fa=fs.nextInt(); pw.println("and 2 3"); pw.flush(); int sa=fs.nextInt(); pw.println("and 1 3"); pw.flush(); int ta=fs.nextInt(); int ab=fo+fa; int bc=so+sa; int ac=to+ta; int one=(ab-bc+ac)/2; int two=ab-one; int three=ac-one; ArrayList<Integer> list=new ArrayList<>(); list.add(one); list.add(two); list.add(three); for(int i=4;i<=n;i++) { pw.println("or 3 "+i); pw.flush(); int a=fs.nextInt(); pw.println("and 3 "+i); pw.flush(); int b=fs.nextInt(); list.add(a+b-three); } Collections.sort(list); pw.println("finish "+list.get(k)); pw.flush(); } pw.flush(); pw.close(); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
9904626aa9b57409aaa575c760122f5c
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.BigInteger; import java.util.InputMismatchException; public class Main { static PrintWriter out; static Reader in; public static void main(String[] args) throws IOException { input_output(); Main solver = new Main(); solver.solve(); out.close(); out.flush(); } static long INF = (long)1e18; static int MAXN = (int)3e5 + 5; static long MOD = (long)1e9 + 7; static int q, t, n, m, k; static double pi = Math.PI; void solve() throws IOException { n = in.nextInt(); k = in.nextInt(); int[] and = new int[n+1], or = new int[n+1]; out.println("and 2 3"); out.flush(); int and23 = in.nextInt(); for (int i = 2; i <= n; i++) { out.println("and 1 "+i); out.flush(); and[i] = in.nextInt(); out.println("or 1 "+i); out.flush(); or[i] = in.nextInt(); } List<Integer> arr = new ArrayList<>(); int first = 0; for (int i = 2; i <= n; i++) first |= and[i]; for (int i = 0; i < 30; i++) { int ithBit = 1 << i; if ((ithBit & first) != 0) continue; boolean bitOn = true; for (int j = 2; j <= n; j++) bitOn &= (ithBit & or[j]) != 0; if (!bitOn) continue; if ((and23 & ithBit) != 0) continue; first += ithBit; } arr.add(first); for (int i = 2; i <= n; i++) { arr.add(or[i]-first+and[i]); } Collections.sort(arr); out.println("finish "+arr.get(k-1)); } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static void input_output() throws IOException { File f = new File("in.txt"); if (f.exists() && !f.isDirectory()) { in = new Reader(new FileInputStream("in.txt")); } else in = new Reader(); f = new File("out.txt"); if (f.exists() && !f.isDirectory()) { out = new PrintWriter(new File("out.txt")); } else out = new PrintWriter(System.out); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
6b51e757b7853bf3d9a7e8e57ed365e6
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
/* "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." */ import java.util.*; import java.lang.*; import java.io.*; public class Codechef { public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = 1; for (int t = 0; t < test; t++) { solve(); } out.close(); } private static void solve() { int n = sc.nextInt(); int k = sc.nextInt(); long x = getSum(1, 2); long y = getSum(2, 3); long z = getSum(1, 3); List<Long> list = new ArrayList<>(); long second = (x + y - z) / 2; long first = x - second; long third = y - second; list.add(first); list.add(second); list.add(third); for (int i = 4; i <= n; i++) { long sum = getSum(1, i); list.add(sum - first); } Collections.sort(list); out.println("finish " + list.get(k - 1)); } private static long getSum(int a, int b) { int and = ask(a, b, true); int or = ask(a, b, false); return and + or; } private static int ask(int a, int b, boolean and) { if (and) { out.print("and "); }else { out.print("or "); } out.println(a + " " + b); out.flush(); int val = sc.nextInt(); return val; } public static FastReader sc; public static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
c6333b8df38fefda0500e76510f281e1
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.io.*; public class TakeaGuess { private static class MyScanner { static BufferedReader br; static StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } private static PrintWriter out = new PrintWriter(System.out); public static int solution(int high, int low ) { int t = high-low; if (t%2==0) return low + t/2; return low + (t+1)/2 ; } public static void main (String[] args) { MyScanner s = new MyScanner(); int n = s.nextInt(); int k = s.nextInt(); out.println("or 1 2"); out.flush(); long a = s.nextLong(); if(a==-1) System.exit(0); out.println("and 1 2"); out.flush(); long b = s.nextLong(); if(b==-1) System.exit(0); long sum1 = a+b; out.println("or 2 3"); out.flush(); a = s.nextLong(); if(a==-1) System.exit(0); out.println("and 2 3"); out.flush(); b = s.nextLong(); if(b==-1) System.exit(0); long sum2 = a+b; out.println("or 1 3"); out.flush(); a = s.nextLong(); if(a==-1) System.exit(0); out.println("and 1 3"); out.flush(); b = s.nextLong(); if(b==-1) System.exit(0); long sum3 = a+b; long[] arr = new long[n]; arr[0] = (sum1+sum3-sum2)/2; arr[1] = (sum1+sum2-sum3)/2; arr[2] = (sum2+sum3-sum1)/2; for(int i = 4; i<=n; i++) { out.println("or 1 "+i); out.flush(); a = s.nextLong(); if(a==-1) System.exit(0); out.println("and 1 "+i); out.flush(); b = s.nextLong(); if(b==-1) System.exit(0); arr[i-1] = a+b-arr[0]; } Arrays.sort(arr); out.println("finish "+arr[k-1]); out.flush(); System.exit(0); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
d5c5df581d3fbcd67c1f6a7e18918a69
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; public class A { static int mod = 1000000007; static Scanner sc; public static void main(String[] args) { sc = new Scanner(System.in); int yo = 1; while (yo-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[n]; int af = and(1,2); int of = or(1,2); int as = and(2,3); int os = or(2,3); int at = and(3,1); int ot = or(3,1); StringBuilder str = new StringBuilder(); for(int i = 0; i < 32; i++) { if((af&(1<<i)) != 0) { str.append("1"); } else if((af&(1<<i)) == 0 && (of&(1<<i)) == 0) { str.append("0"); } else if((as&(1<<i)) != 0) { str.append("0"); } else if((os&(1<<i)) != 0 && (ot&(1<<i)) == 0) { str.append("0"); } else { str.append("1"); } } arr[0] = toNum(str); arr[1] = find(af,of,arr[0]); arr[2] = find(at,ot,arr[0]); for(int i = 3; i < n; i++) { int and = and(1,i+1); int or = or(1,i+1); arr[i] = find(and,or,arr[0]); } sort(arr); int ans = 0; for(int i = 0; i < n; i++) { k--; if(k == 0) { ans = arr[i]; } // out.print(arr[i] + " "); } // out.println(); out.println("finish " + ans); } } /* * 0 * 7 * 4 * 6 * 0 * 5 * 0 * 3 * 1 * 3 * 1 * 5 * 0 * 5 */ private static int find(int af, int of, int num) { StringBuilder str = new StringBuilder(); for(int i = 0; i < 32; i++) { if((af&(1<<i)) != 0) { str.append("1"); } else if((num&(1<<i)) != 0) { str.append("0"); } else if((of&(1<<i)) != 0) { str.append("1"); } else { str.append("0"); } } return toNum(str); } private static int toNum(StringBuilder str) { int num = 0; for(int i = 0; i < str.length(); i++) { if(str.charAt(i) == '1') { num += (1<<i); } } return num; } public static int or(int i, int j) { System.out.println("or " + i + " " + j); return sc.nextInt(); } public static int and(int i, int j) { System.out.println("and " + i + " " + j); return sc.nextInt(); } public static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } public static void sort(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for (int x : arr) ls.add(x); Collections.sort(ls); for (int i = 0; i < arr.length; i++) arr[i] = ls.get(i); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static boolean[] sieve(int N) { boolean[] sieve = new boolean[N + 1]; for (int i = 2; i <= N; i++) sieve[i] = true; for (int i = 2; i <= N; i++) { if (sieve[i]) { for (int j = 2 * i; j <= N; j += i) { sieve[j] = false; } } } return sieve; } public static long power(long x, long y, long p) { long res = 1L; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y >>= 1; x = (x * x) % p; } return res; } public static void print(int[] arr) { //for debugging only for (int x : arr) out.print(x + " "); out.println(); } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] readInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] readDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } // For Input.txt and Output.txt // FileInputStream in = new FileInputStream("input.txt"); // FileOutputStream out = new FileOutputStream("output.txt"); // PrintWriter pw = new PrintWriter(out); // Scanner sc = new Scanner(in); }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
ea12452796298663b12dde18e0ba021a
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.*; import java.io.*; public class Div21556D { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); Integer[] ar = new Integer[n]; //prep System.out.println("or 1 2"); int xy = Integer.parseInt(br.readLine()); System.out.println("and 1 2"); xy += Integer.parseInt(br.readLine()); System.out.println("or 2 3"); int yz = Integer.parseInt(br.readLine()); System.out.println("and 2 3"); yz += Integer.parseInt(br.readLine()); System.out.println("or 1 3"); int xz = Integer.parseInt(br.readLine()); System.out.println("and 1 3"); xz += Integer.parseInt(br.readLine()); int x = -(yz-(xy+xz))/2; int y = xy - x; int z = xz - x; ar[0] = x; ar[1] = y; ar[2] = z; for(int i = 3; i < n; i++) { System.out.println("or " + i + " " + (i+1)); ar[i] = Integer.parseInt(br.readLine()); System.out.println("and " + i + " " + (i+1)); ar[i] += Integer.parseInt(br.readLine()); ar[i] -= ar[i-1]; } List<Integer> res = Arrays.asList(ar); Collections.sort(res); System.out.println("finish " + res.get(k-1)); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
cc0769199efa353cb96ed6e57ce890b4
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class D { static Scanner scn = new Scanner(System.in); public static void main(String[] args) { int n = scn.nextInt(); int k = scn.nextInt(); long[] arr = new long[n]; long aPlusB = and(0, 1) + or(0, 1); long bPlusC = and(1, 2) + or(1, 2); long aPlusC = and(0, 2) + or(0, 2); long sum = aPlusB + bPlusC + aPlusC; sum /= 2; arr[0] = sum - bPlusC; arr[1] = sum - aPlusB; arr[2] = sum - aPlusC; for (int i = 3; i < n; i++) { arr[i] = and(0, i) + or(0, i) - arr[0]; } Arrays.sort(arr); System.out.println("finish " + arr[k - 1]); System.out.flush(); } static int and(int l, int r) { System.out.println("and " + ++l + " " + ++r); System.out.flush(); return scn.nextInt(); } static int or(int l, int r) { System.out.println("or " + ++l + " " + ++r); System.out.flush(); return scn.nextInt(); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
59f8d8a89cabe91a707b2170c73b1894
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class D { public static void main(String[] args) { Scanner s = new Scanner(System.in); solve(s.nextInt(), s.nextInt(), s); } public static void solve(int n, int k, Scanner s) { int nums[] = new int[n]; int o1, o2, o3, a1, a2, a3; int s1, s2, s3; System.out.println("and 1 2"); a3 = s.nextInt(); System.out.println("and 3 2"); a1 = s.nextInt(); System.out.println("and 3 1"); a2 = s.nextInt(); System.out.println("or 1 2"); o3 = s.nextInt(); System.out.println("or 3 2"); o1 = s.nextInt(); System.out.println("or 3 1"); o2 = s.nextInt(); s1 = o1 + a1; s2 = o2 + a2; s3 = o3 + a3; nums[0] = (s2 + s3 + -s1) / 2; nums[1] = (-s2 + s3 + s1) / 2; nums[2] = (s2 + -s3 + s1) / 2; int sum; for (int i = 3; i < n; i++) { sum = 0; System.out.println("or 1 " + (i + 1)); sum += s.nextInt(); System.out.println("and 1 " + (i + 1)); sum += s.nextInt(); nums[i] = sum - nums[0]; } Arrays.sort(nums); System.out.println("finish " + nums[k - 1]); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
dfe00b629400fe20ed50a1051a8e7b67
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { static BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); public static void main(String args[])throws Exception { StringBuilder sb=new StringBuilder(); String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),k=Integer.parseInt(s[1]); int i,or,and; long ans[]=new long[n+1]; or=query(1,2,1); if(or==-1) return; and=query(1,2,2); if(and==-1) return; long ab=2l*and+(and^or); //sum=2*and+xor xor=and^or or=query(2,3,1); if(or==-1) return; and=query(2,3,2); if(and==-1) return; long bc=2l*and+(and^or); or=query(1,3,1); if(or==-1) return; and=query(1,3,2); if(and==-1) return; long ca=2l*and+(and^or); ans[1]=ca+ab-bc; ans[1]/=2; ans[2]=ab-ans[1]; ans[3]=ca-ans[1]; for(i=4;i<=n;i++) { or=query(i,i-1,1); if(or==-1) return; and=query(i,i-1,2); if(and==-1) return; long sum=2l*and+(and^or); ans[i]=sum-ans[i-1]; } PriorityQueue<Long> pq=new PriorityQueue<>(); for(i=1;i<=n;i++) pq.add(ans[i]); long fin=0; while(k-->0) fin=pq.poll(); System.out.println("finish "+fin); System.out.flush(); } static int query(int i,int j,int t)throws Exception { int x=0; if(t==1) { System.out.println("or "+i+" "+j); x=Integer.parseInt(bu.readLine()); System.out.flush(); } else { System.out.println("and "+i+" "+j); x=Integer.parseInt(bu.readLine()); System.out.flush(); } return x; } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
94bc919b1b5f21a83e07b250770d43b7
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.io.*; import java.util.*; public class D { static int mod = (int) (1e9 + 7); static int[] link; static int n, k; static int[][] memo; static int dp(int rem, int idx) { if (idx == n) { return rem == 0 ? 1 : 0; } if (memo[rem][idx] != -1) return memo[rem][idx]; int ret = 0; if (rem == k) { ret = dp(rem, idx + 1) + dp(rem - 1, link[idx]); } else if (rem == 1) { ret = 1 + dp(k, idx + 1) + dp(rem, link[idx]); } else { ret = dp(rem, link[idx]) + dp(rem - 1, link[idx]); } ret %= mod; return memo[rem][idx] = ret; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); // Scanner sc = new Scanner(new File("fortune.in")); // PrintWriter pw = new PrintWriter(System.out); int t = 1; while (t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); System.out.println("or 1 2"); int x = sc.nextInt(); System.out.println("and 1 2"); int y = sc.nextInt(); int a = x + y; System.out.println("or 1 3"); x = sc.nextInt(); System.out.println("and 1 3"); y = sc.nextInt(); int b = x + y; System.out.println("or 2 3"); x = sc.nextInt(); System.out.println("and 2 3"); y = sc.nextInt(); int c = x + y; int sec = (a + c - b) / 2; int fir = a - sec; int rd = c - sec; ArrayList<Integer> ans = new ArrayList<>(); ans.add(sec); ans.add(fir); ans.add(rd); for (int i = 4; i <= n; i++) { System.out.println("or 3 " + i); x = sc.nextInt(); System.out.println("and 3 " + i); y = sc.nextInt(); ans.add(x + y - rd); } Collections.sort(ans); pw.println("finish "+ans.get(k - 1)); } pw.flush(); } static boolean check_nCr_parity(long n, long r) { boolean f = true; // true -> odd for (int i = 0; i < 63; i++) { if (((r >> i) & 1) == 1) { f &= ((n >> i) & 1) == 1; } } return f; } static long[] fac; static void fac() { fac[0] = 1; for (int j = 1; j < fac.length; j++) { fac[j] = fac[j - 1] * j; fac[j] %= mod; } } static long inverse(long n) { return modPow(n, mod - 2, mod); } static long nc(int n, int r) { return ((fac[n] * inverse(fac[r])) % mod) * inverse(fac[n - r]) % mod; } static long modPow(long a, long e, int mod) // O(log e) { a %= mod; long res = 1; while (e > 0) { if ((e & 1) == 1) res = (res * a) % mod; a = (a * a) % mod; e >>= 1; } return res; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(File s) throws FileNotFoundException { br = new BufferedReader(new FileReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
1cc0a9e01eb534b999ff905dc767df79
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.*; import java.io.*; public class Deltix { static MyScanner sc; public static void main(String[] args) { sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = 1; while (t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); int [] a = new int[n]; int and01 = and(0, 1); int or01 = or(0, 1); int and02 = and(0, 2); int or02 = or(0, 2); int and12 = and(1, 2); int or12 = or(1, 2); for (int i = 0; i < 30; i++) { int x = (and01 >> i) & 1; int y = (or01 >> i) & 1; if (x == y) { a[0] += (x << i); a[1] += (x << i); } else { int b = (and02 >> i) & 1; int c = (or02 >> i) & 1; int d = (and12 >> i) & 1; int e = (or12 >> i) & 1; if (b == c) { a[0] += (b << i); a[1] += ((1 - b) << i); } else { a[1] += (d << i); a[0] += ((1 - d) << i); } } } for (int i = 0; i < 30; i++) { int x = (and02 >> i) & 1; int y = (or02 >> i) & 1; int z = (a[0] >> i) & 1; if (z == 0) { a[2] += (y << i); } else { a[2] += (x << i); } } for (int j = 3; j < n; j++) { and02 = and(0, j); or02 = or(0, j); for (int i = 0; i < 30; i++) { int x = (and02 >> i) & 1; int y = (or02 >> i) & 1; int z = (a[0] >> i) & 1; if (z == 0) { a[j] += (y << i); } else { a[j] += (x << i); } } } sort(a); finish(a[k - 1]); } out.close(); } static int and(int a, int b) { ++a; ++b; System.out.println("and " + a + " " + b); System.out.flush(); return sc.nextInt(); } static int or(int a, int b) { ++a; ++b; System.out.println("or " + a + " " + b); System.out.flush(); return sc.nextInt(); } static void finish(int x) { System.out.println("finish " + x); System.out.flush(); } static void sort(int[] a) { ArrayList<Integer> q = new ArrayList<>(); for (int i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } static void sort(long[] a) { ArrayList<Long> q = new ArrayList<>(); for (long i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
d900b27bedde10fd899a92ca58fe04be
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
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.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; public class Main implements Runnable { int n, m, k; long n1, s; static boolean use_n_tests = false; long mod = 1_000_000_007; long mod1 = 998244353L; // Long[][] dp; double scale = 1e+6; char[] s1; Integer[][] dp; int steps = 0; List<Integer> primes = Collections.emptyList();//generatePrimes(31623); boolean[] mark; List<Integer> curComp; Graph g; int[][] ls; int[] coord1, coord2; int[] lasts; boolean[] end1, end2; int ensz1, ensz2; List<Integer> ensz2list; int it = 0; void solve(FastScanner in, PrintWriter out, int testNumber) { n = in.nextInt(); k = in.nextInt(); Long[] sum = new Long[n]; for (int i = 2; i <= n; i++) { long and = ask("and", 1, i); long or = ask("or", 1, i); sum[i - 1] = and + or; } int and = ask("and", 2, 3); int or = ask("or", 2, 3); long bc = and + or; long diff = sum[1] - sum[2]; long C = (bc - diff) / 2; long A = sum[2] - C; sum[0] = A; for (int i = 1; i < n; i++) { sum[i] -= A; } Arrays.sort(sum); out.println("finish " + sum[k - 1]); } // ****************************** template code *********** static public class LcaSparseTable { int len; int[][] up; int[] tin; int[] tout; int time; static List<Integer>[] tree; static LcaSparseTable t; void dfs(List<Integer>[] tree, int u, int p) { tin[u] = time++; up[0][u] = p; for (int i = 1; i < len; i++) up[i][u] = up[i - 1][up[i - 1][u]]; for (int v : tree[u]) if (v != p) dfs(tree, v, u); tout[u] = time++; } public LcaSparseTable(List<Integer>[] tree, int root) { int n = tree.length; len = 1; while ((1 << len) <= n) ++len; up = new int[len][n]; tin = new int[n]; tout = new int[n]; dfs(tree, root, root); } boolean isParent(int parent, int child) { return tin[parent] <= tin[child] && tout[child] <= tout[parent]; } public int lca(int a, int b) { if (isParent(a, b)) return a; if (isParent(b, a)) return b; for (int i = len - 1; i >= 0; i--) if (!isParent(up[i][a], b)) a = up[i][a]; return up[0][a]; } public static void adaptGraph(Graph graph) { int n = graph.size() + 1; tree = new List[n]; for (int i = 0; i < n; i++) { tree[i] = new ArrayList<>(); } List<Integer> edges = graph.getEdges(); for (int i = 0; i < edges.size() / 2; i++) { int v = edges.get(i * 2); int u = edges.get(i * 2 + 1); tree[v].add(u); tree[u].add(v); } t = new LcaSparseTable(tree, 0); } public static int getLca(int a, int b) { return t.lca(a, b); } } List<Integer> factorize(int a) { List<Integer> res = new ArrayList<>(); for (int i = 0; i < primes.size(); i++) { int p = primes.get(i); while (a % p == 0) { res.add(p); a /= p; } if (a == 1 && p > a) { break; } } if (a != 1) { res.add(a); } return res; } void impossible() { out.println(-1); } void yes() { out.println("YES"); } void no() { out.println("NO"); } static boolean next_permutation(char[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1; ; --b) if (p[b] > p[a]) { char t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } public static class DisjointSets { int[] p; DisjointSets(int size) { p = new int[size]; for (int i = 0; i < size; i++) p[i] = i; } public int root(int x) { return x == p[x] ? x : (p[x] = root(p[x])); } public void unite(int a, int b) { a = root(a); b = root(b); if (a != b) p[a] = b; } } boolean triangleCheck(int a, int b, int c) { return a + b > c && a + c > b && b + c > a; } Map<Integer, Integer> numberCompression(List<Integer> ls) { Collections.sort(ls); int id = 1; Map<Integer, Integer> comp = new HashMap<>(); for (int num : ls) { if (!comp.containsKey(num)) { comp.put(num, id++); } } return comp; } long lcm(long a, long b) { return (a / gcd(a, b)) * b; } long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } class Pt { int x, y; Pt(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } boolean sameAxis(Pt b) { return b.x == x || b.y == y; } int manxDist(Pt b) { return Math.abs(x - b.x) + Math.abs(y - b.y); } void read() { x = in.nextInt(); y = in.nextInt(); } } void swap(Integer[] a, int i, int j) { Integer tmp = a[i]; a[i] = a[j]; a[j] = tmp; } void swap(List<Integer> a, int i, int j) { Integer tmp = a.get(i); a.set(i, a.get(j)); a.set(j, tmp); } long manhDist(long x, long y, long x1, long y1) { return Math.abs(x - x1) + Math.abs(y - y1); } double dist(double x, double y, double x1, double y1) { return Math.sqrt(Math.pow(x - x1, 2.0) + Math.pow(y - y1, 2.0)); } public static class FW { public static void add(long[] t, int i, long value) { for (; i < t.length; i |= i + 1) t[i] += value; } public static long sum(long[] t, int i) { long res = 0; for (; i >= 0; i = (i & (i + 1)) - 1) res += t[i]; return res; } public static void add(long[] t, int a, int b, long value) { add(t, a, value); add(t, b + 1, -value); } } int sign(int a) { if (a < 0) { return -1; } return 1; } long binpow(long a, int b) { long res = 1; while (b != 0) { if (b % 2 == 0) { b /= 2; a *= a; a %= mod; } b--; res *= a; res %= mod; } return res; } List<Integer> getDigits(long n) { List<Integer> res = new ArrayList<>(); while (n != 0) { res.add((int) (n % 10L)); n /= 10; } return res; } List<Integer> generatePrimes(int n) { List<Integer> res = new ArrayList<>(); boolean[] sieve = new boolean[n + 1]; for (int i = 2; i <= n; i++) { if (!sieve[i]) { res.add(i); } if ((long) i * i <= n) { for (int j = i * i; j <= n; j += i) { sieve[j] = true; } } } return res; } int ask(String type, int a, int b) { System.out.printf(type + " %d %d\n", a, b); System.out.flush(); return in.nextInt(); } static int stack_size = 1 << 29; static class Coeff { long mod; long[][] C; long[] fact; boolean cycleWay = false; Coeff(int n, long mod) { this.mod = mod; fact = new long[n + 1]; fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = i; fact[i] %= mod; fact[i] *= fact[i - 1]; fact[i] %= mod; } } Coeff(int n, int m, long mod) { // n > m cycleWay = true; this.mod = mod; C = new long[n + 1][m + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.min(i, m); j++) { if (j == 0 || j == i) { C[i][j] = 1; } else { C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; C[i][j] %= mod; } } } } public long C(int n, int m) { if (cycleWay) { return C[n][m]; } return fC(n, m); } private long fC(int n, int m) { return (fact[n] * inv(fact[n - m] * fact[m] % mod)) % mod; } private long inv(long r) { if (r == 1) return 1; return ((mod - mod / r) * inv(mod % r)) % mod; } } class Pair { int first; long second; Pair(int f, long s) { first = f; second = s; } public int getFirst() { return first; } public long getSecond() { return second; } } class MultisetTree<T> { int size = 0; TreeMap<T, Integer> mp = new TreeMap<>(); void add(T x) { mp.merge(x, 1, Integer::sum); size++; } void remove(T x) { if (mp.containsKey(x)) { mp.merge(x, -1, Integer::sum); if (mp.get(x) == 0) { mp.remove(x); } size--; } } boolean contains(T x) { return mp.containsKey(x); } T greatest() { return mp.lastKey(); } T higher(T x) { return mp.higherKey(x); } T smallest() { return mp.firstKey(); } T biggest() { return mp.lastKey(); } int size() { return size; } int diffSize() { return mp.size(); } } class Multiset<T> { int size = 0; Map<T, Integer> mp = new HashMap<>(); void add(T x) { mp.merge(x, 1, Integer::sum); size++; } boolean contains(T x) { return mp.containsKey(x); } void remove(T x) { if (mp.containsKey(x)) { mp.merge(x, -1, Integer::sum); if (mp.get(x) == 0) { mp.remove(x); } size--; } } int size() { return size; } int diffSize() { return mp.size(); } } static class Range { int l, r; int id; public int getL() { return l; } public int getR() { return r; } public Range(int l, int r, int id) { this.l = l; this.r = r; this.id = id; } } static class Array { static Range[] readRanges(int n, FastScanner in) { Range[] result = new Range[n]; for (int i = 0; i < n; i++) { result[i] = new Range(in.nextInt(), in.nextInt(), i); } return result; } static List<List<Integer>> intInit2D(int n) { List<List<Integer>> res = new ArrayList<>(); for (int i = 0; i < n; i++) { res.add(new ArrayList<>()); } return res; } static boolean isSorted(Integer[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } static public long sum(List<Integer> a) { long sum = 0; for (int x : a) { sum += x; } return sum; } static public long sum(int[] a) { long sum = 0; for (int x : a) { sum += x; } return sum; } static public long sum(long[] a) { long sum = 0; for (long x : a) { sum += x; } return sum; } static public long sum(Integer[] a) { long sum = 0; for (int x : a) { sum += x; } return sum; } static public int min(Integer[] a) { int mn = Integer.MAX_VALUE; for (int x : a) { mn = Math.min(mn, x); } return mn; } static public int min(int[] a) { int mn = Integer.MAX_VALUE; for (int x : a) { mn = Math.min(mn, x); } return mn; } static public int max(Integer[] a) { int mx = Integer.MIN_VALUE; for (int x : a) { mx = Math.max(mx, x); } return mx; } static public int max(int[] a) { int mx = Integer.MIN_VALUE; for (int x : a) { mx = Math.max(mx, x); } return mx; } static public int[] readint(int n, FastScanner in) { int[] out = new int[n]; for (int i = 0; i < out.length; i++) { out[i] = in.nextInt(); } return out; } } class Graph { List<List<Integer>> graph; List<Integer> edges; Graph(int n) { create(n); } private void create(int n) { List<List<Integer>> graph = new ArrayList<>(); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } this.graph = graph; edges = new ArrayList<>(); } int size() { return graph.size(); } List<Integer> abj(int v) { return graph.get(v); } void read(int m, FastScanner in) { for (int i = 0; i < m; i++) { int v = in.nextInt() - 1; int u = in.nextInt() - 1; graph.get(v).add(u); } } void readBi(int m, FastScanner in) { for (int i = 0; i < m; i++) { int v = in.nextInt() - 1; int u = in.nextInt() - 1; addEdge(v, u); } } public void addEdge(int v, int u) { graph.get(v).add(u); graph.get(u).add(v); edges.add(v); edges.add(u); } public List<Integer> getEdges() { return edges; } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream io) { br = new BufferedReader(new InputStreamReader(io)); } public String line() { String result = ""; try { result = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return result; } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public char[] nextc() { return next().toCharArray(); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = in.nextInt(); } return res; } public int[] nextArray() { int n = in.nextInt(); return nextArray(n); } public long[] nextArrayL(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = in.nextLong(); } return res; } public Long[] nextArrayL2(int n) { Long[] res = new Long[n]; for (int i = 0; i < n; i++) { res[i] = in.nextLong(); } return res; } public Integer[] nextArray2(int n) { Integer[] res = new Integer[n]; for (int i = 0; i < n; i++) { res[i] = in.nextInt(); } return res; } public long nextLong() { return Long.parseLong(next()); } } void run_t_tests() { int t = in.nextInt(); int i = 0; while (t-- > 0) { solve(in, out, i++); } } void run_one() { solve(in, out, -1); } @Override public void run() { in = new FastScanner(System.in); out = new PrintWriter(System.out); if (use_n_tests) { run_t_tests(); } else { run_one(); } out.close(); } static FastScanner in; static PrintWriter out; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(null, new Main(), "", stack_size); thread.start(); thread.join(); } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
f70c9211b3b50186b195a02a6ff2b9d5
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
//package com.company.codeforces.v210829; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.stream.Collectors; import java.util.stream.IntStream; public class D { FastScanner in; PrintWriter out; public static void main(String[] args) { new D().solve(); } private void solve() { in = new FastScanner(System.in); out = new PrintWriter(System.out); out.println("finish " + solveCase()); out.flush(); } private long solveCase() { int n = in.nextInt(); int k = in.nextInt(); List<Integer> numbers = new ArrayList<>(findFirstThree()); for (int i = 3; i < n; i++) { numbers.add(findNextGivenFirst(numbers.get(0), i)); } Collections.sort(numbers); return numbers.get(k - 1); } private List<Integer> findFirstThree() { int aUb = operate(0, 1, true); int aUc = operate(0, 2, true); int bUc = operate(1, 2, true); int aVb = operate(0, 1, false); int aVc = operate(0, 2, false); int bVc = operate(1, 2, false); int aUbUc = (aUb) | (bUc); int aVbVc = aVb & bVc; int a = (aUbUc & ~(bUc)) | (aVb & ~aVbVc) | (aVc & ~aVbVc) | aVbVc; int b = (aUbUc & ~(aUc)) | (aVb & ~aVbVc) | (bVc & ~aVbVc) | aVbVc; int c = (aUbUc & ~(aUb)) | (bVc & ~aVbVc) | (aVc & ~aVbVc) | aVbVc; return List.of(a, b, c); } private int findNextGivenFirst(int firstValue, int nextId) { int aUx = operate(0, nextId, true); int aVx = operate(0, nextId, false); return ((aUx) & ~firstValue) | (aVx); } private int operate(int id1, int id2, boolean or) { if (or) { out.println("or " + (id1 + 1) + " " + (id2 + 1)); out.flush(); return in.nextInt(); } else { out.println("and " + (id1 + 1) + " " + (id2 + 1)); out.flush(); return in.nextInt(); } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
e064ce6e13016ffc13baff0b6fe3e977
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.util.*; import java.io.*; public class D_1556 { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(), k = sc.nextInt(); pw.println("or 1 2"); pw.flush(); pw.println("and 1 2"); pw.flush(); int k1 = sc.nextInt() + sc.nextInt(); pw.println("or 2 3"); pw.flush(); pw.println("and 2 3"); pw.flush(); int k2 = sc.nextInt() + sc.nextInt(); pw.println("or 1 3"); pw.flush(); pw.println("and 1 3"); pw.flush(); int k3 = sc.nextInt() + sc.nextInt(); int[] array = new int[n]; array[0] = (k1 - k2 + k3) / 2; array[1] = k1 - array[0]; array[2] = k3 - array[0]; for(int i = 3; i < n; i++) { pw.println("or 1 " + (i + 1)); pw.flush(); pw.println("and 1 " + (i + 1)); pw.flush(); int sum = sc.nextInt() + sc.nextInt(); array[i] = sum - array[0]; } Arrays.sort(sc.shuffle(array)); pw.println("finish " + array[k - 1]); pw.flush(); } public static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextIntArray(int n) throws IOException { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = nextInt(); return array; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] array = new Integer[n]; for (int i = 0; i < n; i++) array[i] = new Integer(nextInt()); return array; } public long[] nextLongArray(int n) throws IOException { long[] array = new long[n]; for (int i = 0; i < n; i++) array[i] = nextLong(); return array; } public double[] nextDoubleArray(int n) throws IOException { double[] array = new double[n]; for (int i = 0; i < n; i++) array[i] = nextDouble(); return array; } public static int[] shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
16bffba22326dca57c8cdb5da95513ac
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { static BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); public static void main(String args[])throws Exception { StringBuilder sb=new StringBuilder(); String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),k=Integer.parseInt(s[1]); int i,or,and; long ans[]=new long[n+1]; or=query(1,2,1); if(or==-1) return; and=query(1,2,2); if(and==-1) return; long ab=2l*and+(and^or); //sum=2*and+xor xor=and^or or=query(2,3,1); if(or==-1) return; and=query(2,3,2); if(and==-1) return; long bc=2l*and+(and^or); or=query(1,3,1); if(or==-1) return; and=query(1,3,2); if(and==-1) return; long ca=2l*and+(and^or); ans[1]=ca+ab-bc; ans[1]/=2; ans[2]=ab-ans[1]; ans[3]=ca-ans[1]; for(i=4;i<=n;i++) { or=query(i,i-1,1); if(or==-1) return; and=query(i,i-1,2); if(and==-1) return; long sum=2l*and+(and^or); ans[i]=sum-ans[i-1]; } PriorityQueue<Long> pq=new PriorityQueue<>(); for(i=1;i<=n;i++) pq.add(ans[i]); long fin=0; while(k-->0) fin=pq.poll(); System.out.println("finish "+fin); System.out.flush(); } static int query(int i,int j,int t)throws Exception { int x=0; if(t==1) { System.out.println("or "+i+" "+j); x=Integer.parseInt(bu.readLine()); System.out.flush(); } else { System.out.println("and "+i+" "+j); x=Integer.parseInt(bu.readLine()); System.out.flush(); } return x; } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
8d085cf8f8bb4b39ec1ac31b402290af
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1556d { public static void main(String[] args) throws IOException { int n = rni(), k = ni(), a[] = new int[n]; long ab = sum(0, 1), ac = sum(0, 2), bc = sum(1, 2); a[0] = (int) ((ab + ac - bc) / 2); a[1] = (int) (ab - a[0]); a[2] = (int) (ac - a[0]); for (int i = 3; i < n; ++i) { int sum = sum(0, i); a[i] = sum - a[0]; } rsort(a); pr("finish "); prln(a[k - 1]); close(); } static int sum(int i, int j) throws IOException { pr("and "); pr(i + 1); pr(' '); pr(j + 1); prln(); flush(); int and = ri(); pr("or "); pr(i + 1); pr(' '); pr(j + 1); prln(); flush(); int or = ri(), xor = and ^ or; return and * 2 + xor; } static BufferedReader __i = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __o = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __r = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final long LMAX = 9223372036854775807L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcd(int a, int b) {return b == 0 ? a : gcd(b, a % b);} static long gcd(long a, long b) {return b == 0 ? a : gcd(b, a % b);} static int[] exgcd(int a, int b) {if (b == 0) return new int[] {1, 0}; int[] y = exgcd(b, a % b); return new int[] {y[1], y[0] - y[1] * (a / b)};} static long[] exgcd(long a, long b) {if (b == 0) return new long[] {1, 0}; long[] y = exgcd(b, a % b); return new long[] {y[1], y[0] - y[1] * (a / b)};} static int randInt(int min, int max) {return __r.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static void ria(int[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = ni();} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static void riam1(int[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static void rla(long[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = nl();} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static void rda(double[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = nd();} static char[] rcha() throws IOException {return rline().toCharArray();} static void rcha(char[] a) throws IOException {int n = a.length, i = 0; for (char c : rline().toCharArray()) a[i++] = c;} static String rline() throws IOException {return __i.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} // output static void pr(int i) {__o.print(i);} static void prln(int i) {__o.println(i);} static void pr(long l) {__o.print(l);} static void prln(long l) {__o.println(l);} static void pr(double d) {__o.print(d);} static void prln(double d) {__o.println(d);} static void pr(char c) {__o.print(c);} static void prln(char c) {__o.println(c);} static void pr(char[] s) {__o.print(new String(s));} static void prln(char[] s) {__o.println(new String(s));} static void pr(String s) {__o.print(s);} static void prln(String s) {__o.println(s);} static void pr(Object o) {__o.print(o);} static void prln(Object o) {__o.println(o);} static void prln() {__o.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;}; static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;} static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__o.flush();} static void close() {__o.close();} }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
1b2fac189eb899edcca09b3b3cdec21a
train_107.jsonl
1630247700
This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$.
256 megabytes
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.exit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { static void sort(int a[], int n) { if (n == 0) { return; } for (int i = 1; i < n; i++) { int j = i; int ca = a[i]; do { int nj = (j - 1) >> 1; int na = a[nj]; if (ca <= na) { break; } a[j] = na; j = nj; } while (j != 0); a[j] = ca; } int ca = a[0]; for (int i = n - 1; i > 0; i--) { int j = 0; while ((j << 1) + 2 + Integer.MIN_VALUE < i + Integer.MIN_VALUE) { j <<= 1; j += (a[j + 2] > a[j + 1]) ? 2 : 1; } if ((j << 1) + 2 == i) { j = (j << 1) + 1; } int na = a[i]; a[i] = ca; ca = na; while (j != 0 && a[j] < ca) { j = (j - 1) >> 1; } while (j != 0) { na = a[j]; a[j] = ca; ca = na; j = (j - 1) >> 1; } } a[0] = ca; } static void solve() throws Exception { int n = scanInt(), k = scanInt(); out.println("and 1 2"); out.flush(); int and12 = scanInt(); out.println("or 1 2"); out.flush(); int or12 = scanInt(); out.println("and 2 3"); out.flush(); int and23 = scanInt(); out.println("or 2 3"); out.flush(); int or23 = scanInt(); out.println("and 1 3"); out.flush(); int and13 = scanInt(); out.println("or 1 3"); out.flush(); int or13 = scanInt(); int a[] = new int[n]; a[0] = and12 | and13 | (or12 & ~or23); a[1] = and12 | and23 | (or12 & ~or13); a[2] = and23 | and13 | (or13 & ~or12); for (int i = 3; i < n; i++) { out.println("and 1 " + (i + 1)); out.flush(); int and1i = scanInt(); out.println("or 1 " + (i + 1)); out.flush(); int or1i = scanInt(); a[i] = and1i ^ or1i ^ a[0]; } sort(a, n); out.println("finish " + a[k - 1]); } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
Java
["7 6\n\n2\n\n7"]
2 seconds
["and 2 5\n\nor 5 6\n\nfinish 5"]
NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number.
Java 11
standard input
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
7fb8b73fa2948b360644d40b7035ce4a
It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied.
1,800
null
standard output
PASSED
37f64b3e66c59212a350e610ce3d52f8
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.concurrent.CompletableFuture; import static java.util.Arrays.binarySearch; import static java.util.Arrays.copyOfRange; import static java.util.Arrays.fill; public class Main { public static void main(String[] args) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } } class Task { long[] a, sum; class SegTree { long min,max; } SegTree[] segTrees; public void solve(InputReader in, PrintWriter out) throws Exception { int n = in.nextInt(); int q = in.nextInt(); a = new long[n + 1]; sum = new long[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextLong(); } for (int i = 1; i <= n; i++) { long b = in.nextLong(); a[i] = b - a[i]; } for (int i = 1; i <= n; i++) { sum[i] = sum[i - 1] + a[i]; } segTrees = new SegTree[4 * n]; build(1, 1, n); for (int i = 0; i < q; i++) { int l = in.nextInt(); int r = in.nextInt(); long s = getMin(1, 1, n, l, r); if (sum[r] - sum[l - 1] != 0 || s - sum[l - 1] < 0) { out.println(-1); continue; } long m = getMax(1, 1, n, l, r); out.println(m - sum[l - 1]); } } private void build(int n, int l, int r) { segTrees[n] = new SegTree(); if (l == r) { segTrees[n].min = segTrees[n].max = sum[l]; return; } int m = (l + r) >> 1; build(n << 1, l, m); build(n << 1 | 1, m + 1, r); pushUp(n); } private long getMin(int n, int l, int r, int a, int b) { if (l >= a && r <= b) { return segTrees[n].min; } int m = (l + r) >> 1; long ans = Long.MAX_VALUE; if (a <= m) ans = Math.min(ans, getMin(n << 1, l, m, a, b)); if (b > m) ans = Math.min(ans, getMin(n << 1 | 1, m + 1, r, a, b)); return ans; } private long getMax(int n, int l, int r, int a, int b) { if (l >= a && r <= b) { return segTrees[n].max; } int m = (l + r) >> 1; long ans = Long.MIN_VALUE; if (a <= m) ans = Math.max(ans, getMax(n << 1, l, m, a, b)); if (b > m) ans = Math.max(ans, getMax(n << 1 | 1, m + 1, r, a, b)); return ans; } private void pushUp(int n) { int l = n << 1, r = l + 1; segTrees[n].min = Math.min(segTrees[l].min, segTrees[r].min); segTrees[n].max = Math.max(segTrees[l].max, segTrees[r].max); } } class InputReader { private final 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) { throw new RuntimeException(e); } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(nextLine()); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
4a93afc1835cc37734c43d595f9fe6b3
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.util.*; import java.io.*; public class Main2 { static PrintWriter pw; static Scanner sc; static Random rn = new Random(); static long getSum(int i, int j, long[] pre) { if (i == 0) return pre[j]; return pre[j] - pre[i - 1]; } static long getSum2(int i, int j, long[] pre) { if (j == pre.length - 1) return pre[i]; return pre[i] - pre[j + 1]; } public static void main(String[] args) throws Exception { pw = new PrintWriter(System.out); sc = new Scanner(System.in); int n = sc.nextInt(); int q = sc.nextInt(); int[] a = new int[n], b = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { b[i] = sc.nextInt(); } long[] dif = new long[n]; long[] dif2 = new long[n]; long[] pos = new long[n], neg = new long[n], all = new long[n]; for (int i = 0; i < n; i++) { dif[i] = a[i] - b[i]; all[i] = a[i] - b[i]; if (a[i] - b[i] >= 0) { pos[i] = a[i] - b[i]; } else { neg[i] = -(a[i] - b[i]); } if (i > 0) { dif[i] += dif[i - 1]; pos[i] += pos[i - 1]; neg[i] += neg[i - 1]; } } for (int i = n - 1; i >= 0; i--) { dif2[i] = a[i] - b[i]; if (i < n - 1) dif2[i] += dif2[i + 1]; } // pw.println(Arrays.toString(dif2)); // pw.println(Arrays.toString(dif)); SparseTable stMin = new SparseTable(dif); SparseTable stMin2 = new SparseTable(dif2); SparseTableMax stMax2 = new SparseTableMax(dif2); SparseTableMax stMax = new SparseTableMax(dif); while (q-- > 0) { int l = sc.nextInt() - 1; int r = sc.nextInt() - 1; if (getSum(l, r, dif) == 0) { long maxPref = stMax.query(l, r); int start = l, end = r; while (start <= end) { int mid = start + end >> 1; if (stMax.query(l, mid) >= maxPref) { end = mid - 1; } else start = mid + 1; } boolean canEq = getSum(l, start, neg) >= getSum(l, start, pos); // pw.println(canEq + " " + start + " " + dif[start] + " " + maxPref + " " + getSum(l, start, neg) + " " // + getSum(l, start, pos)); long minSuf = stMin2.query(l, r); start = l; end = r; while (start <= end) { int mid = start + end >> 1; if (stMin2.query(mid, r) > minSuf) { end = mid - 1; } else start = mid + 1; } canEq &= getSum(end, r, pos) >= getSum(end, r, neg); // pw.println(canEq + " " + end + " " + dif[end] + " " + minPref + " " + getSum(end, r, pos) + " " // + getSum(end, r, neg)); long minPref = stMin.query(l, r); start = l; end = r; while (start <= end) { int mid = start + end >> 1; if (stMin.query(l, mid) <= minPref) { end = mid - 1; } else start = mid + 1; } // pw.println(start + " " + getSum(l, start, dif) + " "); long ans = -getSum(l, start, dif); start = l; end = r; long maxSuf = stMax2.query(l, r); while (start <= end) { int mid = start + end >> 1; // pw.println(mid + " " + r + " " + maxSuf + " " + stMax.query(mid, r)); if (stMax2.query(mid, r) == maxSuf) { start = mid + 1; } else end = mid - 1; } ans = Math.max(ans, getSum(end, r, dif2)); // pw.println(end + " " + r + " " + getSum2(end, r, dif2)); if (canEq) { pw.println(ans); } else pw.println(-1); } else pw.println(-1); } pw.flush(); } static class SparseTableMax { long A[], SpT[][]; int log[]; SparseTableMax(long[] A) { int n = A.length; this.A = A; log = new int[n + 1]; for (int i = 2; i <= n; i++) { log[i] = 1 + log[i / 2]; } int k = log[n] + 1; SpT = new long[k][n]; for (int i = 0; i < n; i++) SpT[0][i] = A[i]; for (int j = 1; (1 << j) <= n; j++) for (int i = 0; i + (1 << j) - 1 < n; i++) SpT[j][i] = Math.max(SpT[j - 1][i], SpT[j - 1][i + (1 << (j - 1))]); } long query(int i, int j) { int len = j - i + 1; int k = log[len]; return Math.max(SpT[k][i], SpT[k][j - (1 << k) + 1]); } } static class SparseTable { long A[], SpT[][]; int log[]; SparseTable(long[] A) { int n = A.length; this.A = A; log = new int[n + 1]; for (int i = 2; i <= n; i++) { log[i] = 1 + log[i / 2]; } int k = log[n] + 1; SpT = new long[k][n]; for (int i = 0; i < n; i++) SpT[0][i] = A[i]; for (int j = 1; (1 << j) <= n; j++) for (int i = 0; i + (1 << j) - 1 < n; i++) SpT[j][i] = Math.min(SpT[j - 1][i], SpT[j - 1][i + (1 << (j - 1))]); } long query(int i, int j) { int len = j - i + 1; int k = log[len]; return Math.min(SpT[k][i], SpT[k][j - (1 << k) + 1]); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String r) throws Exception { br = new BufferedReader(new FileReader(new File(r))); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
5a4c834f96c26b09cb8c68371fe16ca6
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.*; import java.util.*; /* */ public class E{ static FastReader sc=null; public static void main(String[] args) { sc=new FastReader(); int n=sc.nextInt(),q=sc.nextInt(); int a[]=sc.readArray(n),b[]=sc.readArray(n); int c[]=new int[n]; long cs[]=new long[n]; for(int i=0;i<n;i++) { if(i>0)cs[i]=cs[i-1]; c[i]=a[i]-b[i]; cs[i]+=c[i]; } RMQ min=new RMQ(n,cs); RGQ max=new RGQ(n,cs); PrintWriter out=new PrintWriter(System.out); while(q-->0) { int l=sc.nextInt()-1,r=sc.nextInt()-1; long sub=(l==0?0:cs[l-1]); long d=cs[r]-sub; if(d!=0) out.println(-1); else { long maxVal=max.Query(l, r); if(maxVal>sub) { out.println(-1); } else { long ans=Math.abs(min.Query(l, r)-sub); out.println(ans); } } } out.close(); } static class RMQ{ int n,LOG; long dp[][]; int log2[]; RMQ(int n,long a[]){ this.n=n; this.LOG= (int)(Math.log(n)/Math.log(2)); dp=new long[LOG+1][n]; for(int i=0;i<n;i++) dp[0][i]=a[i]; log2=new int[n+1]; for(int i=2;i<=n;i++) { log2[i]=log2[i/2]+1; } for(int j=1;j<=LOG;j++) { for(int i=0;i+(1<<j)<=n;i++) { long leftInterval=dp[j-1][i]; long rightInterval=dp[j-1][i+ (1<<(j-1))]; dp[j][i]=combine(leftInterval, rightInterval); } } } long Query(int l,int r) { int len=r-l+1; int p=log2[len]; int k=(1<<p); return combine(dp[p][l], dp[p][r-k+1]); } long combine(long l,long r) { //write how you want to combine the function here return Math.min(l,r); } } static class RGQ{ int n,LOG; long dp[][]; int log2[]; RGQ(int n,long a[]){ this.n=n; this.LOG= (int)(Math.log(n)/Math.log(2)); dp=new long[LOG+1][n]; for(int i=0;i<n;i++) dp[0][i]=a[i]; log2=new int[n+1]; for(int i=2;i<=n;i++) { log2[i]=log2[i/2]+1; } for(int j=1;j<=LOG;j++) { for(int i=0;i+(1<<j)<=n;i++) { long leftInterval=dp[j-1][i]; long rightInterval=dp[j-1][i+ (1<<(j-1))]; dp[j][i]=combine(leftInterval, rightInterval); } } } long Query(int l,int r) { int len=r-l+1; int p=log2[len]; int k=(1<<p); return combine(dp[p][l], dp[p][r-k+1]); } long combine(long l,long r) { //write how you want to combine the function here return Math.max(l,r); } } static int[] ruffleSort(int a[]) { ArrayList<Integer> al=new ArrayList<>(); for(int i:a)al.add(i); Collections.sort(al); for(int i=0;i<a.length;i++)a[i]=al.get(i); return a; } static void print(int a[]) { for(int e:a) { System.out.print(e+" "); } System.out.println(); } static class FastReader{ StringTokenizer st=new StringTokenizer(""); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String next() { while(!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); return a; } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
3b8cca08d8b50dc5d9332bf41172dfdc
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.*; import java.util.*; public class Solution { static class RMQ1 { long[] vs; long[][] lift; public RMQ1(long[] vs) { this.vs = vs; int n = vs.length; int maxlog = Integer.numberOfTrailingZeros(Integer.highestOneBit(n)) + 2; lift = new long[maxlog][n]; for (int i = 0; i < n; i++) lift[0][i] = vs[i]; int lastRange = 1; for (int lg = 1; lg < maxlog; lg++) { for (int i = 0; i < n; i++) { lift[lg][i] = Math.min(lift[lg - 1][i], lift[lg - 1][Math.min(i + lastRange, n - 1)]); } lastRange *= 2; } } public long query(int low, int hi) { int range = hi - low + 1; int exp = Integer.highestOneBit(range); int lg = Integer.numberOfTrailingZeros(exp); return Math.min(lift[lg][low], lift[lg][hi - exp + 1]); } } static class RMQ2 { long[] vs; long[][] lift; public RMQ2(long[] vs) { this.vs = vs; int n = vs.length; int maxlog = Integer.numberOfTrailingZeros(Integer.highestOneBit(n)) + 2; lift = new long[maxlog][n]; for (int i = 0; i < n; i++) lift[0][i] = vs[i]; int lastRange = 1; for (int lg = 1; lg < maxlog; lg++) { for (int i = 0; i < n; i++) { lift[lg][i] = Math.max(lift[lg - 1][i], lift[lg - 1][Math.min(i + lastRange, n - 1)]); } lastRange *= 2; } } public long query(int low, int hi) { int range = hi - low + 1; int exp = Integer.highestOneBit(range); int lg = Integer.numberOfTrailingZeros(exp); return Math.max(lift[lg][low], lift[lg][hi - exp + 1]); } } public static void main(String[] args) throws IOException { FastScanner f= new FastScanner(); int ttt=1; // ttt=f.nextInt(); PrintWriter out=new PrintWriter(System.out); outer: for(int tt=0;tt<ttt;tt++) { int n=f.nextInt(); int q=f.nextInt(); int[] a=f.readArray(n); int[] b=f.readArray(n); int[] l=new int[n]; for(int i=0;i<n;i++) l[i]=a[i]-b[i]; long[] sum=new long[n+1]; for(int i=1;i<=n;i++) { sum[i]=sum[i-1]+l[i-1]; } RMQ1 minq=new RMQ1(sum); RMQ2 maxq=new RMQ2(sum); for(int i=0;i<q;i++) { int start=f.nextInt(); int end=f.nextInt(); long suma=sum[end]-sum[start-1]; long maxa=maxq.query(start, end)-sum[start-1]; long mina=minq.query(start, end)-sum[start-1]; if(suma==0 && maxa<=0) { out.println(-mina); } else out.println(-1); } } out.close(); } static void sort(int[] p) { ArrayList<Integer> q = new ArrayList<>(); for (int i: p) q.add( i); Collections.sort(q); for (int i = 0; i < p.length; i++) p[i] = q.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
d64679eed7da3cd072b4ee4be15d83db
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
// Don't place your source in a package import javax.swing.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //reading /writing file //Scanner sc=new Scanner(new File("src/text.txt")); //PrintWriter pr=new PrintWriter("output.txt"); //File file = new File("src/text.txt"); int T=1; for(int t=0;t<T;t++){ Solution sol1=new Solution(out,fs); sol1.solution(t); } out.flush(); } public static int[] Arr(int n){ int A[]=new int[n]; for(int i=0;i<n;i++)A[i]=Int(); return A; } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution { PrintWriter out; int INF = Integer.MAX_VALUE; int NINF = Integer.MIN_VALUE; int MOD = 998244353; int mod = 1000000007; Main.FastScanner fs; public Solution(PrintWriter out,Main.FastScanner fs) { this.out = out; this.fs=fs; } long pre[]; public void solution(int testcase) { int n = fs.Int(); int m = fs.Int(); int A[]=new int[n]; int B[]=new int[n]; for(int i = 0; i < n; i++){ A[i]=fs.Int(); } pre=new long[n]; for(int i = 0; i < n; i++){ A[i]=fs.Int() - A[i]; pre[i] += A[i]; if(i-1>=0)pre[i]+=pre[i-1]; } //System.out.println(Arrays.toString(pre)); Seg seg = new Seg(0,pre.length-1); while(m>0){ m--; int l = fs.Int()-1; int r = fs.Int()-1; long s = get(pre,l,r); if(s!=0){ out.println(-1); continue; } long min = seg.query1(l,r); long p = 0; if(l!=0)p=pre[l-1]; if(min-p < 0){ out.println(-1); continue; } long mx = seg.query(l,r); out.println(mx - p); } } public long get(long A[],int l,int r){ if(l==0)return A[r]; return A[r]-A[l-1]; } class Seg{ int l,r; long max= Long.MIN_VALUE; long min = Long.MAX_VALUE; Seg left=null,right=null; public Seg(int l,int r){ this.l=l; this.r=r; if(l!=r){ int mid=l+(r-l)/2; if(l<=mid)left=new Seg(l,mid); if(r>=mid+1)right=new Seg(mid+1,r); this.max=Math.max(max,right.max); this.max=Math.max(max,left.max); this.min=Math.min(min,right.min); this.min=Math.min(min,left.min); }else{ this.max = pre[l]; this.min=pre[l]; } } public long query(int s,int e){ if(l==s&&r==e){ return max; } int mid=l+(r-l)/2; //left : to mid-1, if(e<=mid){ return left.query(s,e); } else if(s>=mid+1){ return right.query(s,e); }else{ return Math.max(left.query(s,mid),right.query(mid+1,e)); } } public long query1(int s,int e){ if(l==s&&r==e){ return min; } int mid=l+(r-l)/2; //left : to mid-1, if(e<=mid){ return left.query1(s,e); } else if(s>=mid+1){ return right.query1(s,e); }else{ return Math.min(left.query1(s,mid),right.query1(mid+1,e)); } } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
15d9d7f69424b677c6b42543914d2e51
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; public class TaskD { static long mod = 1000000007; static FastScanner scanner; static final StringBuilder result = new StringBuilder(); public static void main(String[] args) { scanner = new FastScanner(); solve(); } static void solve() { int n = scanner.nextInt(); int q = scanner.nextInt(); int[] a = scanner.nextIntArray(n); int[] b = scanner.nextIntArray(n); long[] rem = new long[n]; long[] sum = new long[n]; for (int i = 0; i < n; i++) { rem[i] = b[i] - a[i]; sum[i] = b[i] - a[i]; } int[] p = new int[n]; Arrays.fill(p, Integer.MAX_VALUE); long[] s = new long[n]; for (int i = 0; i < n; i++) { if (b[i] < a[i]) { long cnt = a[i] - b[i]; long steps = 0; int j = i - 1; while (cnt > 0) { if (j < 0) { j = -1; steps = -1; break; } if (b[j] < a[j]) { steps = Math.max(steps, s[j]); j = p[j]; continue; } long toUse = Math.min(rem[j], cnt); cnt -= toUse; rem[j] -= toUse; steps += toUse; if (cnt == 0) break; j--; } p[i] = j; s[i] = steps; } } long[] lp = new long[n]; for (int i = 0; i < n; i++) lp[i]=p[i]; SegTree minIdx = new SegTree(Math::min, lp, Integer.MAX_VALUE); SegTree maxIds = new SegTree(Math::max, s, 0); SegTree sums = new SegTree(Long::sum, sum, 0); for (int qq = 0; qq < q; qq++) { int l = scanner.nextInt() - 1; int r = scanner.nextInt() - 1; long sumRange = sums.query(l, r + 1); long minRange = minIdx.query(l, r + 1); if (sumRange != 0 || minRange < l) { result.append(-1).append("\n"); continue; } result.append(maxIds.query(l, r + 1)).append("\n"); } System.out.println(result.toString()); } static class SegTree { // limit for array size static int N = 300000; int n; // array size SegTreeFn fn; long[] tree = new long[N]; long def; interface SegTreeFn { long invoke(long a, long b); } SegTree(SegTreeFn fn, long[] arr, long def) { n = arr.length; this.def = def; this.fn = fn; Arrays.fill(tree, def); // insert leaf nodes in tree for (int i = 0; i < n; i++) { tree[n + i] = arr[i]; } // build the tree by calculating // parents for (int i = n - 1; i > 0; --i) { tree[i] = fn.invoke(tree[i << 1], tree[i << 1 | 1]); } } // function to update a tree node void updateTreeNode(int p, int value) { // set value at position p tree[p + n] = value; p = p + n; // move upward and update parents for (int i = p; i > 1; i >>= 1) { tree[i >> 1] = fn.invoke(tree[i], tree[i ^ 1]); } } // function to get sum on // interval [l, r) long query(int l, int r) { long res = def; // loop to find the sum in the range for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) > 0) { res = fn.invoke(res, tree[l++]); } if ((r & 1) > 0) { res = fn.invoke(res, tree[--r]); } } return res; } } static class FenwickMin { private final long[] data; FenwickMin(long[] init) { data = new long[init.length]; for (int i = 0; i < init.length; i++) { update(i, init[i]); } } private void update(int at, long by) { while (at < data.length) { data[at] = Math.min(data[at], by); at |= (at + 1); } } private long query(int at) { long res = Long.MAX_VALUE; while (at >= 0) { res = Math.min(data[at], res); at = (at & (at + 1)) - 1; } return res; } } static class WithIdx implements Comparable<WithIdx> { static int[] order = {0, 1, 3, 2, 4}; int val, idx; public WithIdx(int val, int idx) { this.val = val; this.idx = idx; } @Override public int compareTo(WithIdx o) { if (val == o.val) { return Integer.compare(idx, o.idx); } return Integer.compare(order[val], order[o.val]); } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } long[] nextLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = nextLong(); return res; } String[] nextStringArray(int n) { String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = nextToken(); return res; } } static class PrefixSums { long[] sums; public PrefixSums(long[] sums) { this.sums = sums; } public long sum(int fromInclusive, int toExclusive) { if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong value"); return sums[toExclusive] - sums[fromInclusive]; } public static PrefixSums of(int[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } public static PrefixSums of(long[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } } static class ADUtils { static void sort(int[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } static void reverse(int[] arr) { int last = arr.length / 2; for (int i = 0; i < last; i++) { int tmp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = tmp; } } static void sort(long[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap long a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } } static class MathUtils { static long[] FIRST_PRIMES = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051}; static long[] primes(int to) { long[] all = new long[to + 1]; long[] primes = new long[to + 1]; all[1] = 1; int primesLength = 0; for (int i = 2; i <= to; i++) { if (all[i] == 0) { primes[primesLength++] = i; all[i] = i; } for (int j = 0; j < primesLength && i * primes[j] <= to && all[i] >= primes[j]; j++) { all[(int) (i * primes[j])] = primes[j]; } } return Arrays.copyOf(primes, primesLength); } static long modpow(long b, long e, long m) { long result = 1; while (e > 0) { if ((e & 1) == 1) { /* multiply in this bit's contribution while using modulus to keep * result small */ result = (result * b) % m; } b = (b * b) % m; e >>= 1; } return result; } static long submod(long x, long y, long m) { return (x - y + m) % m; } static long modInverse(long a, long m) { long g = gcdF(a, m); if (g != 1) { throw new IllegalArgumentException("Inverse doesn't exist"); } else { // If a and m are relatively prime, then modulo // inverse is a^(m-2) mode m return modpow(a, m - 2, m); } } static public long gcdF(long a, long b) { while (b != 0) { long na = b; long nb = a % b; a = na; b = nb; } return a; } } } //25 18 47 //11
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
af7274ee52a7b9ae418779775258ac83
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.math.*; import java.io.*; public class Main { public static void main(String[] args) throws FileNotFoundException { InputReader in = new InputReader(System.in); // Scanner in = new Scanner(System.in); // Scanner in = new Scanner(new BufferedReader(new // InputStreamReader(System.in))); PrintWriter out = new PrintWriter(System.out); // InputReader in = new InputReader(new // File("ethan_traverses_a_tree.txt")); // PrintWriter out = new PrintWriter(new // File("ethan_traverses_a_tree-output.txt")); int n = in.nextInt(); int q = in.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } for (int i = 0; i < n; i++) { b[i] = in.nextInt(); } long[] c = new long[n]; long[] sum = new long[n]; for (int i = 0; i < n; i++) { c[i] = b[i] - a[i]; if (i == 0) { sum[i] = c[i]; } else { sum[i] = sum[i - 1] + c[i]; } } SegmentTree stsig = new SegmentTree(n, c); SegmentTree stsum = new SegmentTree(n, sum); for (int p = 0; p < q; p++) { int l = in.nextInt(); int r = in.nextInt(); long ans = -1; if (stsig.querySum(l, r) == 0) { long presum = 0; if (l > 1) { presum = stsig.querySum(1, l - 1); } long rangesummin = stsum.queryMin(l, r) - presum; if (rangesummin >= 0) { ans = stsum.queryMax(l, r) - presum; } } out.printf("%d\n", ans); } out.close(); } static class SegmentTree { private int n; // [1, n] is valid private long[] dataMin; private long[] dataMax; private long[] dataSum; static final long INF = (long)1 << 60; public SegmentTree(int m) { this.n = 1; while (this.n < m) { this.n = this.n * 2; } int nn = this.n * 2; this.dataMin = new long[nn]; this.dataMax = new long[nn]; this.dataSum = new long[nn]; } public SegmentTree(int m, long[] a) { // a[0] .. a[m-1] is valid this(m); for (int i = n; i < 2 * n; i++) { int aIndex = i - n; if (aIndex >= m) { dataMin[i] = dataMax[i] = dataSum[i] = 0; } else { dataMin[i] = dataMax[i] = dataSum[i] = a[aIndex]; } } for (int i = n - 1; i >= 1; i--) { int leftChild = this.getLeftChild(i); int rightChild = this.getRightChild(i); dataMin[i] = Math.min(dataMin[leftChild], this.dataMin[rightChild]); dataMax[i] = Math.max(dataMax[leftChild], this.dataMax[rightChild]); dataSum[i] = dataSum[leftChild] + dataSum[rightChild]; } } private int getLeftChild(int nowIndex) { return nowIndex * 2; } private int getRightChild(int nowIndex) { return nowIndex * 2 + 1; } public long querySum(int y1, int y2) { SegmentTreeResult result = this.queryAll(y1, y2); return result.sum; } public long queryMin(int y1, int y2) { SegmentTreeResult result = this.queryAll(y1, y2); return result.min; } public long queryMax(int y1, int y2) { SegmentTreeResult result = this.queryAll(y1, y2); return result.max; } public SegmentTreeResult queryAll(int y1, int y2) { SegmentTreeResult result = this._query(y1, y2, 1, 1, this.n); return result; } private SegmentTreeResult _query(int y1, int y2, int nowIndex, int leftBound, int rightBound) { SegmentTreeResult result = new SegmentTreeResult(); if (y1 <= leftBound && y2 >= rightBound) { result.min = dataMin[nowIndex]; result.max = dataMax[nowIndex]; result.sum = dataSum[nowIndex]; // System.out.println("cover " + nowIndex + " " + result.sum); return result; } int leftChild = this.getLeftChild(nowIndex); int rightChild = this.getRightChild(nowIndex); result.min = SegmentTree.INF; result.max = -SegmentTree.INF; result.sum = 0; int mid = leftBound + (rightBound - leftBound) / 2; if (y1 <= mid) { SegmentTreeResult leftResult = this._query(y1, y2, leftChild, leftBound, mid); result.min = Math.min(result.min, leftResult.min); result.max = Math.max(result.max, leftResult.max); result.sum += leftResult.sum; } if (y2 > mid) { SegmentTreeResult rightResult = this._query(y1, y2, rightChild, mid + 1, rightBound); result.min = Math.min(result.min, rightResult.min); result.max = Math.max(result.max, rightResult.max); result.sum += rightResult.sum; } // System.out.println("nomal " + nowIndex + " " + result.sum); return result; } public void set(int y, int val) { this._set(y, val, 1, 1, n); } private void _set(int y, int val, int nowIndex, int leftBound, int rightBound) { if (leftBound == rightBound) { dataMin[nowIndex] = dataMax[nowIndex] = dataSum[nowIndex] = val; } else { int leftChild = this.getLeftChild(nowIndex); int rightChild = this.getRightChild(nowIndex); int mid = leftBound + (rightBound - leftBound) / 2; if (y <= mid) { this._set(y, val, leftChild, leftBound, mid); } else { this._set(y, val, rightChild, mid + 1, rightBound); } dataMin[nowIndex] = Math.min(dataMin[leftChild], dataMin[rightChild]); dataMax[nowIndex] = Math.max(dataMax[leftChild], dataMax[rightChild]); dataSum[nowIndex] = dataSum[leftChild] + dataSum[rightChild]; } } } static class SegmentTreeResult { public long min; public long max; public long sum; } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public boolean hasNext() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
62e7275e12319cad4bc68acf25288f78
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.*; import java.util.*; import java.util.function.BinaryOperator; public class E { //--------------------------INPUT READER--------------------------------// static class fs { public BufferedReader br; StringTokenizer st = new StringTokenizer(""); public fs() { this(System.in); } public fs(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() { while (!st.hasMoreTokens()) { 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 ns() { return next(); } int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } } //-----------------------------------------------------------------------// //---------------------------PRINTER-------------------------------------// static class Printer { static PrintWriter w; public Printer() {this(System.out);} public Printer(OutputStream os) { w = new PrintWriter(os); } public void p(int i) {w.println(i);}; public void p(long l) {w.println(l);}; public void p(double d) {w.println(d);}; public void p(String s) { w.println(s);}; public void pr(int i) {w.println(i);}; public void pr(long l) {w.print(l);}; public void pr(double d) {w.print(d);}; public void pr(String s) { w.print(s);}; public void pl() {w.println();}; public void close() {w.close();}; } //------------------------------------------------------------------------// //--------------------------VARIABLES------------------------------------// static fs sc = new fs(); static OutputStream outputStream = System.out; static Printer w = new Printer(outputStream); //-----------------------------------------------------------------------// //--------------------------ADMIN_MODE-----------------------------------// private static void ADMIN_MODE() throws IOException { if (System.getProperty("ONLINE_JUDGE") == null) { w = new Printer(new FileOutputStream("output.txt")); sc = new fs(new FileInputStream("input.txt")); } } //-----------------------------------------------------------------------// //----------------------------START--------------------------------------// public static void main(String[] args) throws IOException { ADMIN_MODE(); // int t = sc.ni(); // while(t-->0) solve(); w.close(); } static void solve() throws IOException { int n = sc.ni(); int q = sc.ni(); long[] a = new long[n]; long[] b = new long[n]; for(int i = 0; i < n; i++) a[i] = sc.nl(); for(int i = 0; i < n; i++) b[i] = sc.nl(); long[] diff = new long[n]; for(int i = 0; i < n; i++) { diff[i] = a[i]-b[i]; } long[] diffPre = new long[n+1]; for(int i = 1; i <= n; i++) { diffPre[i] = diff[i-1] + diffPre[i-1]; } SparseTable st = new SparseTable(diffPre, SparseTable.Operation.MAX); SparseTable st2 = new SparseTable(diffPre, SparseTable.Operation.MIN); while(q-->0) { int l = sc.ni(); int r = sc.ni(); l--; r--; if(diffPre[l] != diffPre[r+1]) { w.p(-1); continue; } long maxQ = st.query(l, r+1); long minQ = st2.query(l, r+1); if(maxQ>diffPre[l]) { w.p(-1); continue; } w.p((diffPre[l]-minQ)); } } /** * Sparse table only supports immutable structures * <p>Specify the operation using "Operation" public enum in the constructor</p> * Enter the range on which you want to perform query [l, r] both inclusive * <p>min, max and gcd queries are constant</p> * sum query is logarithmic * <p> query index is used to find the index of the min/max values</p> */ // region SparseTable static class SparseTable { // The number of elements in the original input array. private int n; // The maximum power of 2 needed. This value is floor(log2(n)) private int P; // Fast log base 2 logarithm lookup table for i, 1 <= i <= n private int[] log2; // The sparse table values. private long[][] dp; // Index Table (IT) associated with the values in the sparse table. private int[][] it; // The various supported query operations on this sparse table. public enum Operation { MIN, MAX, SUM, MULT, GCD } ; private Operation op; // All functions must be associative, e.g: a * (b * c) = (a * b) * c for some operation '*' private BinaryOperator<Long> sumFn = (a, b) -> a + b; private BinaryOperator<Long> minFn = (a, b) -> Math.min(a, b); private BinaryOperator<Long> maxFn = (a, b) -> Math.max(a, b); private BinaryOperator<Long> multFn = (a, b) -> a * b; private BinaryOperator<Long> gcdFn = (a, b) -> { long gcd = a; while (b != 0) { gcd = b; b = a % b; a = gcd; } return Math.abs(gcd); }; public SparseTable(long[] values, Operation op) { // TODO(william): Lazily call init in query methods instead of initializing in constructor? this.op = op; init(values); } private void init(long[] v) { n = v.length; // Tip: to get the floor of the logarithm base 2 in Java you can also do: // Integer.numberOfTrailingZeros(Integer.highestOneBit(n)). P = (int) (Math.log(n) / Math.log(2)); dp = new long[P + 1][n]; it = new int[P + 1][n]; for (int i = 0; i < n; i++) { dp[0][i] = v[i]; it[0][i] = i; } log2 = new int[n + 1]; for (int i = 2; i <= n; i++) { log2[i] = log2[i / 2] + 1; } // Build sparse table combining the values of the previous intervals. for (int i = 1; i <= P; i++) { for (int j = 0; j + (1 << i) <= n; j++) { long leftInterval = dp[i - 1][j]; long rightInterval = dp[i - 1][j + (1 << (i - 1))]; // [j+(1<<(i-1))] = j + 2^(i-1) // Watch in insertion slides for more info if (op == Operation.MIN) { dp[i][j] = minFn.apply(leftInterval, rightInterval); // Propagate the index of the best value if (leftInterval <= rightInterval) { it[i][j] = it[i - 1][j]; } else { it[i][j] = it[i - 1][j + (1 << (i - 1))]; } } else if (op == Operation.MAX) { dp[i][j] = maxFn.apply(leftInterval, rightInterval); // Propagate the index of the best value if (leftInterval >= rightInterval) { it[i][j] = it[i - 1][j]; } else { it[i][j] = it[i - 1][j + (1 << (i - 1))]; } } else if (op == Operation.SUM) { dp[i][j] = sumFn.apply(leftInterval, rightInterval); } else if (op == Operation.MULT) { dp[i][j] = multFn.apply(leftInterval, rightInterval); } else if (op == Operation.GCD) { dp[i][j] = gcdFn.apply(leftInterval, rightInterval); } } } // Uncomment for debugging // printTable(); } // For debugging, testing and slides. private void printTable() { for (long[] r : dp) { for (int i = 0; i < r.length; i++) { System.out.printf("%02d, ", r[i]); } System.out.println(); } } // Queries [l, r] for the operation set on this sparse table. public long query(int l, int r) { // Fast queries types, O(1) if (op == Operation.MIN) { return query(l, r, minFn); } else if (op == Operation.MAX) { return query(l, r, maxFn); } else if (op == Operation.GCD) { return query(l, r, gcdFn); } // Slower query types, O(log2(n)) if (op == Operation.SUM) { return sumQuery(l, r); } else { return multQuery(l, r); } } public int queryIndex(int l, int r) { if (op == Operation.MIN) { return minQueryIndex(l, r); } else if (op == Operation.MAX) { return maxQueryIndex(l, r); } throw new UnsupportedOperationException( "Operation type: " + op + " doesn't support index queries :/"); } private int minQueryIndex(int l, int r) { int len = r - l + 1; int p = log2[len]; long leftInterval = dp[p][l]; long rightInterval = dp[p][r - (1 << p) + 1]; if (leftInterval <= rightInterval) { return it[p][l]; } else { return it[p][r - (1 << p) + 1]; } } private int maxQueryIndex(int l, int r) { int len = r - l + 1; int p = log2[len]; long leftInterval = dp[p][l]; long rightInterval = dp[p][r - (1 << p) + 1]; if (leftInterval >= rightInterval) { return it[p][l]; } else { return it[p][r - (1 << p) + 1]; } } // Do sum query [l, r] in O(log2(n)). // // Perform a cascading query which shrinks the left endpoint while summing over all the intervals // which are powers of 2 between [l, r]. // // WARNING: This method can easily produces values that overflow. // // NOTE: You can achieve a faster time complexity and use less memory with a simple prefix sum // array. This method is here more as a proof of concept than for its usefulness. private long sumQuery(int l, int r) { long sum = 0; for (int p = log2[r - l + 1]; l <= r; p = log2[r - l + 1]) { sum += dp[p][l]; l += (1 << p); } return sum; } private long multQuery(int l, int r) { long result = 1; for (int p = log2[r - l + 1]; l <= r; p = log2[r - l + 1]) { result *= dp[p][l]; l += (1 << p); } return result; } // Do either a min, max or gcd query on the interval [l, r] in O(1). // // We can get O(1) query by finding the smallest power of 2 that fits within the interval length // which we'll call k. Then we can query the intervals [l, l+k] and [r-k+1, r] (which likely // overlap) and apply the function again. Some functions (like min and max) don't care about // overlapping intervals so this trick works, but for a function like sum this would return the // wrong result since it is not an idempotent binary function. private long query(int l, int r, BinaryOperator<Long> fn) { int len = r - l + 1; int p = log2[len]; return fn.apply(dp[p][l], dp[p][r - (1 << p) + 1]); } } // endregion }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
8aae92dc5e26a224932a604333fb6d11
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Arrays; import java.util.Random; import java.io.FileWriter; import java.io.PrintWriter; /* Solution Created: 01:59:27 30/08/2021 Custom Competitive programming helper. */ public class Main { public static void solve() { int n = in.nextInt(), q = in.nextInt(); int[] a = new int[n]; for(int i = 0; i<n; i++) a[i] += in.nextInt(); for(int i = 0; i<n; i++) a[i] -= in.nextInt(); long[] pre = new long[n+1]; for(int i = 1; i<=n; i++) pre[i] = pre[i-1] + a[i-1]; SegmentTreeMIN prefixMin = new SegmentTreeMIN(pre); SegmentTreeMAX prefixMax = new SegmentTreeMAX(pre); while(q-->0) { int l = in.nextInt()-1, r = in.nextInt()-1; long d = pre[r+1]-pre[l]; long maxPrefix = prefixMax.query(l, r)-pre[l]; if(d!=0 || maxPrefix>0) { out.println(-1); continue; } out.println(Math.abs(prefixMin.query(l, r)-pre[l])); } } public static void main(String[] args) { in = new Reader(); out = new Writer(); int t = 1; while(t-->0) solve(); out.exit(); } static class SegmentTreeMIN{ long dummyValue = Long.MAX_VALUE; public long operation(long a, long b){ return Math.min(a, b); } //Modify the values above according to the required operations (i.e. for sum: operation = a+b, dummyValue = 0) private long[] tree; int n; public SegmentTreeMIN(long[] a) { this.n = a.length; this.tree = new long[4*n]; build(0, 0, n-1, a); } public SegmentTreeMIN(int n) { this.n = n; this.tree = new long[4*n]; } private void build(int idx, int l, int r, long[] a) { if(l==r) tree[idx] = a[l]; else { int m = (l+r)/2; build(2*idx+1, l, m, a); build(2*idx+2,m+1,r, a); tree[idx] = operation(tree[2*idx+1], tree[2*idx+2]); } } public void update(int idx, long weight) { updateUtil(0, 0, n-1, idx, weight); } private void updateUtil(int idx ,int l, int r, int i, long weight) { if(l==r) tree[idx] = weight; else { int md = (l+r)/2; if(i<=md) updateUtil(2*idx+1, l, md, i, weight); else updateUtil(2*idx+2, md+1, r, i, weight); tree[idx] = operation(tree[2*idx+1], tree[2*idx+2]); } } public long query(int l, int r) { return queryUtil(0, l, r, 0, n-1); } private long queryUtil(int idx, int lBound, int rBound, int l, int r) { if(rBound < l || r < lBound) return dummyValue; if(lBound <= l && r<= rBound) return tree[idx]; int md = (l+r)/2; return operation(queryUtil(2*idx+1, lBound, rBound, l, md), queryUtil(2*idx+2, lBound, rBound, md+1, r)); } } static class SegmentTreeMAX{ long dummyValue = Long.MIN_VALUE; public long operation(long a, long b){ return Math.max(a, b); } //Modify the values above according to the required operations (i.e. for sum: operation = a+b, dummyValue = 0) private long[] tree; int n; public SegmentTreeMAX(long[] pre) { this.n = pre.length; this.tree = new long[4*n]; build(0, 0, n-1, pre); } public SegmentTreeMAX(int n) { this.n = n; this.tree = new long[4*n]; } private void build(int idx, int l, int r, long[] a) { if(l==r) tree[idx] = a[l]; else { int m = (l+r)/2; build(2*idx+1, l, m, a); build(2*idx+2,m+1,r, a); tree[idx] = operation(tree[2*idx+1], tree[2*idx+2]); } } public void update(int idx, long weight) { updateUtil(0, 0, n-1, idx, weight); } private void updateUtil(int idx ,int l, int r, int i, long weight) { if(l==r) tree[idx] = weight; else { int md = (l+r)/2; if(i<=md) updateUtil(2*idx+1, l, md, i, weight); else updateUtil(2*idx+2, md+1, r, i, weight); tree[idx] = operation(tree[2*idx+1], tree[2*idx+2]); } } public long query(int l, int r) { return queryUtil(0, l, r, 0, n-1); } private long queryUtil(int idx, int lBound, int rBound, int l, int r) { if(rBound < l || r < lBound) return dummyValue; if(lBound <= l && r<= rBound) return tree[idx]; int md = (l+r)/2; return operation(queryUtil(2*idx+1, lBound, rBound, l, md), queryUtil(2*idx+2, lBound, rBound, md+1, r)); } } static Reader in; static Writer out; static class Reader { static BufferedReader br; static StringTokenizer st; 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 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() { ensureNext(); return Integer.parseInt(st.nextToken()); } public double nextDouble() { ensureNext(); return Double.parseDouble(st.nextToken()); } public Long nextLong() { ensureNext(); return Long.parseLong(st.nextToken()); } public String next() { ensureNext(); return st.nextToken(); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } private void ensureNext() { if (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } } } 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 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; } static long pow(long x, long pow, long mod){ long res = 1; x = x % mod; if (x == 0) return 0; while (pow > 0){ if ((pow & 1) != 0) res = (res * x) % mod; pow >>= 1; x = (x * x) % mod; } return res; } 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 yesNo(boolean condition) { println(condition?"YES":"NO"); } 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
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
7b19a2c8c78bf337481d649bb1409e27
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class E { public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int n=fs.nextInt(), q=fs.nextInt(); long[] a=fs.readArray(n), b=fs.readArray(n); long[] diffs=new long[n]; for (int i=0; i<n; i++) diffs[i]=a[i]-b[i]; long[] cs=new long[n+1]; for (int i=1; i<=n; i++) cs[i]=diffs[i-1]+cs[i-1]; RMaxQ maxQ=new RMaxQ(cs); RMinQ minQ=new RMinQ(cs); for (int qq=0; qq<q; qq++) { int l=fs.nextInt()-1, r=fs.nextInt()-1; long startCS=cs[l], endCS=cs[r+1]; if (startCS!=endCS) { out.println(-1); continue; } long maxCS=maxQ.query(l+1, r+1); if (maxCS>startCS) { out.println(-1); continue; } long minCS=minQ.query(l+1, r+1); out.println(startCS-minCS); } out.close(); } static class RMaxQ { long[] vs; long[][] lift; public RMaxQ(long[] vs) { this.vs = vs; int n = vs.length; int maxlog = Integer.numberOfTrailingZeros(Integer.highestOneBit(n)) + 2; lift = new long[maxlog][n]; for (int i = 0; i < n; i++) lift[0][i] = vs[i]; int lastRange = 1; for (int lg = 1; lg < maxlog; lg++) { for (int i = 0; i < n; i++) { lift[lg][i] = Math.max(lift[lg - 1][i], lift[lg - 1][Math.min(i + lastRange, n - 1)]); } lastRange *= 2; } } public long query(int low, int hi) { int range = hi - low + 1; int exp = Integer.highestOneBit(range); int lg = Integer.numberOfTrailingZeros(exp); return Math.max(lift[lg][low], lift[lg][hi - exp + 1]); } } static class RMinQ { long[] vs; long[][] lift; public RMinQ(long[] vs) { this.vs = vs; int n = vs.length; int maxlog = Integer.numberOfTrailingZeros(Integer.highestOneBit(n)) + 2; lift = new long[maxlog][n]; for (int i = 0; i < n; i++) lift[0][i] = vs[i]; int lastRange = 1; for (int lg = 1; lg < maxlog; lg++) { for (int i = 0; i < n; i++) { lift[lg][i] = Math.min(lift[lg - 1][i], lift[lg - 1][Math.min(i + lastRange, n - 1)]); } lastRange *= 2; } } public long query(int low, int hi) { int range = hi - low + 1; int exp = Integer.highestOneBit(range); int lg = Integer.numberOfTrailingZeros(exp); return Math.min(lift[lg][low], lift[lg][hi - exp + 1]); } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long[] readArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
135ad828a09dc93ed72d0ab62a74b1d2
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run() { work(); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } long inf=Long.MAX_VALUE/3; long[] sum1;//最大 long[] sum2;//最小 void work() { int n=ni(),q=ni(); sum1=new long[n<<2]; sum2=new long[n<<2]; Arrays.fill(sum1,-inf); Arrays.fill(sum2,inf); long[] A=new long[n]; for(int i=0;i<n;i++){ A[i]=-ni(); } for(int i=0;i<n;i++){ A[i]+=ni(); } long[] sum=new long[n]; for(int i=0;i<n;i++){ sum[i]=A[i]+(i==0?0:sum[i-1]); add(1,i,sum[i],0,n-1); } for(;q>0;q--){ int s=ni()-1,e=ni()-1; if(sum[e]-(s==0?0:sum[s-1])!=0){ out.println(-1); continue; } long[] ret=query(1,s,e,0,n-1); if(ret[1]-(s==0?0:sum[s-1])<0){ out.println(-1); continue; } out.println(ret[0]-(s==0?0:sum[s-1])); } } private long[] query(int node, int s, int e, int l, int r) { if(l>=s&&r<=e){ return new long[]{sum1[node],sum2[node]}; } int m=(l+r)/2; long[] ret=null; if(m>=s){ ret=query(node<<1,s,e,l,m); } if(m+1<=e){ long[] ret2=query(node<<1|1,s,e,m+1,r); if(ret==null){ ret=ret2; }else{ ret[0]=Math.max(ret[0],ret2[0]); ret[1]=Math.min(ret[1],ret2[1]); } } return ret; } private void add(int node, int idx, long v, int l, int r) { int m=(l+r)/2; if(l==r){ sum1[node]=v; sum2[node]=v; return; } if(idx<=m){ add(node<<1,idx,v,l,m); }else{ add(node<<1|1,idx,v,m+1,r); } sum1[node]=Math.max(sum1[node<<1],sum1[node<<1|1]); sum2[node]=Math.min(sum2[node<<1],sum2[node<<1|1]); } @SuppressWarnings("unused") private ArrayList<Integer>[] ng(int n, int m) { ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { int s=in.nextInt()-1,e=in.nextInt()-1; graph[s].add(e); graph[e].add(s); } return graph; } private ArrayList<long[]>[] ngw(int n, int m) { ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong(); graph[(int)s].add(new long[] {e,w}); graph[(int)e].add(new long[] {s,w}); } return graph; } private int ni() { return in.nextInt(); } private long nl() { return in.nextLong(); } private double nd() { return in.nextDouble(); } private String ns() { return in.next(); } private long[] na(int n) { long[] A=new long[n]; for(int i=0;i<n;i++) { A[i]=in.nextLong(); } return A; } private int[] nia(int n) { int[] A=new int[n]; for(int i=0;i<n;i++) { A[i]=in.nextInt(); } return A; } } class FastReader { BufferedReader br; StringTokenizer st; InputStreamReader input;//no buffer public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public FastReader(boolean isBuffer) { if(!isBuffer){ input=new InputStreamReader(System.in); }else{ br=new BufferedReader(new InputStreamReader(System.in)); } } public boolean hasNext(){ try{ String s=br.readLine(); if(s==null){ return false; } st=new StringTokenizer(s); }catch(IOException e){ e.printStackTrace(); } return true; } public String next() { if(input!=null){ try { StringBuilder sb=new StringBuilder(); int ch=input.read(); while(ch=='\n'||ch=='\r'||ch==32){ ch=input.read(); } while(ch!='\n'&&ch!='\r'&&ch!=32){ sb.append((char)ch); ch=input.read(); } return sb.toString(); }catch (Exception e){ e.printStackTrace(); } } while(st==null || !st.hasMoreElements())//回车,空行情况 { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return (int)nextLong(); } public long nextLong() { try { if(input!=null){ long ret=0; int b=input.read(); while(b<'0'||b>'9'){ b=input.read(); } while(b>='0'&&b<='9'){ ret=ret*10+(b-'0'); b=input.read(); } return ret; } }catch (Exception e){ e.printStackTrace(); } return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
1812162112d623dec1b6ebe6f654a23c
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
/* stream Butter! eggyHide eggyVengeance I need U xiao rerun when */ import static java.lang.Math.*; import java.util.*; import java.io.*; import java.math.*; public class x1556E { public static void main(String hi[]) throws Exception { FastScanner infile = new FastScanner(); int N = infile.nextInt(); int Q = infile.nextInt(); int[] arr = infile.nextInts(N); int[] brr = infile.nextInts(N); for(int i=0; i < N; i++) arr[i] -= brr[i]; //increase 1, decrease 1, etc long[] psums = new long[N]; psums[0] = arr[0]; for(int i=1; i < N; i++) psums[i] = psums[i-1]+arr[i]; LazySegTree segtree = new LazySegTree(N); LazySegTreeMin rmq = new LazySegTreeMin(N); for(int i=0; i < N; i++) { segtree.update(i, i, psums[i]); rmq.update(i, i, psums[i]); } ArrayList<Query> queries = new ArrayList<Query>(); for(int i=0; i < Q; i++) { int left = infile.nextInt()-1; int right = infile.nextInt()-1; queries.add(new Query(left, right, i)); } Collections.sort(queries); long[] res = new long[Q]; int pointer = 0; for(Query q: queries) { int L = q.left; int R = q.right; while(pointer < L) { segtree.update(pointer, N-1, -1*arr[pointer]); rmq.update(pointer, N-1, -1*arr[pointer]); pointer++; } long tot = psums[R]; if(L > 0) tot -= psums[L-1]; if(tot != 0) res[q.id] = -1; else { if(segtree.query(L, R) > 0) res[q.id] = -1; else res[q.id] = -1*rmq.query(L, R); } } StringBuilder sb = new StringBuilder(); for(long x: res) sb.append(x+"\n"); System.out.print(sb); } } class LazySegTree { //definitions private long NULL = Long.MIN_VALUE/2; private long[] tree; private long[] lazy; private int length; public LazySegTree(int N) { length = N; int b; for(b=0; (1<<b) < length; b++); tree = new long[1<<(b+1)]; lazy = new long[1<<(b+1)]; } public long query(int left, int right) { //left and right are 0-indexed return get(1, 0, length-1, left, right); } private long get(int v, int currL, int currR, int L, int R) { if(L > R) return NULL; if(L <= currL && currR <= R) return tree[v]; propagate(v); int mid = (currL+currR)/2; return comb(get(v*2, currL, mid, L, Math.min(R, mid)), get(v*2+1, mid+1, currR, Math.max(L, mid+1), R)); } public void update(int left, int right, long delta) { add(1, 0, length-1, left, right, delta); } private void add(int v, int currL, int currR, int L, int R, long delta) { if(L > R) return; if(currL == L && currR == R) { //exact covering tree[v] += delta; lazy[v] += delta; return; } propagate(v); int mid = (currL+currR)/2; add(v*2, currL, mid, L, Math.min(R, mid), delta); add(v*2+1, mid+1, currR, Math.max(L, mid+1), R, delta); tree[v] = comb(tree[v*2], tree[v*2+1]); } private void propagate(int v) { //tree[v] already has lazy[v] if(lazy[v] == 0) return; tree[v*2] += lazy[v]; lazy[v*2] += lazy[v]; tree[v*2+1] += lazy[v]; lazy[v*2+1] += lazy[v]; lazy[v] = 0; } private long comb(long a, long b) { return max(a,b); } } class LazySegTreeMin { //definitions private long NULL = Long.MAX_VALUE/2; private long[] tree; private long[] lazy; private int length; public LazySegTreeMin(int N) { length = N; int b; for(b=0; (1<<b) < length; b++); tree = new long[1<<(b+1)]; lazy = new long[1<<(b+1)]; } public long query(int left, int right) { //left and right are 0-indexed return get(1, 0, length-1, left, right); } private long get(int v, int currL, int currR, int L, int R) { if(L > R) return NULL; if(L <= currL && currR <= R) return tree[v]; propagate(v); int mid = (currL+currR)/2; return comb(get(v*2, currL, mid, L, Math.min(R, mid)), get(v*2+1, mid+1, currR, Math.max(L, mid+1), R)); } public void update(int left, int right, long delta) { add(1, 0, length-1, left, right, delta); } private void add(int v, int currL, int currR, int L, int R, long delta) { if(L > R) return; if(currL == L && currR == R) { //exact covering tree[v] += delta; lazy[v] += delta; return; } propagate(v); int mid = (currL+currR)/2; add(v*2, currL, mid, L, Math.min(R, mid), delta); add(v*2+1, mid+1, currR, Math.max(L, mid+1), R, delta); tree[v] = comb(tree[v*2], tree[v*2+1]); } private void propagate(int v) { //tree[v] already has lazy[v] if(lazy[v] == 0) return; tree[v*2] += lazy[v]; lazy[v*2] += lazy[v]; tree[v*2+1] += lazy[v]; lazy[v*2+1] += lazy[v]; lazy[v] = 0; } private long comb(long a, long b) { return min(a,b); } } class Query implements Comparable<Query> { public int left; public int right; public int id; public Query(int a, int b, int i) { left = a; right = b; id = i; } public int compareTo(Query oth) { return left-oth.left; } } class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
fc05afb092d7e799eee1dd6b79026ce2
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class E { public static void main(String[] args) throws IOException { /**/ Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in))); /*/ Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/e.in")))); /**/ int n = sc.nextInt(); int q = sc.nextInt(); long[] diffs = new long[n+2]; for (int i = 1; i <= n; ++i) { diffs[i] -= sc.nextLong(); } for (int i = 1; i <= n; ++i) { diffs[i] += sc.nextLong(); } long[][] dsum = new long[17][n+2]; long[][] dsmax = new long[17][n+2]; long[][] dsmin = new long[17][n+2]; for (int i = 1; i <= n; ++i) { dsum[0][i] = diffs[i]; dsmax[0][i] = dsum[0][i]; dsmin[0][i] = dsum[0][i]; } for (int i = 1; i < 17; ++i) { for (int j = 1; j <= n; ++j) { int j2 = j+(1<<(i-1)); if (j2>n) break; dsum[i][j] = dsum[i-1][j]+dsum[i-1][j2]; dsmax[i][j] = Math.max(dsmax[i-1][j], dsum[i-1][j]+dsmax[i-1][j2]); dsmin[i][j] = Math.min(dsmin[i-1][j], dsum[i-1][j]+dsmin[i-1][j2]); } } for (int i = 0; i < q; ++i) { int l = sc.nextInt(); int r = sc.nextInt()+1; long sum = 0; long max = -1234567890123456L; long min = 1234567890123456L; for (int j = 16; j >= 0; --j) { if (r-l>=(1<<j)) { max = Math.max(max, sum+dsmax[j][l]); min = Math.min(min, sum+dsmin[j][l]); sum += dsum[j][l]; l+=1<<j; } } if (sum!=0||min<0) { System.out.println(-1); continue; } System.out.println(max); } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 8
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
53498ac670d007303796c2e01dda9823
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //static final long mod=(long)1e9+7; /*static final long mod=998244353L; public static long pow(long a,long p) { long res=1; while(p>0) { if(p%2==1) { p--; res*=a; res%=mod; } else { a*=a; a%=mod; p/=2; } } return res; }*/ /*static class Pair { int u,v; Pair(int u,int v) { this.u=u; this.v=v; } }*/ /*static class Pair implements Comparable<Pair> { int v,l; Pair(int v,int l) { this.v=v; this.l=l; } public int compareTo(Pair p) { return l-p.l; } }*/ /*static long gcd(long a,long b) { if(b%a==0) return a; return gcd(b%a,a); } public static void dfs(int u,ArrayList<Integer> edge[],boolean vis[]) { vis[u]=true; for(int v:edge[u]) { if(!vis[v]) dfs(v,edge,vis); } } static class DSU { int par[],rank[],n; DSU(int n) { this.n=n; par=new int[n+1]; rank=new int[n+1]; for(int i=1;i<=n;i++) par[i]=i; } public void union(int u,int v) { u=find(u); v=find(v); if(u==v) return; if(rank[u]>rank[v]) par[v]=u; else if(rank[u]<rank[v]) par[u]=v; else { rank[v]++; par[u]=v; } } public int find(int u) { if(u==par[u]) return u; return par[u]=find(par[u]); } } static class Edge { int v,ind; long w; Edge(int v,int w,int ind) { this.ind=ind; this.v=v; this.w=1L*w; } } static class Pair implements Comparable<Pair> { int u,v; Pair(int u,int v) { this.u=u; this.v=v; } public int compareTo(Pair p) { if(this.u!=p.u) return this.u-p.u; return p.v-this.v; } }*/ /*static class Pair { long sum,pre,suf,max; Pair(long sum,long pre,long suf,long max) { this.sum=sum; this.pre=pre; this.max=max; this.suf=suf; } } static Pair[] p1,p2; public static void build(int l,int r,long a[],long b[],int ind) { if(l==r) { if(a[l]==b[l]) { p1[ind]=new Pair(0,0,0,0); p2[ind]=new Pair(0,0,0,0); } else { if(a[l]>b[l]) { p1[ind]=new Pair(a[l]-b[l],a[l]-b[l],a[l]-b[l],a[l]-b[l]); p2[ind]=new Pair(-(long)1e14,-(long)1e14,-(long)1e14,-(long)1e14); } else { p1[ind]=new Pair(-(long)1e14,-(long)1e14,-(long)1e14,-(long)1e14); p2[ind]=new Pair(-a[l]+b[l],-a[l]+b[l],-a[l]+b[l],-a[l]+b[l]); } } return; } int mid=(l+r)/2; build(l,mid,a,b,2*ind+1); build(mid+1,r,a,b,2*ind+2); p1[ind]=new Pair(0,0,0,0); p1[ind].sum=p1[2*ind+1].sum+p1[2*ind+2].sum; p1[ind].pre=Math.max(p1[2*ind+1].pre,p1[2*ind+1].sum+p1[2*ind+2].pre); p1[ind].suf=Math.max(p1[2*ind+2].suf,p1[2*ind+2].sum+p1[2*ind+1].suf); p1[ind].max=Math.max(p1[2*ind+1].max,Math.max(p1[2*ind+2].max,p1[2*ind+1].suf+p1[2*ind+2].pre)); p2[ind]=new Pair(0,0,0,0); p2[ind].sum=p2[2*ind+1].sum+p2[2*ind+2].sum; p2[ind].pre=Math.max(p2[2*ind+1].pre,p2[2*ind+1].sum+p2[2*ind+2].pre); p2[ind].suf=Math.max(p2[2*ind+2].suf,p2[2*ind+2].sum+p2[2*ind+1].suf); p2[ind].max=Math.max(p2[2*ind+1].max,Math.max(p2[2*ind+2].max,p2[2*ind+1].suf+p2[2*ind+2].pre)); } public static Pair q1(int s,int e,int l,int r,int ind) { //System.out.println(s+" "+e+" "+l+" "+r+" "+p1[ind].pre+" "+p1[ind].suf+" "+p1[ind].max+" "+p1[ind].max); if(l>e||r<s) return new Pair(-(long)1e14,-(long)1e14,-(long)1e14,-(long)1e14); if(l>=s&&r<=e) return p1[ind]; int mid=(l+r)/2; Pair pp1=q1(s,e,l,mid,2*ind+1); Pair pp2=q1(s,e,mid+1,r,2*ind+2); Pair pp3=new Pair(0,0,0,0); pp3.sum=pp1.sum+pp2.sum; pp3.pre=Math.max(pp1.pre,pp1.sum+pp2.pre); pp3.suf=Math.max(pp2.suf,pp2.sum+pp1.suf); pp3.max=Math.max(pp1.max,Math.max(pp2.max,pp1.suf+pp2.pre)); return pp3; } public static Pair q2(int s,int e,int l,int r,int ind) { //System.out.println(s+" "+e+" "+l+" "+r+" "+p1[ind].pre+" "+p1[ind].suf+" "+p1[ind].max+" "+p1[ind].max); if(l>e||r<s) return new Pair(-(long)1e14,-(long)1e14,-(long)1e14,-(long)1e14); if(l>=s&&r<=e) return p2[ind]; int mid=(l+r)/2; Pair pp1=q2(s,e,l,mid,2*ind+1); Pair pp2=q2(s,e,mid+1,r,2*ind+2); Pair pp3=new Pair(0,0,0,0); pp3.sum=pp1.sum+pp2.sum; pp3.pre=Math.max(pp1.pre,pp1.sum+pp2.pre); pp3.suf=Math.max(pp2.suf,pp2.sum+pp1.suf); pp3.max=Math.max(pp1.max,Math.max(pp2.max,pp1.suf+pp2.pre)); return pp3; }*/ static long seg[],seg2[]; public static void build(int l,int r,long pref[],int ind) { if(l==r) { seg[ind]=seg2[ind]=pref[l]; return; } int mid=(l+r)/2; build(l,mid,pref,2*ind+1); build(mid+1,r,pref,2*ind+2); seg[ind]=Math.max(seg[2*ind+1],seg[2*ind+2]); seg2[ind]=Math.min(seg2[2*ind+1],seg2[2*ind+2]); } public static long q1(int s,int e,int l,int r,int ind) { if(r<s||l>e) return Long.MAX_VALUE; if(l>=s&&r<=e) return seg2[ind]; int mid=(l+r)/2; return Math.min(q1(s,e,l,mid,2*ind+1),q1(s,e,mid+1,r,2*ind+2)); } public static long q2(int s,int e,int l,int r,int ind) { if(r<s||l>e) return Long.MIN_VALUE; if(l>=s&&r<=e) return seg[ind]; int mid=(l+r)/2; return Math.max(q2(s,e,l,mid,2*ind+1),q2(s,e,mid+1,r,2*ind+2)); } public static void main(String args[])throws Exception { FastReader fs=new FastReader(); PrintWriter pw=new PrintWriter(System.out); //int tc=fs.nextInt(); int tc=1; while(tc-->0) { int n=fs.nextInt(); int q=fs.nextInt(); long a[]=new long[n]; long b[]=new long[n]; for(int i=0;i<n;i++) a[i]=fs.nextLong(); for(int i=0;i<n;i++) b[i]=fs.nextLong(); //p1=new Pair[4*n]; //p2=new Pair[4*n]; seg=new long[4*n]; seg2=new long[4*n]; long pref[]=new long[n]; pref[0]=a[0]-b[0]; TreeSet<Integer> ts1=new TreeSet<>(); TreeSet<Integer> ts2=new TreeSet<>(); for(int i=1;i<n;i++) { pref[i]+=pref[i-1]+a[i]-b[i]; if(a[i]!=b[i]) { if(a[i]<b[i]) ts1.add(i); else ts2.add(i); } } build(0,n-1,pref,0); while(q-->0) { int l=fs.nextInt()-1; int r=fs.nextInt()-1; long win=pref[r]-(l>0?pref[l-1]:0); if(win!=0) pw.println(-1); else { //Pair s1=q1(l,r,0,n-1,0); //Pair s2=q2(l,r,0,n-1,0); //pw.println(Math.max(s1.max,s2.max)); long rem=0; if(l>0) rem=pref[l-1]; long s1=q1(l,r,0,n-1,0)-rem; long s2=q2(l,r,0,n-1,0)-rem; if(s2>0) pw.println(-1); else pw.println(Math.max(-s1,s2)); } } } pw.flush(); pw.close(); } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
6e0c38bd8922ec560487571ba9710408
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.*; import java.util.*; public class gotoJapan { public static void main(String[] args) throws java.lang.Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solution solver = new Solution(); boolean isTest = false; int tC = isTest ? Integer.parseInt(in.next()) : 1; for (int i = 1; i <= tC; i++) solver.solve(in, out, i); out.close(); } /* ............................................................. */ static class Solution { InputReader in; PrintWriter out; class SegmentTree { Pair seg[]; long arr[]; int n; public SegmentTree(long arr[], int n) { this.n = n; seg = new Pair[n * 4]; this.arr = arr; } Pair task(Pair a, Pair b) { return new Pair(Math.min(a.x, b.x),Math.max(a.y, b.y)); } Pair mSeg(int i, int l, int r) { if (l == r) { seg[i] = task(new Pair(arr[l], arr[l]), new Pair(arr[l], arr[l])); return seg[i]; } int m = (l + r) / 2; return seg[i] = task(mSeg(2 * i + 1, l, m), mSeg(2 * i + 2, m + 1, r)); } Pair qSeg(int ql, int qr, int i, int l, int r) { if (r < ql || l > qr) return new Pair((long)1e18, (long)(-1e18));// TO DO if (ql <= l && qr >= r) return seg[i]; int m = (l + r) / 2; return task(qSeg(ql, qr, 2 * i + 1, l, m), qSeg(ql, qr, 2 * i + 2, m + 1, r)); } } public void solve(InputReader in, PrintWriter out, int test) { this.in = in; this.out = out; int n=ni(); int q=ni(); long a[]=nal(n); long b[]=nal(n); long pre[]=new long[n+1]; long suf[]=new long[n+2]; for(int i=1;i<=n;i++) { pre[i]=pre[i-1]+b[i-1]-a[i-1]; suf[n-i+1]=suf[n-i+2]+(a[n-i]-b[n-i]); } SegmentTree seg=new SegmentTree(pre, n+1); SegmentTree seg1=new SegmentTree(suf, n+2); seg.mSeg(0, 0, n); seg1.mSeg(0, 0, n); for(int i=1;i<=q;i++) { int l=ni(); int r=ni(); Pair x=seg.qSeg(l, r, 0, 0, n); Pair y=seg1.qSeg(l, r, 0, 0, n); if((x.x-pre[l-1])<0l||(y.x-suf[r+1])<0) { out.println(-1); } else { out.println(Math.min(x.y-pre[l-1],y.y-suf[r+1])); } } } class Pair { long x; long y; Pair(long x, long y) { this.x = x; this.y = y; } } char[] n() { return in.next().toCharArray(); } int ni() { return in.nextInt(); } long nl() { return in.nextLong(); } long[] nal(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } void pn(long zx) { out.println(zx); } void pn(String sz) { out.println(sz); } void pn(double dx) { out.println(dx); } void pn(long ar[]) { for (int i = 0; i < ar.length; i++) out.print(ar[i] + " "); out.println(); } void pn(String ar[]) { for (int i = 0; i < ar.length; i++) out.println(ar[i]); } } /* ......................Just Input............................. */ static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } /* ......................Just Input............................. */ }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
8a5e98193553720451b817e67324fcf2
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.*; import java.util.*; public class E { static int n, q; static int[] a, b; static long[] c, ps; public static void main(String[] args) throws IOException{ FastIO file = new FastIO(); n = file.nextInt(); q = file.nextInt(); a = new int[n]; b = new int[n]; c = new long[n]; for (int i=0; i<n; i++){ a[i] = file.nextInt(); } for (int i=0; i<n; i++){ b[i] = file.nextInt(); } for (int i=0; i<n; i++){ c[i] = b[i]-a[i]; } ps = new long[n+1]; for (int i=1; i<=n; i++){ ps[i] = ps[i-1] + c[i-1]; } SegTree st = new SegTree(n+1); st.build(ps); long[] ans = new long[q]; for (int i=0; i<q; i++){ // 1 based int l = file.nextInt(); int r = file.nextInt(); // Check if at any point the bracket sequence becomes negative long rangeMin = st.queryMin(l, r+1); long rangeMax = st.queryMax(l, r+1); if (ps[r] - ps[l-1] != 0 || rangeMin - ps[l-1] != 0){ ans[i] = -1; }else{ ans[i] = rangeMax - ps[l-1]; } } for (long i : ans){ file.println(i); } file.close(); } static class SegTree{ int size; long[] min, max; public SegTree(int n){ size = 1; while (size < n){ size *= 2; } min = new long[2*size]; max = new long[2*size]; } public void build(long[] arr){ build(arr, 0, 0, size); } public void build(long[] arr, int node, int l, int r){ if (r - l == 1){ if (l < arr.length){ min[node] = arr[l]; max[node] = arr[l]; }else{ min[node] = Long.MAX_VALUE; max[node] = Long.MIN_VALUE; } return; } int mid = (l + r)/2; build(arr, 2*node+1, l, mid); build(arr, 2*node+2, mid, r); min[node] = Math.min(min[2*node+1], min[2*node+2]); max[node] = Math.max(max[2*node+1], max[2*node+2]); } // public void set(int pos, int val){ // set(pos, val, 0, 0, size); // } // public void set(int pos, int val, int node, int l, int r){ // if (r - l == 1){ // min[node] = val; // max[node] = val; // return; // } // int mid = (l + r)/2; // if (pos < mid){ // set(pos, val, 2*node+1, l, mid); // }else{ // set(pos, val, 2*node+2, mid, r); // } // min[node] = Math.min(min[2*node+1], min[2*node+2]); // max[node] = Math.max(max[2*node+1], max[2*node+2]); // } public long queryMin(int l, int r){ // [l, r) -> not inclusive of r return queryMin(l, r, 0, 0, size); } public long queryMin(int l, int r, int node, int cl, int cr){ // l, r = target queryMin range, cx, cy = the current segment tree range we are looking at if (cl >= r || cr <= l){ return Long.MAX_VALUE; } if (cl >= l && cr <= r){ return min[node]; // We want the entire current range } int mid = (cl + cr)/2; long s1 = queryMin(l, r, 2*node+1, cl, mid); long s2 = queryMin(l, r, 2*node+2, mid, cr); return Math.min(s1, s2); } public long queryMax(int l, int r){ // [l, r) -> not inclusive of r return queryMax(l, r, 0, 0, size); } public long queryMax(int l, int r, int node, int cl, int cr){ // l, r = target queryMin range, cx, cy = the current segment tree range we are looking at if (cl >= r || cr <= l){ return Long.MIN_VALUE; } if (cl >= l && cr <= r){ return max[node]; // We want the entire current range } int mid = (cl + cr)/2; long s1 = queryMax(l, r, 2*node+1, cl, mid); long s2 = queryMax(l, r, 2*node+2, mid, cr); return Math.max(s1, s2); } } static class FastIO extends PrintWriter { private InputStream stream; private byte[] buf = new byte[1<<16]; private int curChar, numChars; public FastIO() { this(System.in,System.out); } public FastIO(InputStream i, OutputStream o) { super(o); stream = i; } public FastIO(String i, String o) throws IOException { super(new FileWriter(o)); stream = new FileInputStream(i); } public FastIO(String i) throws IOException { super(System.out); stream = new FileInputStream(i); } // throws InputMismatchException() if previously detected end of file private int nextByte() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars == -1) return -1; // end of file } return buf[curChar++]; } // to read in entire lines, replace c <= ' ' // with a function that checks whether c is a line break public String next() { int c; do { c = nextByte(); } while (c <= ' '); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > ' '); return res.toString(); } public int nextInt() { int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10*res+c-'0'; c = nextByte(); } while (c > ' '); return res * sgn; } public long nextLong() { int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10*res+c-'0'; c = nextByte(); } while (c > ' '); return res * sgn; } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
588e7bb109bf329bb06342e2764dd9da
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class CF_1556_E{ //SOLUTION BEGIN void pre() throws Exception{} void solve(int TC) throws Exception{ int N = ni(), Q = ni(); long[] A = new long[1+N]; for(int i = 1; i<= N; i++)A[i] -= nl(); for(int i = 1; i<= N; i++)A[i] += nl(); long[] P = new long[1+N]; for(int i = 1; i<= N; i++)P[i] = P[i-1]+A[i]; MinTree min = new MinTree(P); MaxTree max = new MaxTree(P); for(int q = 0; q< Q; q++){ int L = ni(), R = ni(); long mn = min.query(L, R-1) - P[L-1], mx = max.query(L, R-1)-P[L-1]; if(mn < 0 || P[R] != P[L-1])pn(-1); else pn(mx); } } class MinTree { private long initValue(){return IINF;} private long update(long oldValue, long newValue){return oldValue+newValue;} private long merge(long le, long ri){return Math.min(le, ri);} private long initQuery(){return IINF;} private int m= 1; private long[] t; public MinTree(int n){ while(m<n)m<<=1; t = new long[m<<1]; Arrays.fill(t, initValue()); } public MinTree(long[] a){ while(m<a.length)m<<=1; t = new long[m<<1]; Arrays.fill(t, initValue()); for(int i = 0; i< a.length; i++)t[i+m] = a[i]; for(int i = m-1; i>0; i--)t[i] = merge(t[i<<1], t[i<<1|1]); } public void update(int i, long val){ t[i += m] = update(t[i], val); for(i>>=1;i>0;i>>=1)t[i] = merge(t[i<<1], t[i<<1|1]); } public long query(int l, int r){ long lans = initQuery(), rans = initQuery(); for(l+=m,r+=m+1;l<r;l>>=1,r>>=1){ if((l&1)==1)lans = merge(lans, t[l++]); if((r&1)==1)rans = merge(t[--r], rans); } return merge(lans, rans); } } class MaxTree { private long initValue(){return -IINF;} private long update(long oldValue, long newValue){return oldValue+newValue;} private long merge(long le, long ri){return Math.max(le,ri);} private long initQuery(){return -IINF;} private int m= 1; private long[] t; public MaxTree(int n){ while(m<n)m<<=1; t = new long[m<<1]; Arrays.fill(t, initValue()); } public MaxTree(long[] a){ while(m<a.length)m<<=1; t = new long[m<<1]; Arrays.fill(t, initValue()); for(int i = 0; i< a.length; i++)t[i+m] = a[i]; for(int i = m-1; i>0; i--)t[i] = merge(t[i<<1], t[i<<1|1]); } public void update(int i, long val){ t[i += m] = update(t[i], val); for(i>>=1;i>0;i>>=1)t[i] = merge(t[i<<1], t[i<<1|1]); } public long query(int l, int r){ long lans = initQuery(), rans = initQuery(); for(l+=m,r+=m+1;l<r;l>>=1,r>>=1){ if((l&1)==1)lans = merge(lans, t[l++]); if((r&1)==1)rans = merge(t[--r], rans); } return merge(lans, rans); } } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} void exit(boolean b){if(!b)System.exit(0);} static void dbg(Object... o){System.err.println(Arrays.deepToString(o));} final long IINF = (long)1e15; final int INF = (int)1e9+2; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8; static boolean multipleTC = false, memory = true, fileIO = false; FastReader in;PrintWriter out; void run() throws Exception{ long ct = System.currentTimeMillis(); if (fileIO) { in = new FastReader(""); out = new PrintWriter(""); } else { in = new FastReader(); out = new PrintWriter(System.out); } //Solution Credits: Taranpreet Singh int T = multipleTC? ni():1; pre(); for (int t = 1; t <= T; t++) solve(t); out.flush(); out.close(); System.err.println(System.currentTimeMillis() - ct); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new CF_1556_E().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 28).start(); else new CF_1556_E().run(); } int[][] make(int n, int e, int[] from, int[] to, boolean f){ int[][] g = new int[n][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = to[i]; if(f)g[to[i]][--cnt[to[i]]] = from[i]; } return g; } int[][][] makeS(int n, int e, int[] from, int[] to, boolean f){ int[][][] g = new int[n][][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0}; if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1}; } return g; } int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));} int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;} long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object... o){for(Object oo:o)out.print(oo+" ");} void pn(Object... o){for(int i = 0; i< o.length; i++)out.print(o[i]+(i+1 < o.length?" ":"\n"));} void pni(Object... o){for(Object oo:o)out.print(oo+" ");out.println();out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
c463e3e8ae5eb65d1dff6d334a6a4733
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
/* "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." */ import java.util.*; import java.lang.*; import java.io.*; public class Codechef { static class TreeNode { long max; long min; TreeNode () { max = Long.MIN_VALUE; min = Long.MAX_VALUE; } } static int MAX = 100005; static TreeNode[] segTree = new TreeNode[4 * MAX]; static long[] prefix = new long[MAX]; public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = 1; for (int t = 0; t < test; t++) { solve(); } out.close(); } private static void solve() { int n = sc.nextInt(); int queries = sc.nextInt(); int[] arrA = new int[n]; int[] arrB = new int[n]; for (int i = 0; i < n; i++) { arrA[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { arrB[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { prefix[i + 1] = prefix[i] + arrB[i] - arrA[i]; } for (int i = 0; i < 4 * MAX; i++) { segTree[i] = new TreeNode(); } build(0, 1, n); for (int q = 0; q < queries; q++) { int l = sc.nextInt(); int r = sc.nextInt(); TreeNode node = query(0, 1, n, l, r); if (prefix[r] != prefix[l - 1] || (node.min - prefix[l - 1]) < 0) { out.println(-1); continue; } long minimalBalancingOperations = node.max - prefix[l - 1]; out.println(minimalBalancingOperations); } } private static void build(int currIndex, int start, int end) { if (start == end) { segTree[currIndex].max = segTree[currIndex].min = prefix[start]; return; } int mid = (start + end) / 2; build(2 * currIndex + 1, start, mid); build(2 * currIndex + 2, mid + 1, end); segTree[currIndex].max = Math.max(segTree[2 * currIndex + 1].max, segTree[2 * currIndex + 2].max); segTree[currIndex].min = Math.min(segTree[2 * currIndex + 1].min, segTree[2 * currIndex + 2].min); } private static TreeNode query(int currIndex, int start, int end, int l, int r) { if (l > end || r < start) { return new TreeNode(); } if (l <= start && r >= end) { return segTree[currIndex]; } int mid = (start + end) / 2; TreeNode left = query(2 * currIndex + 1, start, mid, l, r); TreeNode right = query(2 * currIndex + 2, mid + 1, end, l, r); TreeNode merged = new TreeNode(); merged.max = Math.max(left.max, right.max); merged.min = Math.min(left.min, right.min); return merged; } public static FastReader sc; public static PrintWriter out; 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
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
7c29526c33fe4ee95a2d6af70369ed27
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.*; import java.util.*; public class Codeforces { static int mod=1000000007; static long pref[]; static long mat[][],grid[][]; static int log[]; static int max; static int k; public static void main(String[] args) throws Exception { PrintWriter out=new PrintWriter(System.out); FastScanner fs=new FastScanner(); int n=fs.nextInt(), q=fs.nextInt(); int arr[]=fs.readArray(n); int brr[]=fs.readArray(n); long diff[]=new long[n+1]; pref=new long[n+1]; for(int i=1;i<=n;i++) { pref[i]= pref[i-1]+ brr[i-1]-arr[i-1]; diff[i]=brr[i-1]-arr[i-1]; } max=n+1; callog(); k=log[max]; build(pref); while(q-->0) { int l=fs.nextInt(), r=fs.nextInt(); long sum = pref[r]-pref[l-1]; if(sum!=0) { out.println(-1); continue; } long min = min_query(l,r)-pref[l-1]; if(min<0) { out.println(-1); continue; } long ans= max_query(l,r)-pref[l-1]; out.println(ans); } out.close(); } static void build(long arr[]) { mat=new long[max][k+1]; for(int i=0;i<arr.length;i++) { mat[i][0]=arr[i]; } for(int j=1;j<=k;j++) { for(int i=0;i+(1<<j)<=max;i++) { mat[i][j]=Math.min(mat[i][j-1], mat[i+(1<<(j-1))][j-1]); } } grid=new long[max][k+1]; for(int i=0;i<arr.length;i++) { grid[i][0]=arr[i]; } for(int j=1;j<=k;j++) { for(int i=0;i+(1<<j)<=max;i++) { grid[i][j]=Math.max(grid[i][j-1], grid[i+(1<<(j-1))][j-1]); } } } static long max_query(int l,int r) { int j=log[r-l+1]; return Math.max(grid[l][j], grid[r-(1<<j)+1][j]); } static void callog() { log=new int[max+1]; log[1]=0; for(int i=2;i<=max;i++) { log[i]=log[i/2]+1; } } static long min_query(int l,int r) { int j=log[r-l+1]; return Math.min(mat[l][j], mat[r-(1<<j)+1][j]); } static long pow(long a,long b) { if(b<0) return 1; long res=1; while(b!=0) { if((b&1)!=0) { res*=a; res%=mod; } a*=a; a%=mod; b=b>>1; } return res; } static long gcd(long a,long b) { if(b==0) return a; return gcd(b,a%b); } static long nck(int n,int k) { if(k>n) return 0; long res=1; res*=fact(n); res%=mod; res*=modInv(fact(k)); res%=mod; res*=modInv(fact(n-k)); res%=mod; return res; } static long fact(long n) { long res=1; for(int i=2;i<=n;i++) { res*=i; res%=mod; } return res; } static long modInv(long n) { return pow(n,mod-2); } static void sort(int[] a) { //suffle int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n); int temp=a[i]; a[i]=a[oi]; a[oi]=temp; } //then sort Arrays.sort(a); } // Use this to input code since it is faster than a Scanner static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long[] lreadArray(int n) { long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
9f23df7e962b8955daffe9d22822409f
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1556e { public static void main(String[] args) throws IOException { int n = rni(), q = ni(), a[] = ria(n), b[] = ria(n), x[] = new int[n]; long bal[] = new long[n + 1]; for (int i = 0; i < n; ++i) { x[i] = b[i] - a[i]; bal[i + 1] = bal[i] + x[i]; } sptb min = new sptb(bal, Long::min), max = new sptb(bal, Long::max); while (q --> 0) { int l = rni() - 1, r = ni(); if (min.qry(l, r) < bal[l] || bal[l] != bal[r]) { prln(-1); } else { prln(max.qry(l, r) - bal[l]); } } close(); } @FunctionalInterface interface LongOperator { long merge(long a, long b); } // cannot use with summation static class sptb { LongOperator op; int n, lg[]; long[][] lookup; sptb(long[] a, LongOperator operator) { n = a.length; lg = new int[n + 1]; int pow2 = 4; for (int i = 2, ind = 1; i <= n; ++i) { if (pow2 == i) { ++ind; pow2 <<= 1; } lg[i] = ind; } op = operator; lookup = new long[n][lg[n] + 1]; for (int i = 0; i < n; ++i) { lookup[i][0] = a[i]; } for (int j = 1; (1 << j) <= n; ++j) { for (int i = 0; (i + (1 << j)) <= n; ++i) { lookup[i][j] = op.merge(lookup[i][j - 1], lookup[i + (1 << (j - 1))][j - 1]); } } } long qry(int l, int r) { int j = lg[r - l]; return op.merge(lookup[l][j], lookup[r - (1 << j)][j]); } } static BufferedReader __i = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __o = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __r = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final long LMAX = 9223372036854775807L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcd(int a, int b) {return b == 0 ? a : gcd(b, a % b);} static long gcd(long a, long b) {return b == 0 ? a : gcd(b, a % b);} static int[] exgcd(int a, int b) {if (b == 0) return new int[] {1, 0}; int[] y = exgcd(b, a % b); return new int[] {y[1], y[0] - y[1] * (a / b)};} static long[] exgcd(long a, long b) {if (b == 0) return new long[] {1, 0}; long[] y = exgcd(b, a % b); return new long[] {y[1], y[0] - y[1] * (a / b)};} static int randInt(int min, int max) {return __r.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static void ria(int[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = ni();} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static void riam1(int[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static void rla(long[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = nl();} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static void rda(double[] a) throws IOException {int n = a.length; r(); for (int i = 0; i < n; ++i) a[i] = nd();} static char[] rcha() throws IOException {return rline().toCharArray();} static void rcha(char[] a) throws IOException {int n = a.length, i = 0; for (char c : rline().toCharArray()) a[i++] = c;} static String rline() throws IOException {return __i.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} // output static void pr(int i) {__o.print(i);} static void prln(int i) {__o.println(i);} static void pr(long l) {__o.print(l);} static void prln(long l) {__o.println(l);} static void pr(double d) {__o.print(d);} static void prln(double d) {__o.println(d);} static void pr(char c) {__o.print(c);} static void prln(char c) {__o.println(c);} static void pr(char[] s) {__o.print(new String(s));} static void prln(char[] s) {__o.println(new String(s));} static void pr(String s) {__o.print(s);} static void prln(String s) {__o.println(s);} static void pr(Object o) {__o.print(o);} static void prln(Object o) {__o.println(o);} static void prln() {__o.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;}; static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;} static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__o.flush();} static void close() {__o.close();} }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
14eca47b1fa3a2c3a0670589cc8d4f7e
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static long gcd(long a,long b) { if(a==0) return b; return gcd(b%a,a); } public static long lcm(long a,long b) { return (a*b)/gcd(a,b); } public static long [] input(BufferedReader br,int n) throws java.lang.Exception{ long ans[]=new long[n]; String input[]=br.readLine().split(" "); for(int i=0;i<n;i++) { ans[i]=Long.parseLong(input[i]); } return ans; } static class Seg{ int n; long max[]; long min[]; public Seg(int n,long a[]) { max=new long[4*n]; min=new long[4*n]; this.n=n; build(0,0,n-1,a); } public void build(int node,int l,int h,long a[]) { if(l==h) { max[node]=a[l]; min[node]=a[l]; return; } int mid=(l+h)/2; build(2*node+1,l,mid,a); build(2*node+2,mid+1,h,a); max[node]=Math.max(max[2*node+1], max[2*node+2]); min[node]=Math.min(min[2*node+1], min[2*node+2]); } public long rangeMax(int node,int l,int h,int ql,int qh) { if(ql<=l&&h<=qh) return max[node]; int mid=(l+h)/2; if(qh<=mid) return rangeMax(2*node+1,l,mid,ql,qh); else if(mid<ql) return rangeMax(2*node+2,mid+1,h,ql,qh); else return Math.max(rangeMax(2*node+1,l,mid,ql,qh), rangeMax(2*node+2,mid+1,h,ql,qh)); } public long rangeMin(int node,int l,int h,int ql,int qh) { if(ql<=l&&h<=qh) return min[node]; int mid=(l+h)/2; if(qh<=mid) return rangeMin(2*node+1,l,mid,ql,qh); else if(mid<ql) return rangeMin(2*node+2,mid+1,h,ql,qh); else return Math.min(rangeMin(2*node+1,l,mid,ql,qh), rangeMin(2*node+2,mid+1,h,ql,qh)); } } public static void main(String[] args) throws java.lang.Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); // int testCases=Integer.parseInt(br.readLine()); int testCases=1; while(testCases-->0) { long input[]=input(br,2); int n=(int)input[0]; int q=(int)input[1]; long a[]=input(br,n); long b[]=input(br,n); long c[]=new long[n]; for(int i=0;i<n;i++) { c[i]=b[i]-a[i]; } for(int i=1;i<n;i++) { c[i]+=c[i-1]; } Seg obj=new Seg(n,c); for(int i=0;i<q;i++) { input=input(br,2); int l=(int)input[0]-1; int h=(int)input[1]-1; long left=l==0?0:c[l-1]; long max=obj.rangeMax(0, 0, n-1, l, h); long min=obj.rangeMin(0, 0, n-1, l, h); if(c[h]-left!=0||min-left!=0) { out.println(-1); }else out.println(max-left); } } out.close(); } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
08100e3e3039df3effd365056736aa6d
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.util.*; import java.io.*; public class _1556_E { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer line = new StringTokenizer(in.readLine()); int n = Integer.parseInt(line.nextToken()); int q = Integer.parseInt(line.nextToken()); int[] x = new int[n]; long[] psum = new long[n]; StringTokenizer aline = new StringTokenizer(in.readLine()); StringTokenizer bline = new StringTokenizer(in.readLine()); for(int i = 0; i < n; i++) { x[i] = Integer.parseInt(bline.nextToken()) - Integer.parseInt(aline.nextToken()); psum[i] = (i > 0 ? psum[i - 1] : 0) + x[i]; } Segtree st = new Segtree(psum); for(int i = 0; i < q; i++) { line = new StringTokenizer(in.readLine()); int l = Integer.parseInt(line.nextToken()) - 1; int r = Integer.parseInt(line.nextToken()) - 1; long cur_psum = l > 0 ? psum[l - 1] : 0; long min = st.min(1, 0, n - 1, l, r) - cur_psum; long max = st.max(1, 0, n - 1, l, r) - cur_psum; if(psum[r] - cur_psum == 0 && min >= 0) { out.println(max); }else { out.println(-1); } } in.close(); out.close(); } static class Segtree { long[] a, min, max; Segtree(long[] aa) { a = aa; min = new long[a.length * 4]; max = new long[a.length * 4]; construct(1, 0, a.length - 1); } void construct(int v, int l, int r) { if(l == r) { min[v] = a[l]; max[v] = a[l]; }else { int m = (l + r) / 2; construct(v * 2, l, m); construct(v * 2 + 1, m + 1, r); min[v] = Math.min(min[v * 2], min[v * 2 + 1]); max[v] = Math.max(max[v * 2], max[v * 2 + 1]); } } long min(int v, int l, int r, int ql, int qr) { if(ql > qr) { return Long.MAX_VALUE; }else if(l == ql && r == qr) { return min[v]; }else { int m = (l + r) / 2; long left = min(v * 2, l, m, ql, Math.min(m, qr)); long right = min(v * 2 + 1, m + 1, r, Math.max(ql, m + 1), qr); return Math.min(left, right); } } long max(int v, int l, int r, int ql, int qr) { if(ql > qr) { return Long.MIN_VALUE; }else if (l == ql && r == qr) { return max[v]; }else { int m = (l + r) / 2; long left = max(v * 2, l, m, ql, Math.min(m, qr)); long right = max(v * 2 + 1, m + 1, r, Math.max(ql, m + 1), qr); return Math.max(left, right); } } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
e8cca87a8ccf05015b1331f39de8e26b
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),q=Integer.parseInt(s[1]); int a[]=new int[n],b[]=new int[n],i; s=bu.readLine().split(" "); for(i=0;i<n;i++) a[i]=Integer.parseInt(s[i]); s=bu.readLine().split(" "); for(i=0;i<n;i++) b[i]=Integer.parseInt(s[i]); long pre[]=new long[n+1],min[]=new long[4*n+10],max[]=new long[4*n+10]; Arrays.fill(min,Long.MAX_VALUE); for(i=1;i<=n;i++) { pre[i]=b[i-1]-a[i-1]; pre[i]+=pre[i-1]; update(min,0,n,i,pre[i],0,true); update(max,0,n,i,pre[i],0,false); } while(q-->0) { s=bu.readLine().split(" "); int l=Integer.parseInt(s[0]),r=Integer.parseInt(s[1]); long rsum=pre[r]-pre[l-1],mx=query(max,0,n,l,r,0,false),mn=query(min,0,n,l,r,0,true); if(rsum==0 && mn-pre[l-1]>=0) sb.append(mx-pre[l-1]+"\n"); else sb.append("-1\n"); } System.out.print(sb); } static void update(long st[],int ss,int se,int i,long v,int n,boolean min) { if(ss>se) return; if(ss==se) { st[n]=v; return; } int m=(ss+se)>>1; if(i<=m) update(st,ss,m,i,v,2*n+1,min); else update(st,m+1,se,i,v,2*n+2,min); if(min) st[n]=Math.min(st[2*n+1],st[2*n+2]); else st[n]=Math.max(st[2*n+1],st[2*n+2]); } static long query(long st[],int ss,int se,int qs,int qe,int n,boolean min) { if(ss>se || qs>se || qe<ss) return min?Long.MAX_VALUE:Long.MIN_VALUE; if(qs<=ss && qe>=se) return st[n]; int m=(ss+se)>>1; return min? Math.min(query(st,ss,m,qs,qe,2*n+1,min),query(st,m+1,se,qs,qe,2*n+2,min)): Math.max(query(st,ss,m,qs,qe,2*n+1,min),query(st,m+1,se,qs,qe,2*n+2,min)); } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
74315acad382d62e9f1b55a78ad357dd
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
// upsolve with kaiboy import java.io.*; import java.util.*; public class CF1556E extends PrintWriter { CF1556E() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1556E o = new CF1556E(); o.main(); o.flush(); } static final long INF = 0x3f3f3f3f3f3f3f3fL; long[] aa, tmax, tmin; int n; void build() { tmax = new long[n * 2]; tmin = new long[n * 2]; for (int i = 0; i < n; i++) tmax[n + i] = tmin[n + i] = aa[i]; for (int i = n - 1; i > 0; i--) { tmax[i] = Math.max(tmax[i << 1], tmax[i << 1 | 1]); tmin[i] = Math.min(tmin[i << 1], tmin[i << 1 | 1]); } } long qmax(int l, int r) { long ans = -INF; for (l += n, r += n; l <= r; l >>= 1, r >>= 1) { if ((l & 1) == 1) ans = Math.max(ans, tmax[l++]); if ((r & 1) == 0) ans = Math.max(ans, tmax[r--]); } return ans; } long qmin(int l, int r) { long ans = INF; for (l += n, r += n; l <= r; l >>= 1, r >>= 1) { if ((l & 1) == 1) ans = Math.min(ans, tmin[l++]); if ((r & 1) == 0) ans = Math.min(ans, tmin[r--]); } return ans; } void main() { n = sc.nextInt(); int q = sc.nextInt(); aa = new long[n]; for (int i = 0; i < n; i++) aa[i] = -sc.nextInt(); for (int i = 0; i < n; i++) aa[i] += sc.nextInt(); for (int i = 1; i < n; i++) aa[i] += aa[i - 1]; build(); while (q-- > 0) { int l = sc.nextInt() - 1; int r = sc.nextInt() - 1; long a = l == 0 ? 0 : aa[l - 1]; long b = aa[r]; println(a != b || qmin(l, r) != a ? -1 : qmax(l, r) - a); } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
f079dc8bbf26741b87805437cc36d094
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
//package com.company.codeforces.v210829; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; public class E { FastScanner in; PrintWriter out; public static void main(String[] args) { new E().solve(); } private void solve() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solveCase(); out.flush(); } private void solveCase() { int n = in.nextInt(); int q = in.nextInt(); List<Long> a = LongStream.range(0, n).map(i -> in.nextInt()).boxed().collect(Collectors.toList()); List<Long> b = LongStream.range(0, n).map(i -> in.nextInt()).boxed().collect(Collectors.toList()); List<Long> d = new ArrayList<>(); long last = 0; d.add(0L); for (int i = n - 1; i >= 0; i--) { long acum = last + a.get(i) - b.get(i); d.add(acum); last = acum; } Collections.reverse(d); SegmentTree minTree = new SegmentTree(n); SegmentTree maxTree = new SegmentTree(n); for (int i = 0; i < n; i++) { minTree.update(i, -d.get(i)); maxTree.update(i, d.get(i)); } for (int i = 0; i < q; i++) { int l = in.nextInt() - 1; int r = in.nextInt(); long totalDiff = d.get(l) - d.get(r); if (totalDiff != 0) { out.println(-1); continue; } long minValue = -minTree.query(l, r) - d.get(r); if (minValue < 0) { out.println(-1); continue; } long maxValue = maxTree.query(l, r) - d.get(r); out.println(maxValue); } } private static class SegmentTree { private final long[] rmq; private final int n; public SegmentTree(int n) { this.rmq = new long[2 * n]; Arrays.fill(rmq, Long.MIN_VALUE); this.n = n; } void update(int position, long value) { rmq[n + position] = value; int node = (n + position) / 2; while (node != 0) { rmq[node] = Math.max(rmq[2 * node], rmq[2 * node + 1]); node /= 2; } } long query(int left, int right) { left += n; right += n; long res = Long.MIN_VALUE; while (left < right) { if (left % 2 == 1) res = Math.max(res, rmq[left++]); if (right % 2 == 1) res = Math.max(res, rmq[--right]); left /= 2; right /= 2; } return res; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
2933cd71fbb171b7a88c6383966e5723
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.List; import java.util.*; public class realfast implements Runnable { private static final int INF = (int) 1e9; long in= 1000000007; long fac[]= new long[1000001]; long inv[]=new long[1000001]; long minu = 1000000000; long maxu = 1000000000; public void solve() throws IOException { minu = -minu*1000000; maxu = maxu*1000000; int n = readInt(); int q= readInt(); int arr[]=new int[n+1]; int brr[]=new int[n+1]; for(int i=1;i<=n;i++) arr[i]= readInt(); for(int i =1;i<=n;i++) brr[i]= readInt(); long sum[]=new long[n+1]; for(int i=1;i<=n;i++) { sum[i]= sum[i-1]+ brr[i]-arr[i]; } long seg1[]=new long [4*n+10]; long seg2[]=new long [4*n+10]; build_max(seg1,sum,1,n,0); build_min(seg2,sum,1,n,0); for(int i =0;i<q;i++) { int l = readInt(); int r = readInt(); if((sum[r]-sum[l-1])==0) { long minwa = query_min(seg2,l,r,1,n,0); long maxwa = query_max(seg1,l,r,1,n,0); if(minwa-sum[l-1]==0) out.println(maxwa-sum[l-1]); else out.println(-1); } else out.println(-1); } } public void build_max(long seg[] , long sum[] , int left , int right , int index) { if(left==right) { seg[index] = sum[left]; return ; } int mid = left+(right-left)/2; build_max(seg,sum,left,mid,2*index+1); build_max(seg,sum,mid+1,right,2*index+2); seg[index]=Math.max(seg[2*index+1],seg[2*index+2]); } public void build_min(long seg[] , long sum[] , int left, int right , int index) { if(left==right) { seg[index]=sum[left]; return ; } int mid = left+(right-left)/2; build_min(seg,sum,left,mid,2*index+1); build_min(seg,sum,mid+1,right,2*index+2); seg[index]=Math.min(seg[2*index+1],seg[2*index+2]); } public long query_max(long seg[] , int l , int r , int left , int right , int index) { if(left>r||l>right) return minu; if(left>=l&&right<=r) return seg[index]; int mid = left+(right-left)/2; long val1 = query_max(seg,l,r,left,mid,2*index+1); long val2 = query_max(seg,l,r,mid+1,right,2*index+2); return Math.max(val1,val2); } public long query_min(long seg[] , int l , int r , int left , int right , int index) { if(left>r||l>right) return maxu; if(left>=l&&right<=r) return seg[index]; int mid = left+(right-left)/2; long val1 = query_min(seg,l,r,left,mid,2*index+1); long val2 = query_min(seg,l,r,mid+1,right,2*index+2); return Math.min(val1,val2); } public long query(long seg[] , int left, int right , int index, int l , int r) { long inf = 100000000; inf = inf*inf; if(left>=l&&right<=r) { return seg[index]; } if(l>right||left>r) return inf; int mid = left+(right-left)/2; return Math.min(query(seg,left,mid,2*index+1,l,r),query(seg,mid+1,right,2*index+2,l,r)); } public int value (int seg[], int left , int right ,int index, int l, int r) { if(left>right) { return -100000000; } if(right<l||left>r) return -100000000; if(left>=l&&right<=r) return seg[index]; int mid = left+(right-left)/2; int val = value(seg,left,mid,2*index+1,l,r); int val2 = value(seg,mid+1,right,2*index+2,l,r); return Math.max(val,val2); } public int gcd(int a , int b ) { if(a<b) { int t =a; a=b; b=t; } if(a%b==0) return b ; return gcd(b,a%b); } public long pow(long n , long p,long m) { if(p==0) return 1; long val = pow(n,p/2,m);; val= (val*val)%m; if(p%2==0) return val; else return (val*n)%m; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int u ; int v; edge(int u, int v) { this.u=u; this.v=v; } public int compareTo(edge e) { return this.v-e.v; } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
3527ffcba6f3de522402b0cfad3777c4
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.util.*; import java.io.*; public class E { public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); int q = sc.nextInt(); int[] arr = new int[n]; int[] brr = new int[n]; for(int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } for(int i = 0; i < n; i++) { brr[i] = sc.nextInt(); } int[] crr = new int[n]; for(int i = 0; i < n; i++) { crr[i] = brr[i] - arr[i]; } long[] acc = new long[n+1]; for(int i = 1; i <= n; i++) { acc[i] = acc[i-1] + crr[i-1]; } Node st = new Node(0, n, acc); StringBuilder sb = new StringBuilder(); while(q-- > 0) { int L = sc.nextInt()-1; int R = sc.nextInt()-1; if(acc[R+1] == acc[L] && st.querymin(L, R+1) == acc[L]) { long r = st.querymax(L, R+1) - acc[L]; sb.append(r+"\n"); } else { sb.append("-1\n"); } } PrintWriter pw = new PrintWriter(System.out); pw.println(sb.toString().trim()); pw.flush(); } static class Node{ int L, R; long min, max, sum; Node left, right; public Node(int L, int R, long[] arr){ this.L = L; this.R = R; if(L == R) { sum = max = min = arr[L]; } else { left = new Node(L, (L+R)/2, arr); right = new Node((L+R)/2+1, R, arr); min = Math.min(left.min, right.min); max = Math.max(left.max, right.max); sum = left.sum + right.sum; } } public long querysum(int qL, int qR) { if(qR < L || R < qL) return 0; else if(qL <= L && R <= qR) return sum; else { long x = left.querysum(qL, qR); long y = right.querysum(qL, qR); return x + y; } } public long querymax(int qL, int qR) { if(qR < L || R < qL) return Long.MIN_VALUE; else if(qL <= L && R <= qR) return max; else { long x = left.querymax(qL, qR); long y = right.querymax(qL, qR); return Math.max(x, y); } } public long querymin(int qL, int qR) { if(qR < L || R < qL) return Long.MAX_VALUE; else if(qL <= L && R <= qR) return min; else { long x = left.querymin(qL, qR); long y = right.querymin(qL, qR); return Math.min(x, y); } } } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
1f37b48e3748ae99b0d1210d77071eff
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.util.*; import java.io.*; public class DeltixRound { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////// ///////// //////// ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// ///////// //////// ///////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = 1; while (t-- > 0) { int n = sc.nextInt(); int q = sc.nextInt(); int sz = 1; while (sz < n) sz <<= 1; long[] need = new long[sz + 1]; int[] a = new int[sz + 1]; int[] b = new int[sz + 1]; for (int i = 1; i <= n; i++) a[i] = sc.nextInt(); for (int i = 1; i <= n; i++) b[i] = sc.nextInt(); for (int i = 1; i <= n; i++) need[i] = b[i] - a[i]; SegmentTree tree = new SegmentTree(need); while (q-- > 0) { long[] cur = tree.query(sc.nextInt(), sc.nextInt()); // System.err.println(Arrays.toString(cur)); if (cur[0] == 0 && cur[1] == 0) { pw.println(cur[2]); } else pw.println(-1); } } pw.flush(); } static class SegmentTree { // 1-based DS, OOP int N; //the number of elements in the array as a power of 2 (i.e. after padding) long[] array, sTree[]; SegmentTree(long[] in) { array = in; N = in.length - 1; sTree = new long[N << 1][3]; //no. of nodes = 2*N - 1, we add one to cross out index zero build(1, 1, N); } void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = new long[]{array[b], Math.max(-array[b], 0), Math.max(array[b], 0)}; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = merge(sTree[node << 1], sTree[node << 1 | 1]); } } long[] merge(long[] left, long[] right) { long[] res = new long[3]; res[0] += left[0] + right[0]; res[1] = Math.max(0, Math.max(left[1], -(left[0] - right[1]))); res[2] = Math.max(0, Math.max(left[2], (left[0] + right[2]))); return res; } long[] query(int i, int j) { return query(1, 1, N, i, j); } long[] query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return new long[]{0, 0, 0}; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; long[] q1 = query(node << 1, b, mid, i, j); long[] q2 = query(node << 1 | 1, mid + 1, e, i, j); return merge(q1, q2); } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] nextIntArr(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
7f3f5a3cb5eb7496d41c2a531ef156c5
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.function.Supplier; import java.util.function.IntFunction; import java.io.OutputStream; import java.io.PrintStream; import java.io.IOException; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.io.UncheckedIOException; import java.util.function.Consumer; import java.io.Closeable; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); EEquilibrium solver = new EEquilibrium(); solver.solve(1, in, out); out.close(); } } static class EEquilibrium { Debug debug = new Debug(false); public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.ri(); int q = in.ri(); long[] ab = new long[n]; for (int i = 0; i < n; i++) { ab[i] -= in.ri(); } for (int i = 0; i < n; i++) { ab[i] += in.ri(); } SegTree<SumImpl, Update.NIL> st = new SegTree<>(0, n - 1, SumImpl::new, Update.NIL.SUPPLIER, i -> { SumImpl s = new SumImpl(); s.maxPs = Math.max(0, ab[i]); s.minPs = Math.min(0, ab[i]); s.ps = ab[i]; return s; }); debug.debug("ab", ab); SumImpl sum = new SumImpl(); for (int i = 0; i < q; i++) { int l = in.ri() - 1; int r = in.ri() - 1; sum.clear(); st.query(l, r, 0, n - 1, sum); if (sum.minPs < 0 || sum.ps != 0) { out.println(-1); } else { out.println(sum.maxPs); } } } } static interface Sum<S> { void add(S s); void copy(S s); S clone(); } static class SumImpl implements UpdatableSum<SumImpl, Update.NIL> { long ps; long minPs; long maxPs; void clear() { ps = minPs = maxPs = 0; } public void add(SumImpl sum) { minPs = Math.min(minPs, ps + sum.minPs); maxPs = Math.max(maxPs, ps + sum.maxPs); ps += sum.ps; } public void copy(SumImpl sum) { ps = sum.ps; minPs = sum.minPs; maxPs = sum.maxPs; } public SumImpl clone() { SumImpl ans = new SumImpl(); ans.copy(this); return ans; } public void update(Update.NIL nil) { } public String toString() { return "" + ps; } } static class SegTree<S extends UpdatableSum<S, U>, U extends Update<U>> implements Cloneable { private SegTree<S, U> left; private SegTree<S, U> right; public S sum; private U update; private void modify(U x) { update.update(x); sum.update(x); } private void pushDown() { if (update.ofBoolean()) { left.modify(update); right.modify(update); update.clear(); assert !update.ofBoolean(); } } private void pushUp() { sum.copy(left.sum); sum.add(right.sum); } public SegTree(int l, int r, Supplier<S> sSupplier, Supplier<U> uSupplier, IntFunction<S> func) { update = uSupplier.get(); update.clear(); if (l < r) { sum = sSupplier.get(); int m = DigitUtils.floorAverage(l, r); left = new SegTree<>(l, m, sSupplier, uSupplier, func); right = new SegTree<>(m + 1, r, sSupplier, uSupplier, func); pushUp(); } else { sum = func.apply(l); } } private boolean cover(int L, int R, int l, int r) { return L <= l && R >= r; } private boolean leave(int L, int R, int l, int r) { return R < l || L > r; } public void query(int L, int R, int l, int r, S s) { if (leave(L, R, l, r)) { return; } if (cover(L, R, l, r)) { s.add(sum); return; } int m = DigitUtils.floorAverage(l, r); pushDown(); left.query(L, R, l, m, s); right.query(L, R, m + 1, r, s); } public SegTree<S, U> deepClone() { SegTree<S, U> clone = clone(); clone.sum = clone.sum.clone(); clone.update = clone.update.clone(); if (clone.left != null) { clone.left = clone.left.deepClone(); clone.right = clone.right.deepClone(); } return clone; } public void visitLeave(Consumer<SegTree<S, U>> consumer) { if (left == null) { consumer.accept(this); return; } pushDown(); left.visitLeave(consumer); right.visitLeave(consumer); } public String toString() { StringBuilder ans = new StringBuilder(); deepClone().visitLeave(x -> ans.append(x.sum).append(' ')); return ans.toString(); } public SegTree<S, U> clone() { try { return (SegTree<S, U>) super.clone(); } catch (CloneNotSupportedException e) { throw new UnsupportedOperationException(e); } } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int ri() { return readInt(); } public int readInt() { boolean rev = false; skipBlank(); if (next == '+' || next == '-') { rev = next == '-'; next = read(); } int val = 0; while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } return rev ? val : -val; } } static class Debug { private boolean offline; private PrintStream out = System.err; static int[] empty = new int[0]; public Debug(boolean enable) { offline = enable && System.getSecurityManager() == null; } public Debug debug(String name, Object x) { return debug(name, x, empty); } public Debug debug(String name, Object x, int... indexes) { if (offline) { if (x == null || !x.getClass().isArray()) { out.append(name); for (int i : indexes) { out.printf("[%d]", i); } out.append("=").append("" + x); out.println(); } else { indexes = Arrays.copyOf(indexes, indexes.length + 1); if (x instanceof byte[]) { byte[] arr = (byte[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof short[]) { short[] arr = (short[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof boolean[]) { boolean[] arr = (boolean[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof char[]) { char[] arr = (char[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof int[]) { int[] arr = (int[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof float[]) { float[] arr = (float[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof double[]) { double[] arr = (double[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof long[]) { long[] arr = (long[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else { Object[] arr = (Object[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } } } return this; } } static interface Update<U extends Update<U>> extends Cloneable { void update(U u); void clear(); boolean ofBoolean(); U clone(); static class NIL implements Update<Update.NIL> { public static final Update.NIL INSTANCE = new Update.NIL(); public static final Supplier<Update.NIL> SUPPLIER = () -> INSTANCE; private NIL() { } public void update(Update.NIL nilUpdate) { } public void clear() { } public boolean ofBoolean() { return false; } public Update.NIL clone() { return this; } } } static interface UpdatableSum<S, U> extends Cloneable, Sum<S> { void update(U u); } static class FastOutput implements AutoCloseable, Closeable, Appendable { private static final int THRESHOLD = 32 << 10; private OutputStream writer; private StringBuilder cache = new StringBuilder(THRESHOLD * 2); private static Field stringBuilderValueField; private char[] charBuf = new char[THRESHOLD * 2]; private byte[] byteBuf = new byte[THRESHOLD * 2]; static { try { stringBuilderValueField = StringBuilder.class.getSuperclass().getDeclaredField("value"); stringBuilderValueField.setAccessible(true); } catch (Exception e) { stringBuilderValueField = null; } stringBuilderValueField = null; } public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } private void afterWrite() { if (cache.length() < THRESHOLD) { return; } flush(); } public FastOutput(OutputStream writer) { this.writer = writer; } public FastOutput append(char c) { cache.append(c); afterWrite(); return this; } public FastOutput append(int c) { cache.append(c); afterWrite(); return this; } public FastOutput append(long c) { cache.append(c); afterWrite(); return this; } public FastOutput println(int c) { return append(c).println(); } public FastOutput println(long c) { return append(c).println(); } public FastOutput println() { return append('\n'); } public FastOutput flush() { try { if (stringBuilderValueField != null) { try { byte[] value = (byte[]) stringBuilderValueField.get(cache); writer.write(value, 0, cache.length()); } catch (Exception e) { stringBuilderValueField = null; } } if (stringBuilderValueField == null) { int n = cache.length(); if (n > byteBuf.length) { //slow writer.write(cache.toString().getBytes(StandardCharsets.UTF_8)); // writer.append(cache); } else { cache.getChars(0, n, charBuf, 0); for (int i = 0; i < n; i++) { byteBuf[i] = (byte) charBuf[i]; } writer.write(byteBuf, 0, n); } } writer.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { writer.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class DigitUtils { private DigitUtils() { } public static int floorAverage(int x, int y) { return (x & y) + ((x ^ y) >> 1); } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
b23da256cfa9bd8d273b649edcab2f8a
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.System.arraycopy; import static java.lang.System.exit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class E { static class LongMaxTree { final int n; final long t[]; LongMaxTree(int n) { this.n = n; t = new long[2 * n - 1]; } long get(int i) { return t[i + n - 1]; } long getMax(int l, int r) { long v = Long.MIN_VALUE; for (l += n, r += n; l != r; l >>>= 1, r >>>= 1) { if ((l & 1) != 0) { v = max(v, t[l++ - 1]); } if ((r & 1) != 0) { v = max(v, t[--r - 1]); } } return v; } void set(int i, long v) { t[(i += n) - 1] = v; for (i >>= 1; i != 0; i >>= 1) { t[i - 1] = max(t[(i << 1) - 1], t[i << 1]); } } } static class LongMinTree { final int n; final long t[]; LongMinTree(int n) { this.n = n; t = new long[2 * n - 1]; } long get(int i) { return t[i + n - 1]; } long getMin(int l, int r) { long v = Long.MAX_VALUE; for (l += n, r += n; l != r; l >>>= 1, r >>>= 1) { if ((l & 1) != 0) { v = min(v, t[l++ - 1]); } if ((r & 1) != 0) { v = min(v, t[--r - 1]); } } return v; } void set(int i, long v) { t[(i += n) - 1] = v; for (i >>= 1; i != 0; i >>= 1) { t[i - 1] = min(t[(i << 1) - 1], t[i << 1]); } } } static void solve() throws Exception { int n = scanInt(), q = scanInt(); LongMinTree minTree = new LongMinTree(n + 1); LongMaxTree maxTree = new LongMaxTree(n + 1); for (int i = 0; i < n; i++) { minTree.t[n + i] = -scanInt(); } for (int i = 0; i < n; i++) { minTree.t[n + i] += scanInt(); } long sum = 0; for (int i = 0; i < n; i++) { long v = minTree.t[n + i]; minTree.t[n + i] = sum; sum += v; } minTree.t[n + n] = sum; arraycopy(minTree.t, n, maxTree.t, n, n + 1); for (int i = n; i != 0; i--) { minTree.t[i - 1] = min(minTree.t[(i << 1) - 1], minTree.t[i << 1]); maxTree.t[i - 1] = max(maxTree.t[(i << 1) - 1], maxTree.t[i << 1]); } for (int qq = 0; qq < q; qq++) { int l = scanInt() - 1, r = scanInt(); long s = minTree.get(l); out.println(minTree.get(r) != s || minTree.getMin(l, r + 1) != s ? -1 : maxTree.getMax(l, r + 1) - s); } } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
11aa4df043094fb8a89fd442857f9235
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
//package deltixs2021; import java.io.*; import java.util.ArrayDeque; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Queue; public class E { InputStream is; FastWriter out; String INPUT = ""; void solve() { int n = ni(), Q = ni(); int[] a = na(n); int[] b = na(n); for(int i = 0;i < n;i++){ b[i] -= a[i]; } long[] cum = new long[n+1]; for(int i = 0;i < n;i++){ cum[i+1] = cum[i] + b[i]; } long[] rcum = new long[n+1]; for(int i = 0;i <= n;i++)rcum[i] = -cum[i]; SegmentTreeRMQL stmin = new SegmentTreeRMQL(cum); SegmentTreeRMQL stmax = new SegmentTreeRMQL(rcum); for(int z = 0;z < Q;z++){ int l = ni()-1, r = ni()-1; if(cum[r+1] - cum[l] != 0){ out.println(-1); }else if(stmin.min(l, r+1) < cum[l]){ out.println(-1); }else{ out.println(-stmax.min(l, r+1) - cum[l]); } } } public static class SegmentTreeRMQL { public final int M, H, N; public long[] vals; public static final long I = Long.MAX_VALUE; public SegmentTreeRMQL(int n) { N = n; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; vals = new long[M]; Arrays.fill(vals, 0, M, I); } public SegmentTreeRMQL(long[] a) { this(a.length); for(int i = 0;i < N;i++){ vals[H+i] = a[i]; } // Arrays.fill(vals, H+N, M, I); for(int i = H-1;i >= 1;i--)propagate(i); } public void update(int pos, long x) { vals[H+pos] = x; for(int i = (H+pos)>>>1;i >= 1;i >>>= 1)propagate(i); } private void propagate(int i) { vals[i] = Math.min(vals[2*i], vals[2*i+1]); } public long min(int l, int r){ long min = I; if(l >= r)return min; l += H; r += H; for(;l < r;l>>>=1,r>>>=1){ if((l&1) == 1)min = Math.min(min, vals[l++]); if((r&1) == 1)min = Math.min(min, vals[--r]); } return min; } public int firstle(int l, long v) { if(l >= H)return -1; int cur = H+l; while(true){ if(vals[cur] <= v){ if(cur >= H)return cur-H; cur = 2*cur; }else{ cur++; if((cur&cur-1) == 0)return -1; if((cur&1)==0)cur>>>=1; } } } public int lastle(int l, long v) { if(l < 0)return -1; int cur = H+l; while(true){ if(vals[cur] <= v){ if(cur >= H)return cur-H; cur = 2*cur + 1; }else{ if((cur&cur-1) == 0)return -1; cur--; if((cur&1)==1)cur>>>=1; } } } } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new FastWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new E().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for(int i = 0;i < n;i++)a[i] = nl(); return a; } 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[][] nmi(int n, int m) { int[][] map = new int[n][]; for(int i = 0;i < n;i++)map[i] = na(m); return map; } private int ni() { return (int)nl(); } 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(); } } public static class FastWriter { private static final int BUF_SIZE = 1<<13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter(){out = null;} public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if(ptr == BUF_SIZE)innerflush(); return this; } public FastWriter write(char c) { return write((byte)c); } public FastWriter write(char[] s) { for(char c : s){ buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if(x == Integer.MIN_VALUE){ return write((long)x); } if(ptr + 12 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if(x == Long.MIN_VALUE){ return write("" + x); } if(ptr + 21 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if(x < 0){ write('-'); x = -x; } x += Math.pow(10, -precision)/2; // if(x < 0){ x = 0; } write((long)x).write("."); x -= (long)x; for(int i = 0;i < precision;i++){ x *= 10; write((char)('0'+(int)x)); x -= (int)x; } return this; } public FastWriter writeln(char c){ return write(c).writeln(); } public FastWriter writeln(int x){ return write(x).writeln(); } public FastWriter writeln(long x){ return write(x).writeln(); } public FastWriter writeln(double x, int precision){ return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for(int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for(long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte)'\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for(char[] line : map)write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c){ return writeln(c); } public FastWriter println(int x){ return writeln(x); } public FastWriter println(long x){ return writeln(x); } public FastWriter println(double x, int precision){ return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } public void trnz(int... o) { for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" "); System.out.println(); } // print ids which are 1 public void trt(long... o) { Queue<Integer> stands = new ArrayDeque<>(); for(int i = 0;i < o.length;i++){ for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x)); } System.out.println(stands); } public void tf(boolean... r) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } public void tf(boolean[]... b) { for(boolean[] r : b) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } System.out.println(); } public void tf(long[]... b) { if(INPUT.length() != 0) { for (long[] r : b) { for (long x : r) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } System.out.println(); } } public void tf(long... b) { if(INPUT.length() != 0) { for (long x : b) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 11
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
868636ba6b97a44a585cc6a5f90e7e76
train_107.jsonl
1630247700
William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 &lt; pos_2 &lt; \dots &lt; pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
256 megabytes
import java.util.*; import java.util.function.*; import java.io.*; // you can compare with output.txt and expected out public class RoundDeltix2021E { MyPrintWriter out; MyScanner in; // final static long FIXED_RANDOM; // static { // FIXED_RANDOM = System.currentTimeMillis(); // } final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void initIO(boolean isFileIO) { if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) { try{ in = new MyScanner(new FileInputStream("input.txt")); out = new MyPrintWriter(new FileOutputStream("output.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } } else{ in = new MyScanner(System.in); out = new MyPrintWriter(new BufferedOutputStream(System.out)); } } public static void main(String[] args){ // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); // the code for the deep recursion (more than 100k or 3~400k or so) // Thread t = new Thread(null, new RoundEdu130F(), "threadName", 1<<28); // t.start(); // t.join(); RoundDeltix2021E sol = new RoundDeltix2021E(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; boolean hasMultipleTests = false; initIO(isFileIO); int t = hasMultipleTests? in.nextInt() : 1; for (int i = 1; i <= t; ++i) { if(isDebug){ out.printf("Test %d\n", i); } getInput(); solve(); printOutput(); } in.close(); out.close(); } // use suitable one between matrix(2, n), matrix(n, 2), transposedMatrix(2, n) for graph edges, pairs, ... int n, q; long[] a, b; int[] l, r; void getInput() { n = in.nextInt(); q = in.nextInt(); a = in.nextLongArray(n); b = in.nextLongArray(n); int[][] lr = in.nextTransposedMatrix(q, 2, -1); l = lr[0]; r = lr[1]; } void printOutput() { out.printlnAns(ans); } long[] ans; void solve(){ ans = new long[q]; for(int i=0; i<n; i++) a[i] -= b[i]; // sum[l..r] must be 0 // +1, -1, +1, -1, ... -> make all 0 // but that's not sufficient // e.g., 0, +1, 0, 0, -1 // it's like moving 1 from a[j] to a[i] for i < j // (i) to be valid: min sum [i..r] >= 0 // -> at index i, store sum [i..n-1] and find min [l..r] then subtract sum [r+1..n-1] // (ii) the cost: max sum [i..r] long[] suffix = new long[n+1]; for(int i=n-1; i>=0; i--) suffix[i] = suffix[i+1] + a[i]; SegmentTree minTree = new SegmentTree(Math::min, suffix); SegmentTree maxTree = new SegmentTree(Math::max, suffix); for(int i=0; i<q; i++) { long sum = suffix[l[i]] - suffix[r[i]+1]; if(sum != 0) { ans[i] = -1; continue; } long min = minTree.getRange(l[i], r[i]) - suffix[r[i]+1]; if(min < 0) ans[i] = -1; else ans[i] = maxTree.getRange(l[i], r[i]) - suffix[r[i]+1]; } } class SegmentTree { BiFunction<Long, Long, Long> function; //int identity; int n; long[] tree; //public SegmentTree(BiFunction<Integer, Integer, Integer> function, int[] arr, int identity){ public SegmentTree(BiFunction<Long, Long, Long> function, long[] arr){ this.function = function; //this.identity = identity; this.n = arr.length; int m = n<=1? 8: Integer.highestOneBit(n-1)*4; // int m = Integer.highestOneBit(n-1)*4; tree = new long[m]; //Arrays.fill(tree, identity); // O(n) build(arr, 1, 0, n-1); // O(nlgn) // for(int i=0; i<n; i++) // update(i, arr[i]); } private void build(long[] arr, int treeIdx, int left, int right) { if(left == right) { tree[treeIdx] = arr[left]; return; } int mid = (left+right)>>1; // int treeIdxLeftMid = treeIdx*2; // int treeIdxMidRight = treeIdx*2+1; int treeIdxLeftMid = treeIdx<<1; int treeIdxMidRight = (treeIdx<<1)+1; build(arr, treeIdxLeftMid, left, mid); build(arr, treeIdxMidRight, mid+1, right); tree[treeIdx] = function.apply(tree[treeIdxLeftMid], tree[treeIdxMidRight]); } public long getRange(int start, int end){ return getRange(start+1, end+1, 1, 1, n); // same as getRange(start, end, 1, 0, n-1); } private long getRange(int start, int end, int treeIdx, int left, int right) { // guaranteed: left <= start <= end <= right // alternative: just return identity for the case of out of range if(start == left && end == right) return tree[treeIdx]; int mid = (left+right)>>1; if(end <= mid) return getRange(start, end, treeIdx<<1, left, mid); else if(start <= mid){ long val1 = getRange(start, mid, treeIdx<<1, left, mid); long val2 = getRange(mid+1, end, (treeIdx<<1)+1, mid+1, right); return function.apply(val1, val2); } else return getRange(start, end, (treeIdx<<1)+1, mid+1, right); } } // Optional<T> solve() // return Optional.empty(); static class Pair implements Comparable<Pair>{ final static long FIXED_RANDOM = System.currentTimeMillis(); int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } @Override public int hashCode() { // http://xorshift.di.unimi.it/splitmix64.c long x = first; x <<= 32; x += second; x += FIXED_RANDOM; x += 0x9e3779b97f4a7c15l; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l; x = (x ^ (x >> 27)) * 0x94d049bb133111ebl; return (int)(x ^ (x >> 31)); } @Override public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; Pair other = (Pair) obj; return first == other.first && second == other.second; } @Override public String toString() { return "[" + first + "," + second + "]"; } @Override public int compareTo(Pair o) { int cmp = Integer.compare(first, o.first); return cmp != 0? cmp: Integer.compare(second, o.second); } } public static class MyScanner { BufferedReader br; StringTokenizer st; // 32768? public MyScanner(InputStream is, int bufferSize) { br = new BufferedReader(new InputStreamReader(is), bufferSize); } public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); // br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[][] nextMatrix(int n, int m) { return nextMatrix(n, m, 0); } int[][] nextMatrix(int n, int m, int offset) { int[][] mat = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[i][j] = nextInt()+offset; } } return mat; } int[][] nextTransposedMatrix(int n, int m){ return nextTransposedMatrix(n, m, 0); } int[][] nextTransposedMatrix(int n, int m, int offset){ int[][] mat = new int[m][n]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[j][i] = nextInt()+offset; } } return mat; } int[] nextIntArray(int len) { return nextIntArray(len, 0); } int[] nextIntArray(int len, int offset){ int[] a = new int[len]; for(int j=0; j<len; j++) a[j] = nextInt()+offset; return a; } long[] nextLongArray(int len) { return nextLongArray(len, 0); } long[] nextLongArray(int len, int offset){ long[] a = new long[len]; for(int j=0; j<len; j++) a[j] = nextLong()+offset; return a; } String[] nextStringArray(int len) { String[] s = new String[len]; for(int i=0; i<len; i++) s[i] = next(); return s; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } // public <T> void printlnAns(Optional<T> ans) { // if(ans.isEmpty()) // println(-1); // else // printlnAns(ans.get()); // } public void printlnAns(OptionalInt ans) { println(ans.orElse(-1)); } public void printlnAns(long ans) { println(ans); } public void printlnAns(int ans) { println(ans); } public void printlnAns(boolean[] ans) { for(boolean b: ans) printlnAns(b); } public void printlnAns(boolean ans) { if(ans) println(YES); else println(NO); } public void printAns(long[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(long[] arr){ printAns(arr); println(); } public void printAns(int[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(int[] arr){ printAns(arr); println(); } public <T> void printAns(ArrayList<T> arr){ if(arr != null && arr.size() > 0){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void printlnAns(ArrayList<T> arr){ printAns(arr); println(); } public void printAns(int[] arr, int add){ if(arr != null && arr.length > 0){ print(arr[0]+add); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]+add); } } } public void printlnAns(int[] arr, int add){ printAns(arr, add); println(); } public void printAns(ArrayList<Integer> arr, int add) { if(arr != null && arr.size() > 0){ print(arr.get(0)+add); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)+add); } } } public void printlnAns(ArrayList<Integer> arr, int add){ printAns(arr, add); println(); } public void printlnAnsSplit(long[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public void printlnAnsSplit(int[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public <T> void printlnAnsSplit(ArrayList<T> arr, int split){ if(arr != null && !arr.isEmpty()){ for(int i=0; i<arr.size(); i+=split){ print(arr.get(i)); for(int j=i+1; j<i+split; j++){ print(" "); print(arr.get(j)); } println(); } } } } static private void permutateAndSort(long[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); long temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private void permutateAndSort(int[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); int temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private int[][] constructChildren(int n, int[] parent, int parentRoot){ int[][] childrens = new int[n][]; int[] numChildren = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) numChildren[parent[i]]++; } for(int i=0; i<n; i++) { childrens[i] = new int[numChildren[i]]; } int[] idx = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) childrens[parent[i]][idx[parent[i]]++] = i; } return childrens; } static private int[][][] constructDirectedNeighborhood(int n, int[][] e){ int[] inDegree = new int[n]; int[] outDegree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outDegree[u]++; inDegree[v]++; } int[][] inNeighbors = new int[n][]; int[][] outNeighbors = new int[n][]; for(int i=0; i<n; i++) { inNeighbors[i] = new int[inDegree[i]]; outNeighbors[i] = new int[outDegree[i]]; } for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outNeighbors[u][--outDegree[u]] = v; inNeighbors[v][--inDegree[v]] = u; } return new int[][][] {inNeighbors, outNeighbors}; } static private int[][] constructNeighborhood(int n, int[][] e) { int[] degree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; degree[u]++; degree[v]++; } int[][] neighbors = new int[n][]; for(int i=0; i<n; i++) neighbors[i] = new int[degree[i]]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][--degree[u]] = v; neighbors[v][--degree[v]] = u; } return neighbors; } static private void drawGraph(int[][] e) { makeDotUndirected(e); try { final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot") .redirectOutput(new File("graph.png")) .start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } static private void makeDotUndirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict graph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "--" + e[i][1] + ";"); } out2.println("}"); out2.close(); } static private void makeDotDirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict digraph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "->" + e[i][1] + ";"); } out2.println("}"); out2.close(); } }
Java
["8 5\n0 1 2 9 3 2 7 5\n2 2 1 9 4 1 5 8\n2 6\n1 7\n2 4\n7 8\n5 8"]
2 seconds
["1\n3\n1\n-1\n-1"]
NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations: $$$pos = [1, 3, 5, 6]$$$ $$$pos = [1, 7]$$$ $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.
Java 17
standard input
[ "data structures", "dp", "greedy" ]
5f3022de0429cca31bab24501347eb69
The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i &lt; r_i \le n)$$$, the edges of segments.
2,200
For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.
standard output
PASSED
7ebc9eb1c64e71b26d05e5af3071a755
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
//---#ON_MY_WAY--- import static java.lang.Math.*; import java.io.*; import java.math.*; import java.util.*; public class apples { static FastReader x = new FastReader(); static OutputStream outputStream = System.out; static PrintWriter out = new PrintWriter(outputStream); /*---------------------------------------CODE STARTS HERE-------------------------*/ public static void main(String[] args) { int t = x.nextInt(); StringBuilder str = new StringBuilder(); while (t > 0) { int n = x.nextInt(); int odd = 0, even = 0; int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = x.nextInt(); if(a[i]%2==0) even++; else odd++; } if(abs(even-odd)>1) { str.append(-1); } else { ArrayList<Integer> e = new ArrayList<>(); ArrayList<Integer> o = new ArrayList<>(); ArrayList<Integer> ee = new ArrayList<>(); ArrayList<Integer> oo = new ArrayList<>(); for (int i = 0; i < n; i++) { if(a[i]%2==0&&i%2==0) e.add(i); if(a[i]%2==1&&i%2==1) o.add(i); if(a[i]%2==0&&i%2==1) ee.add(i); if(a[i]%2==1&&i%2==0) oo.add(i); } //System.out.println(e+" "+o+" "+ee+" "+oo); if((e.size()==0&&o.size()==0)||(ee.size()==0&&oo.size()==0)) { str.append(0); } else if(n%2==1) { int k = -1; if(even>odd) { if(ee.size()>0&&oo.size()>0) { k = 0; for(int i = 0; i < ee.size()&& i < oo.size(); i++) { k += abs(ee.get(i)-oo.get(i)); } } str.append(k); } else { int ans = -1; if(e.size()>0&&o.size()>0) { ans = 0; for(int i = 0; i < e.size()&&i < o.size(); i++) { ans += abs(e.get(i)-o.get(i)); } } str.append(ans); } } else { int ans = Integer.MAX_VALUE; if(e.size()>0&&o.size()>0) { ans = 0; for(int i = 0; i < e.size()&&i < o.size(); i++) { ans += abs(e.get(i)-o.get(i)); } } int k = Integer.MAX_VALUE; if(ee.size()>0&&oo.size()>0) { k = 0; for(int i = 0; i < ee.size()&& i < oo.size(); i++) { k += abs(ee.get(i)-oo.get(i)); } } ans = min(ans, k); str.append(ans); } } str.append("\n"); t--; } out.println(str); out.flush(); } /*--------------------------------------------FAST I/O--------------------------------*/ 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; } char nextchar() { char ch = ' '; try { ch = (char) br.read(); } catch (IOException e) { e.printStackTrace(); } return ch; } } /*--------------------------------------------BOILER PLATE---------------------------*/ static int[] readarr(int n) { int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = x.nextInt(); } return arr; } static int[] sortint(int a[]) { ArrayList<Integer> al = new ArrayList<>(); for (int i : a) { al.add(i); } Collections.sort(al); for (int i = 0; i < a.length; i++) { a[i] = al.get(i); } return a; } static long[] sortlong(long a[]) { ArrayList<Long> al = new ArrayList<>(); for (long i : a) { al.add(i); } Collections.sort(al); for (int i = 0; i < al.size(); i++) { a[i] = al.get(i); } return a; } static int pow(int x, int y) { int result = 1; while (y > 0) { if (y % 2 == 0) { x = x * x; y = y / 2; } else { result = result * x; y = y - 1; } } return result; } static int[] revsort(int a[]) { ArrayList<Integer> al = new ArrayList<>(); for (int i : a) { al.add(i); } Collections.sort(al, Comparator.reverseOrder()); for (int i = 0; i < a.length; i++) { a[i] = al.get(i); } return a; } static int[] gcd(int a, int b, int ar[]) { if (b == 0) { ar[0] = a; ar[1] = 1; ar[2] = 0; return ar; } ar = gcd(b, a % b, ar); int t = ar[1]; ar[1] = ar[2]; ar[2] = t - (a / b) * ar[2]; return ar; } static boolean[] esieve(int n) { boolean p[] = new boolean[n + 1]; Arrays.fill(p, true); for (int i = 2; i * i <= n; i++) { if (p[i] == true) { for (int j = i * i; j <= n; j += i) { p[j] = false; } } } return p; } static ArrayList<Integer> primes(int n) { boolean p[] = new boolean[n + 1]; ArrayList<Integer> al = new ArrayList<>(); Arrays.fill(p, true); int i = 0; for (i = 2; i * i <= n; i++) { if (p[i] == true) { al.add(i); for (int j = i * i; j <= n; j += i) { p[j] = false; } } } for (i = i; i <= n; i++) { if (p[i] == true) { al.add(i); } } return al; } static int etf(int n) { int res = n; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { res /= i; res *= (i - 1); while (n % i == 0) { n /= i; } } } if (n > 1) { res /= n; res *= (n - 1); } return res; } static int gcd(int a, int b) { if (a == 0) { return b; } return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) { return b; } return gcd(b % a, a); } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
c68093b0991915c65da968807e53af91
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; /** * * @author Acer */ public class NewClass1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-- > 0){ int n = sc.nextInt(); ArrayList<Integer> arr = new ArrayList<>(); int even = 0; int odd = 0; for (int i = 0; i < n; i++) { int a = sc.nextInt(); if(a%2 == 0){ arr.add(0); even++; } else{ arr.add(1); odd++; } } if(n == 1){ System.out.println(0); continue; } if(Math.abs(even-odd) > 1){ System.out.println(-1); } else{ if(even == odd){ int index = 0; int count1 = 0; for (int i = 0; i < n; i++) { if(arr.get(i) == 0){ count1+=Math.abs(i-index); index+=2; } } index = 1; int count2 = 0; for (int i = 0; i < n; i++) { if(arr.get(i) == 0){ count2+=Math.abs(i-index); index+=2; } } System.out.println(Math.min(count1, count2)); } else if(even > odd){ int index = 0; int count = 0; for (int i = 0; i < n; i++) { if(arr.get(i) == 0){ count+=Math.abs(i-index); index+=2; } } System.out.println(count); } else if(odd > even){ int index = 1; int count = 0; for (int i = 0; i < n; i++) { if(arr.get(i) == 0){ count+=Math.abs(i-index); index+=2; } } System.out.println(count); } } } } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
ec68814c190152f8285ab16199d29618
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.*; import java.util.*; import java.math.BigDecimal; import java.math.*; public class Main{ public static void main(String[] args) { TaskA solver = new TaskA(); int t = in.nextInt(); for (int i = 1; i <= t ; i++) { solver.solve(i, in, out); } // solver.solve(1, in, out); out.flush(); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n=in.nextInt(); int[]inp=new int[n]; ArrayList<Integer>odd=new ArrayList(); ArrayList<Integer>even= new ArrayList(); for(int i=0;i<n;i++) { inp[i]=in.nextInt(); if(inp[i]%2==0) {even.add(i);} else if(inp[i]%2==1) {odd.add(i);} } if(Math.abs(even.size()-odd.size())>1) { println(-1); return; } int count1=0,count2=0; for(int i=0;i<=n/2;i++) { if(i<odd.size()) { count1+=Math.abs(odd.get(i)-2*i); count2+=Math.abs(odd.get(i)-(2*i+1)); } } if(odd.size()>even.size()) { out.println(count1); } else if(even.size()>odd.size()) { out.println(count2); } else { out.println(Math.min(count1, count2)); } } } static int bs(int size,int[]arr) { int x = -1; for (int b = size/2; b >= 1; b /= 2) { while (!ok(arr)); } int k = x+1; return k; } static boolean ok(int[]x) { return false; } public static int solve1(ArrayList<Integer> A) { long[]arr =new long[A.size()+1]; int n=A.size(); for(int i=1;i<=A.size();i++) { arr[i]=((i%2)*((n-i+1)%2))%2; arr[i]%=2; } int ans=0; for(int i=0;i<A.size();i++) { if(arr[i+1]==1) { ans^=A.get(i); } } return ans; } public static String printBinary(long a) { String str=""; for(int i=31;i>=0;i--) { if((a&(1<<i))!=0) { str+=1; } if((a&(1<<i))==0 && !str.isEmpty()) { str+=0; } } return str; } public static String reverse(long a) { long rev=0; String str=""; int x=(int)(Math.log(a)/Math.log(2))+1; for(int i=0;i<32;i++) { rev<<=1; if((a&(1<<i))!=0) { rev|=1; str+=1; } else { str+=0; } } return str; } //////////////////////////////////////////////////////// static void sortF(Pair arr[], int n) { // Comparator to sort the pair according to second element Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { return p1.first - p2.first; } }); } static void sortS(Pair arr[], int n) { // Comparator to sort the pair according to second element Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { return p1.second - p2.second; } }); } static class Pair { int first ;int second ; public Pair(int x, int y) { this.first = x ;this.second = y ; } @Override public boolean equals(Object obj) { if(obj == this)return true ; if(obj == null)return false ; if(this.getClass() != obj.getClass()) return false ; Pair other = (Pair)(obj) ; if(this.first != other.first)return false ; if(this.second != other.second)return false ; return true ; } @Override public int hashCode() { return this.first^this.second ; } @Override public String toString() { String ans = "" ;ans += this.first ; ans += " "; ans += this.second ; return ans ; } } ////////////////////////////////////////////////////////////////////////// static int nD(long num) { String s=String.valueOf(num); return s.length(); } static int CommonDigits(int x,int y) { String s=String.valueOf(x); String s2=String.valueOf(y); return 0; } static int lcs(String str1, String str2, int m, int n) { int L[][] = new int[m + 1][n + 1]; int i, j; // Following steps build L[m+1][n+1] in // bottom up fashion. Note that L[i][j] // contains length of LCS of str1[0..i-1] // and str2[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (str1.charAt(i - 1) == str2.charAt(j - 1)) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m][n]; } ///////////////////////////////// boolean IsPowerOfTwo(int x) { return (x != 0) && ((x & (x - 1)) == 0); } //////////////////////////////// static long power(long a,long b,long m ) { long ans=1; while(b>0) { if(b%2==1) { ans=((ans%m)*(a%m))%m; b--; } else { a=(a*a)%m;b/=2; } } return ans%m; } /////////////////////////////// public static boolean repeatedSubString(String string) { return ((string + string).indexOf(string, 1) != string.length()); } static int search(char[]c,int start,int end,char x) { for(int i=start;i<end;i++) { if(c[i]==x) {return i;} } return -2; } //////////////////////////////// static int gcd(int a, int b) { while (b != 0) { int t = b; b = a % b; a = t; } return a; } static long fac(long a) { if(a== 0L || a==1L)return 1L ; return a*fac(a-1L) ; } static ArrayList al() { ArrayList<Integer>a =new ArrayList<>(); return a; } static HashSet h() { return new HashSet<Integer>(); } static void debug(int[][]a) { int n= a.length; for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { out.print(a[i][j]+" "); } out.print("\n"); } } static void debug(int[]a) { out.println(Arrays.toString(a)); } static void debug(ArrayList<Integer>a) { out.println(a.toString()); } static boolean[]seive(int n){ boolean[]b=new boolean[n+1]; for (int i = 2; i <= n; i++) b[i] = true; for(int i=2;i*i<=n;i++) { if(b[i]) { for(int j=i*i;j<=n;j+=i) { b[j]=false; } } } return b; } static int longestIncreasingSubseq(int[]arr) { int[]sizes=new int[arr.length]; Arrays.fill(sizes, 1); int max=1; for(int i=1;i<arr.length;i++) { for(int j=0;j<i;j++) { if(arr[j]<arr[i]) { sizes[i]=Math.max(sizes[i],sizes[j]+1); max=Math.max(max, sizes[i]); } } } return max; } public static ArrayList primeFactors(long n) { ArrayList<Long>h= new ArrayList<>(); // Print the number of 2s that divide n if(n%2 ==0) {h.add(2L);} // n must be odd at this point. So we can // skip one element (Note i = i +2) for (long i = 3; i <= Math.sqrt(n); i+= 2) { if(n%i==0) {h.add(i);} } if (n > 2) h.add(n); return h; } static boolean Divisors(long n){ if(n%2==1) { return true; } for (long i=2; i<=Math.sqrt(n); i++){ if (n%i==0 && i%2==1){ return true; } } return false; } static InputStream inputStream = System.in; static OutputStream outputStream = System.out; static InputReader in = new InputReader(inputStream); static PrintWriter out = new PrintWriter(outputStream); public static void superSet(int[]a,ArrayList<String>al,int i,String s) { if(i==a.length) { al.add(s); return; } superSet(a,al,i+1,s); superSet(a,al,i+1,s+a[i]+" "); } public static long[] makeArr() { long size=in.nextInt(); long []arr=new long[(int)size]; for(int i=0;i<size;i++) { arr[i]=in.nextInt(); } return arr; } public static long[] arr(int n) { long []arr=new long[n+1]; for(int i=1;i<n+1;i++) { arr[i]=in.nextLong(); } return arr; } public static void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } static void print(int c) { out.print(c); } static void println(int x) { out.println(x); } static void print(String s) { out.print(s); } static void println(String s) { out.println(s); } public static void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; //Copy data to temp arrays for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void reverse(int[] array) { int n = array.length; for (int i = 0; i < n / 2; i++) { int temp = array[i]; array[i] = array[n - i - 1]; array[n - i - 1] = temp; } } public static long nCr(int n,int k) { long ans=1L; k=k>n-k?n-k:k; for( int j=1;j<=k;j++,n--) { if(n%j==0) { ans*=n/j; }else if(ans%j==0) { ans=ans/j*n; }else { ans=(ans*n)/j; } } return ans; } static int searchMax(int index,long[]inp) { while(index+1<inp.length &&inp[index+1]>inp[index]) { index+=1; } return index; } static int searchMin(int index,long[]inp) { while(index+1<inp.length &&inp[index+1]<inp[index]) { index+=1; } return index; } public class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
47a17c25d09a55309b8a25a7b74b0b08
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int c = 0; public static void sort(int[] arr, int l, int r) { if (l < r) { int mid = (r + l) / 2; sort(arr, l, mid); sort(arr, mid + 1, r); merge(arr, l, mid, mid + 1, r); } } public static void merge(int[] arr, int l1, int r1, int l2, int r2) { int[] temp = new int[r2 - l1 + 1]; int p = 0; int l = l1; while (l1 <= r1 && l2 <= r2) { if (arr[l1] <= arr[l2]) temp[p++] = arr[l1++]; else { temp[p++] = arr[l2++]; c += r1 - l1 + 1; } } while (l1 <= r1) { temp[p++] = arr[l1++]; } while (l2 <= r2) { temp[p++] = arr[l2++]; } for (int i = 0; i < p; i++) { arr[i + l] = temp[i]; } } static void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static int weakness(int[] arr, int i) { if (i <= 1) return 0; if (arr[i] == 2) return arr[1]; return weakness(arr, i - 1) + arr[i - 1]; } public static void main(String[] args) throws IOException, InterruptedException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[] arr = sc.nextIntArray(n); int odd = 0, even = 0; PriorityQueue<Integer> evenP = new PriorityQueue<>(); PriorityQueue<Integer> oddP = new PriorityQueue<>(); for (int i = 0; i < n; i++) { if ((arr[i] & 1) == 0) { even++; evenP.add(i); } else { odd++; oddP.add(i); } } if (Math.abs(even - odd) > 1) pw.println(-1); else { int result = 0; if (even > odd) { int c = 1; while (!oddP.isEmpty()) { result += Math.abs(oddP.poll() - c); c += 2; } pw.println(result); } else if (odd > even) { int c = 1; while (!evenP.isEmpty()) { result += Math.abs(evenP.poll() - c); c += 2; } pw.println(result); } else { int r1 = 0, r2 = 0; int c = 1; while (!oddP.isEmpty()) { r1 += Math.abs(oddP.poll() - c); c += 2; } c = 1; while (!evenP.isEmpty()) { r2 += Math.abs(evenP.poll() - c); c += 2; } pw.println(Math.min(r1, r2)); } } } pw.flush(); } // static class Pair implements Comparable<Pair> { String x; int y; public Pair(String x, int y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public int compareTo(Pair p) { if (x.charAt(0) == p.x.charAt(0)) { String s1 = x + p.x; String s2 = p.x + x; return s1.compareTo(s2); } else return x.charAt(0) - p.x.charAt(0); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public int[] nextIntArray(int n) throws IOException { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] array = new Integer[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } public long[] nextlongArray(int n) throws IOException { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } public Long[] nextLongArray(int n) throws IOException { Long[] array = new Long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } public char[] nextCharArray(int n) throws IOException { char[] array = new char[n]; String string = next(); for (int i = 0; i < n; i++) { array[i] = string.charAt(i); } return array; } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
b8dc45dcf728667b967667a55195a7f0
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.util.Scanner; public class T1556B { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { int n = in.nextInt(); ArrayParity arrayParity = new ArrayParity(n); ArrayParity secondArrayParity = new ArrayParity(n); for (int j = 0; j < n; j++) { arrayParity.array[j] = (in.nextInt() % 2); secondArrayParity.array[j] = arrayParity.array[j]; } arrayParity.calculateCurrent(); secondArrayParity.calculateCurrent(); StatusFirstParity statusFirstParity = arrayParity.getStatusFirst(); if (statusFirstParity == StatusFirstParity.IMPOSSIBLE) { System.out.println("-1"); continue; } else if (statusFirstParity == StatusFirstParity.ZERO) { if (arrayParity.array[0] != 0) { arrayParity.swapAndUpdateCurrent(); } else { arrayParity.calculateCurrentZero(); } } else if (statusFirstParity == StatusFirstParity.ONE) { if (arrayParity.array[0] != 1) { arrayParity.swapAndUpdateCurrent(); } else { arrayParity.calculateCurrentOne(); } } else { if (arrayParity.array[0] == 0) { arrayParity.calculateCurrentZero(); secondArrayParity.swapAndUpdateCurrent(); } else { arrayParity.calculateCurrentOne(); secondArrayParity.swapAndUpdateCurrent(); } } calculateArrayParity(arrayParity); int steps; steps = arrayParity.steps; if (statusFirstParity == StatusFirstParity.ANY) { calculateArrayParity(secondArrayParity); if (secondArrayParity.steps < steps) { steps = secondArrayParity.steps; } } System.out.println(steps); } } static void calculateArrayParity(ArrayParity arrayParity) { int currentIndex = 1; while (currentIndex < arrayParity.n) { if (arrayParity.array[currentIndex] == arrayParity.array[currentIndex - 1]) { arrayParity.swapAndUpdateCurrent(); } else { if (arrayParity.array[currentIndex] == 0) { arrayParity.calculateCurrentZero(); } else { arrayParity.calculateCurrentOne(); } } currentIndex++; } } } enum StatusFirstParity { IMPOSSIBLE, ZERO, ONE, ANY; } class ArrayParity { int n; int array[]; int currentZero = -1; int currentOne = -1; int steps = 0; public ArrayParity(int[] array) { n = array.length; this.array = array; } public ArrayParity(int n) { this.n = n; array = new int[n]; } int getNumberEven() { int numberEven = 0; for (int i = 0; i < array.length; i++) { if (array[i] == 0) { numberEven++; } } return numberEven; } StatusFirstParity getStatusFirst() { int numberEven = getNumberEven(); int numberOdd = n - numberEven; //нечётное if (numberOdd - numberEven == 1) { return StatusFirstParity.ONE; } else if (numberEven - numberOdd == 1) { return StatusFirstParity.ZERO; } else if (numberEven == numberOdd) { return StatusFirstParity.ANY; } else { return StatusFirstParity.IMPOSSIBLE; } } void calculateCurrent() { calculateCurrentZero(); calculateCurrentOne(); } void calculateCurrentZero() { currentZero++; while (currentZero < n && array[currentZero] != 0) { currentZero++; } } void calculateCurrentOne() { currentOne++; while (currentOne < n && array[currentOne] != 1) { currentOne++; } } void swapAndUpdateCurrent() { steps += Math.abs(currentOne - currentZero); array[currentZero] = 1; array[currentOne] = 0; calculateCurrent(); } /*void calculateLast() { if (array[0] == 0) { currentZero = 0; currentOne = findNumberAfterIndex(1, 0); } else { currentOne = 0; currentZero = findNumberAfterIndex(0, 0); } }*/ /*int findNumberAfterIndex(int number, int index) { for (int i = index+1; i < array.length; i++) { if (array[i] == number) { return i; } } return -1; } int changeLastsAndUpdateLast() { array[currentOne] = 0; array[currentZero] = 1; int steps = 0; if (currentOne > currentZero) { steps = currentOne - currentZero; } else { steps = currentZero - currentOne; } currentZero = findNumberAfterIndex(0, currentZero); currentOne = findNumberAfterIndex(1, currentOne); return steps; }*/ }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
8f617168462d81e077c890b56bc1583c
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; public class A { public static BufferedReader in; public static void main(String[] args )throws Exception { InputStreamReader ina = new InputStreamReader(System.in); in = new BufferedReader(ina); int teste = Integer.parseInt(in.readLine()); int i = 1; while (teste-- > 0) { lahenda(i++); } } private static void lahenda(int test) throws Exception { int teste = Integer.parseInt(in.readLine()); String algne = in.readLine(); String[] arvud = algne.split(" "); ArrayList<Integer> paaris_indeks = new ArrayList<>(); ArrayList<Integer> paaritu_indeks = new ArrayList<>(); for (int i = 0; i < teste; i++) { int arv = Integer.valueOf(arvud[i]); if(arv%2 == 0){ paaris_indeks.add(i); } else { paaritu_indeks.add(i); } } // Kui üks arv vaid siis; if((paaris_indeks.size() + paaritu_indeks.size()) <=1){ System.out.println("0"); } else { // Kui paaris on 2 või enama võrra rohkem kui paarituid või teistpidi, siis võimatu if(Math.abs(paaris_indeks.size() - paaritu_indeks.size()) > 1){ System.out.println("-1"); } else { // Kas esimene on paaris või paaritute seas if(paaris_indeks.size() > paaritu_indeks.size()){ System.out.println(leia_vahetused(paaris_indeks)); } else if(paaritu_indeks.size() > paaris_indeks.size()) { System.out.println(leia_vahetused(paaritu_indeks)); } else { System.out.println(Math.min(leia_vahetused(paaritu_indeks), leia_vahetused(paaris_indeks))); } } } } private static int leia_vahetused(ArrayList<Integer> rohkematega) { int vahetused = 0; for (int i = 0; i < rohkematega.size(); i++) { vahetused = vahetused + Math.abs(rohkematega.get(i) - i*2); } return vahetused; } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
950bf9bf1e3869b9b8b4965b1430a1a8
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.util.*; import java.io.*; // import java.lang.*; // import java.math.*; public class Codeforces { static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); static long mod=1000000007; // static long mod=998244353; static int MAX=Integer.MAX_VALUE; static int MIN=Integer.MIN_VALUE; static long MAXL=Long.MAX_VALUE; static long MINL=Long.MIN_VALUE; static ArrayList<Integer> graph[]; public static void main (String[] args) throws java.lang.Exception { // code goes here int t=I(); outer:while(t-->0) { int n=I(); int a[]=new int[n]; ArrayList<Integer> e=new ArrayList<>(),o=new ArrayList<>(); int even=0,odd=0; for(int i=0;i<n;i++){ a[i]=I(); if(a[i]%2==0){ even++; e.add(i); }else{ odd++; o.add(i); } } if(n%2==0){ if(even==odd){ int j=0,temp1=0,temp2=0; for(int i:e){ temp1+=Math.abs(i-j); j+=2; } j=0; for(int i:o){ temp2+=Math.abs(i-j); j+=2; } out.println(Math.min(temp1,temp2)); }else{ out.println("-1"); } }else{ if(Math.abs(even-odd)==1){ if(even>odd){ int temp=0,j=0; for(int i:e){ temp+=Math.abs(i-j); j+=2; } out.println(temp); }else{ int temp=0,j=0; for(int i:o){ temp+=Math.abs(i-j); j+=2; } out.println(temp); } }else{ out.println("-1"); } } } out.close(); } public static class pair { long a; long b; public pair(long val,long index) { a=val; b=index; } } public static class myComp implements Comparator<pair> { //sort in ascending order. public int compare(pair p1,pair p2) { if(p1.a==p2.a) return 0; else if(p1.a<p2.a) return -1; else return 1; } //sort in descending order. // public int compare(pair p1,pair p2) // { // if(p1.a==p2.a) // return 0; // else if(p1.a<p2.a) // return 1; // else // return -1; // } } public static long kadane(long a[],int n) { long max_sum=Long.MIN_VALUE,max_end=0; for(int i=0;i<n;i++){ max_end+=a[i]; if(max_sum<max_end){max_sum=max_end;} if(max_end<0){max_end=0;} } return max_sum; } public static void DFS(int s,boolean visited[]) { visited[s]=true; for(int i:graph[s]){ if(!visited[i]){ DFS(i,visited); } } } public static void setGraph(int n,int m) { graph=new ArrayList[n+1]; for(int i=0;i<=n;i++){ graph[i]=new ArrayList<>(); } for(int i=0;i<m;i++){ int u=I(),v=I(); graph[u].add(v); graph[v].add(u); } } public static int BS(long a[],long x,int ii,int jj) { // int n=a.length; int mid=0; int i=ii,j=jj; while(i<=j) { mid=(i+j)/2; if(a[mid]<x){ i=mid+1; }else if(a[mid]>x){ j=mid-1; }else{ return mid; } } return -1; } public static int lower_bound(int arr[],int s, int N, int X) { if(arr[N]<X)return N; if(arr[0]>X)return -1; int left=s,right=N; while(left<right){ int mid=(left+right)/2; if(arr[mid]==X) return mid; else if(arr[mid]>X){ if(mid>0 && arr[mid]>X && arr[mid-1]<=X){ return mid-1; }else{ right=mid-1; } }else{ if(mid<N && arr[mid+1]>X && arr[mid]<=X){ return mid; }else{ left=mid+1; } } } return left; } public static ArrayList<Integer> primeSieve(int n) { ArrayList<Integer> arr=new ArrayList<>(); boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } for (int i = 2; i <= n; i++) { if (prime[i] == true) arr.add(i); } return arr; } // Fenwick / BinaryIndexed Tree USE IT - FenwickTree ft1=new FenwickTree(n); public static class FenwickTree { int farr[]; int n; public FenwickTree(int c) { n=c+1; farr=new int[n]; } // public void update_range(int l,int r,long p) // { // update(l,p); // update(r+1,(-1)*p); // } public void update(int x,int p) { for(;x<=n;x+=x&(-x)) { farr[x]+=p; } } public long get(int x) { long ans=0; for(;x>0;x-=x&(-x)) { ans=ans+farr[x]; } return ans; } } //Disjoint Set Union public static class DSU { int par[],rank[]; public DSU(int c) { par=new int[c+1]; rank=new int[c+1]; for(int i=0;i<=c;i++) { par[i]=i; rank[i]=0; } } public int find(int a) { if(a==par[a]) return a; return par[a]=find(par[a]); } public void union(int a,int b) { int a_rep=find(a),b_rep=find(b); if(a_rep==b_rep) return; if(rank[a_rep]<rank[b_rep]) par[a_rep]=b_rep; else if(rank[a_rep]>rank[b_rep]) par[b_rep]=a_rep; else { par[b_rep]=a_rep; rank[a_rep]++; } } } //SEGMENT TREE CODE // public static void segmentUpdate(int si,int ss,int se,int qs,int qe,long x) // { // if(ss>qe || se<qs)return; // if(qs<=ss && qe>=se) // { // seg[si][0]+=1L; // seg[si][1]+=x*x; // seg[si][2]+=2*x; // return; // } // int mid=(ss+se)/2; // segmentUpdate(2*si+1,ss,mid,qs,qe,x); // segmentUpdate(2*si+2,mid+1,se,qs,qe,x); // } // public static long segmentGet(int si,int ss,int se,int x,long f,long s,long t,long a[]) // { // if(ss==se && ss==x) // { // f+=seg[si][0]; // s+=seg[si][1]; // t+=seg[si][2]; // long ans=a[x]+(f*((long)x+1L)*((long)x+1L))+s+(t*((long)x+1L)); // return ans; // } // int mid=(ss+se)/2; // if(x>mid){ // return segmentGet(2*si+2,mid+1,se,x,f+seg[si][0],s+seg[si][1],t+seg[si][2],a); // }else{ // return segmentGet(2*si+1,ss,mid,x,f+seg[si][0],s+seg[si][1],t+seg[si][2],a); // } // } public static class myComp1 implements Comparator<pair1> { //sort in ascending order. public int compare(pair1 p1,pair1 p2) { if(p1.a==p2.a) return 0; else if(p1.a<p2.a) return -1; else return 1; } //sort in descending order. // public int compare(pair p1,pair p2) // { // if(p1.a==p2.a) // return 0; // else if(p1.a<p2.a) // return 1; // else // return -1; // } } public static class pair1 { long a; long b; public pair1(long val,long index) { a=val; b=index; } } public static ArrayList<pair1> mergeIntervals(ArrayList<pair1> arr) { //****************use this in main function-Collections.sort(arr,new myComp1()); ArrayList<pair1> a1=new ArrayList<>(); if(arr.size()<=1) return arr; a1.add(arr.get(0)); int i=1,j=0; while(i<arr.size()) { if(a1.get(j).b<arr.get(i).a) { a1.add(arr.get(i)); i++; j++; } else if(a1.get(j).b>arr.get(i).a && a1.get(j).b>=arr.get(i).b) { i++; } else if(a1.get(j).b>=arr.get(i).a) { long a=a1.get(j).a; long b=arr.get(i).b; a1.remove(j); a1.add(new pair1(a,b)); i++; } } return a1; } public static boolean isPalindrome(String s,int n) { for(int i=0;i<=n/2;i++){ if(s.charAt(i)!=s.charAt(n-i-1)){ return false; } } return true; } public static int gcd(int a,int b) { if(b==0) return a; else return gcd(b,a%b); } public static long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); } public static long fact(long n) { long fact=1; for(long i=2;i<=n;i++){ fact=((fact%mod)*(i%mod))%mod; } return fact; } public static long fact(int n) { long fact=1; for(int i=2;i<=n;i++){ fact=((fact%mod)*(i%mod))%mod; } return fact; } 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; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static void printArray(long a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(int a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(pair a[]) { for(int i=0;i<a.length;i++){ out.print(a[i].a+"->"+a[i].b+" "); } out.println(); } public static void printArray(char a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]); } out.println(); } public static void printArray(String a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(boolean a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(int a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(long a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(char a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArrayL(ArrayList<Long> arr) { for(int i=0;i<arr.size();i++){ out.print(arr.get(i)+" "); } out.println(); } public static void printArrayI(ArrayList<Integer> arr) { for(int i=0;i<arr.size();i++){ out.print(arr.get(i)+" "); } out.println(); } public static void printArrayS(ArrayList<String> arr) { for(int i=0;i<arr.size();i++){ out.print(arr.get(i)+" "); } out.println(); } public static void printMapInt(HashMap<Integer,Integer> hm){ for(Map.Entry<Integer,Integer> e:hm.entrySet()){ out.println(e.getKey()+"->"+e.getValue()); }out.println(); } public static void printMapLong(HashMap<Long,Long> hm){ for(Map.Entry<Long,Long> e:hm.entrySet()){ out.println(e.getKey()+"->"+e.getValue()); }out.println(); } //Modular Arithmetic public static long add(long a,long b) { a+=b; if(a>=mod)a-=mod; return a; } public static long sub(long a,long b) { a-=b; if(a<0)a+=mod; return a; } public static long mul(long a,long b) { return ((a%mod)*(b%mod))%mod; } public static long divide(long a,long b,long m) { a=mul(a,modInverse(b,m)); return a; } public static long modInverse(long a,long m) { int x=0,y=0; own p=new own(x,y); long g=gcdExt(a,m,p); if(g!=1){ out.println("inverse does not exists"); return -1; }else{ long res=((p.a%m)+m)%m; return res; } } public static long gcdExt(long a,long b,own p) { if(b==0){ p.a=1; p.b=0; return a; } int x1=0,y1=0; own p1=new own(x1,y1); long gcd=gcdExt(b,a%b,p1); p.b=p1.a - (a/b) * p1.b; p.a=p1.b; return gcd; } public static long pwr(long m,long n) { long res=1; m=m%mod; if(m==0) return 0; while(n>0) { if((n&1)!=0) { res=(res*m)%mod; } n=n>>1; m=(m*m)%mod; } return res; } public static class own { long a; long b; public own(long val,long index) { a=val; b=index; } } //Modular Airthmetic public static void sort(int[] A) { int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i) { int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } public static void sort(char[] A) { int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i) { char tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } public static void sort(long[] A) { int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i) { long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } public static int i(char ch){return Integer.parseInt(String.valueOf(ch));} public static int I(){return sc.I();} public static long L(){return sc.L();} public static String S(){return sc.S();} public static double D(){return sc.D();} } 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 I(){ return Integer.parseInt(next()); } long L(){ return Long.parseLong(next()); } double D(){ return Double.parseDouble(next()); } String S(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
87cf4b1943071fe081faa2b1c6683c4d
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.io.*; public class Equal { static class pair implements Comparable<pair> { int x; int y; public pair(int u, int v) { this.x = u; this.y = v; } @Override public int compareTo(pair o) { return o.x - x; } } static String input; static int scoreI = 100002; static int scoreO = 100002; static int[][] mem; static int dp(int l, int r) { if (l > r) { if (input.length() % 2 == 0) return -1; return 1; } if (mem[l][r] != 0) return mem[l][r]; int turn = (input.length() - (r - l + 1)) % 2; if (turn == 0) { if (input.charAt(l) == 'O' && input.charAt(r) == 'O') { return mem[l][r] = -(r - l + 2); } int d1 = 0; int d2 = 0; if (input.charAt(l) == 'I') d1 = dp(l + 1, r); if (input.charAt(r) == 'I') d2 = dp(l, r - 1); if (d1 == 0 || d2 == 0) return mem[l][r] = d1 + d2; else return mem[l][r] = Math.max(d1, d2); } if (input.charAt(l) == 'I' && input.charAt(r) == 'I') { return mem[l][r] = (r - l + 2); } int d1 = 0; int d2 = 0; if (input.charAt(l) == 'O') d1 = dp(l + 1, r); if (input.charAt(r) == 'O') d2 = dp(l, r - 1); if (d1 == 0 || d2 == 0) return mem[l][r] = d1 + d2; else return mem[l][r] = Math.min(d1, d2); } static int log(long a, long b) { int res = 0; while (a >= b) { a /= b; res++; } return res; } static long pow(long a, int b) { long res = 1; while (b-- > 0) { res *= a; } return res; } static int takePlaces(int[]evenPos,int[]oddPos,int[]a,int start){ int oCount=0; int eCount=0; int steps=0; int even=evenPos.length; int odd=oddPos.length; int last=1-start; for (int i = 0; i <even+odd ; i++) { int curr=1-last; int curEven=eCount==even?-1:evenPos[eCount]; int curOdd=oCount==odd?-1:oddPos[oCount]; if(curr==1){ if(curEven!=-1&&curOdd>curEven){ steps+=curOdd-curEven; for (int j = eCount; j <eCount+curOdd-curEven ; j++) { if(evenPos[j]<curOdd){ evenPos[j]++; } else break; } } oCount++; } else { if(curOdd!=-1&&curEven>curOdd) { steps+=curEven-curOdd; for (int j = oCount; j <oCount+curEven-curOdd ; j++) { if(oddPos[j]<curEven){ oddPos[j]++; } else break; } } eCount++; } last=curr; } return steps; } static int takePlaces2(int[]a,int start){ int []a2=a.clone(); int cur=start; int steps=0; int eCount=-1; for (int i = 0; i <a2.length ; i++) { if(a2[i]==0){ eCount=i; break; } } int oCount=-1; for (int i = 0; i <a2.length ; i++) { if(a2[i]==1){ oCount=i; break; } } for (int i = 0; i <a2.length ; i++) { if(a2[i]!=cur){ steps+=Math.abs(oCount-eCount); a2[oCount]=0; a2[eCount]=1; for (int j = oCount+1; j <a2.length ; j++) { if(a2[j]==1){ oCount=j; break; } } for (int j = eCount+1; j <a2.length ; j++) { if(a2[j]==0){ eCount=j; break; } } } else{ if(cur==0){ for (int j = eCount+1; j <a2.length ; j++) { if(a2[j]==0){ eCount=j; break; } } } else { for (int j = oCount+1; j <a2.length ; j++) { if(a2[j]==1){ oCount=j; break; } } } } cur=1-cur; } return steps; } public static void main(String[] args) throws IOException { //BufferedReader br = new BufferedReader(new FileReader("name.in")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; PrintWriter out = new PrintWriter(System.out); int T=Integer.parseInt(br.readLine()); while(T-->0){ int n=Integer.parseInt(br.readLine()); st=new StringTokenizer(br.readLine()); int odd=0; int even=0; int[]a=new int[n]; for (int i = 0; i < n; i++) { a[i]=(Integer.parseInt(st.nextToken()))%2; if(a[i]==0) even++; else odd++; } if(Math.abs(odd-even)>1) out.println(-1); else{ int[]oddPos=new int[odd]; int[]evenPos=new int[even]; int[]oddPos2=new int[odd]; int[]evenPos2=new int[even]; int oCount=0; int eCount=0; for (int i = 0; i <n ; i++) { if(a[i]==0){ evenPos[eCount]=evenPos2[eCount]=i; eCount++; } else{ oddPos[oCount]=oddPos2[oCount]=i; oCount++; } } int steps=takePlaces2(a,even>odd?0:1); int steps2=steps+1; if(odd==even) steps2=takePlaces2(a,0); out.println(Math.min(steps,steps2)); } } out.flush(); out.close(); } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
c883117ddef7987a615e76d5c8e0d48c
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.*; import java.util.*; public class Trials2 { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader inp=new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); int t=Integer.parseInt(inp.readLine()); while(t-- >0) { int n=Integer.parseInt(inp.readLine()); String s[]=inp.readLine().split(" "); long arr[]=new long[n]; ArrayList<Integer> even=new ArrayList<>(); ArrayList<Integer> odd=new ArrayList<>(); boolean v[]=new boolean[n]; Arrays.fill(v, false); for(int i=0;i<n;i++) { arr[i]=Long.parseLong(s[i]); if(arr[i]%2==0) even.add(i); else odd.add(i); } if(n%2==0 && even.size()!=odd.size()) out.write("-1 \n"); else if(n%2==1 && Math.abs(even.size()-odd.size())!=1) out.write("-1 \n"); else { long val1=0; long val2=0; for(int i=0;i<even.size();i++) { val1+=Math.abs(even.get(i)-2*i); } for(int i=0;i<odd.size();i++) { val2+=Math.abs(odd.get(i)-2*i); } if(even.size()>odd.size()) { out.write(Long.toString(val1)+"\n"); } else if(even.size()<odd.size()) { out.write(Long.toString(val2)+"\n"); } else { out.write(Long.toString(Math.min(val1, val2))+"\n"); } } } out.flush(); } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
a37036dd73f9de6a6aa228d7d3e7e518
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.util.*; import static java.lang.Math.*; import java.io.*; public class Exercise { static Scanner sc = new Scanner(System.in); static int numbers[]; static int numEl; static int test(int c) { int count = 0; int cost = 0; for(int i = 1; i <=numEl; i++) { if(numbers[i] % 2 == c) { count++; cost += abs(i - (count * 2 - 1)); } } return cost; } static void solve() { numEl = sc.nextInt(); numbers = new int[numEl+1]; int even = 0, odd = 0; for(int i = 1; i <= numEl; i++) { numbers[i] = sc.nextInt(); if(numbers[i] % 2 == 0) even++; else odd++; } if(abs(odd - even) > 1) { System.out.println(-1); return; } long ans = (long) 1e18; if(odd>=even) ans = min(ans, test(1)); if(even>=odd) ans = min(ans, test(0)); System.out.println(ans); } public static void main(String[] args) throws IOException { int testcases = sc.nextInt(); while (testcases-- != 0) solve(); } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
0494c974b228b7c74eebb26955823cc0
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class P1556B_TakeYourPlaces { public static int[] a; public static int n; public static ArrayList<Integer> evenIndices, indices; public static long ans = 0; public static void main(String[] subhani) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); a = new int[n]; ans = 0; for (int i = 0; i < n; ++i) a[i] = Integer.parseInt(st.nextToken()) % 2; solve(); } } public static void solve() { evenIndices = new ArrayList<>(); ans = Integer.MAX_VALUE; for (int i = 0; i < n; ++i) if (a[i] == 0) evenIndices.add(i); for (int r = 0; r < 2; ++r) { indices = new ArrayList<Integer>(); for (int i = r; i < n; i += 2) indices.add(i); if (indices.size() == evenIndices.size()) { long swaps = 0; for (int i = 0; i < indices.size(); ++i) swaps += Math.abs(indices.get(i) - evenIndices.get(i)); ans = Math.min(ans, swaps); } } if (ans == Integer.MAX_VALUE) System.out.println(-1); else System.out.println(ans); } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
1271ff13e43baadf451ea969a9495a70
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import static java.lang.Math.*; import java.io.*; import java.math.*; import java.util.*; public class cf3 { static FastReader x = new FastReader(); static OutputStream outputStream = System.out; static PrintWriter out = new PrintWriter(outputStream); /*---------------------------------------CODE STARTS HERE-------------------------*/ public static void main(String[] args) { int t = x.nextInt(); StringBuilder str = new StringBuilder(); while (t > 0) { int n = x.nextInt(); int a[] = new int[n]; ArrayList<Integer> odd = new ArrayList<>(); for(int i=0;i<n;i++) { a[i] = x.nextInt(); if(a[i]%2!=0) { odd.add(i); } } int j=0; int k=0; boolean pos =false; if(odd.size()==(n/2)||odd.size()==(n+1)/2) { pos=true; } int ans =0; int c1=0,c2=0; if(pos) { if(n%2==0) { int t1[] = new int[n]; int t2[] =new int[n]; int m=0; for(int i=0;i<n;i++) { t1[i]=m; m=(m+1)%2; t2[i]=m; if(t1[i]==1) { c1 += abs(i-odd.get(j)); j++; } if(t2[i]==1) { c2+=abs(i-odd.get(k)); k++; } } ans = min(c1,c2); }else { int m=0; int o = odd.size(); int e = n-odd.size(); if(o>e) { m=1; } int t1[] = new int[n]; for(int i=0;i<n;i++) { t1[i] =m; m=(m+1)%2; if(t1[i]==1) { ans+=(abs(i-odd.get(j))); j++; } } } System.out.println(ans); }else { System.out.println(-1); } str.append("\n"); t--; } out.println(str); out.flush(); } /*--------------------------------------------FAST I/O--------------------------------*/ 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; } char nextchar() { char ch = ' '; try { ch = (char) br.read(); } catch (IOException e) { e.printStackTrace(); } return ch; } } /*--------------------------------------------BOILER PLATE---------------------------*/ static int[] readarr(int n) { int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = x.nextInt(); } return arr; } static int[] sortint(int a[]) { ArrayList<Integer> al = new ArrayList<>(); for (int i : a) { al.add(i); } Collections.sort(al); for (int i = 0; i < a.length; i++) { a[i] = al.get(i); } return a; } static long[] sortlong(long a[]) { ArrayList<Long> al = new ArrayList<>(); for (long i : a) { al.add(i); } Collections.sort(al); for (int i = 0; i < al.size(); i++) { a[i] = al.get(i); } return a; } static int pow(int x, int y) { int result = 1; while (y > 0) { if (y % 2 == 0) { x = x * x; y = y / 2; } else { result = result * x; y = y - 1; } } return result; } static int[] revsort(int a[]) { ArrayList<Integer> al = new ArrayList<>(); for (int i : a) { al.add(i); } Collections.sort(al, Comparator.reverseOrder()); for (int i = 0; i < a.length; i++) { a[i] = al.get(i); } return a; } static int[] gcd(int a, int b, int ar[]) { if (b == 0) { ar[0] = a; ar[1] = 1; ar[2] = 0; return ar; } ar = gcd(b, a % b, ar); int t = ar[1]; ar[1] = ar[2]; ar[2] = t - (a / b) * ar[2]; return ar; } static boolean[] esieve(int n) { boolean p[] = new boolean[n + 1]; Arrays.fill(p, true); for (int i = 2; i * i <= n; i++) { if (p[i] == true) { for (int j = i * i; j <= n; j += i) { p[j] = false; } } } return p; } static ArrayList<Integer> primes(int n) { boolean p[] = new boolean[n + 1]; ArrayList<Integer> al = new ArrayList<>(); Arrays.fill(p, true); int i = 0; for (i = 2; i * i <= n; i++) { if (p[i] == true) { al.add(i); for (int j = i * i; j <= n; j += i) { p[j] = false; } } } for (i = i; i <= n; i++) { if (p[i] == true) { al.add(i); } } return al; } static int etf(int n) { int res = n; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { res /= i; res *= (i - 1); while (n % i == 0) { n /= i; } } } if (n > 1) { res /= n; res *= (n - 1); } return res; } static int gcd(int a, int b) { if (a == 0) { return b; } return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) { return b; } return gcd(b % a, a); } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
f05bf1a8a0350cc81d8a61d1693befcc
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.*; import java.util.*; public class TakeYourPlaces { static int getAfter(int[] a , int pos ,int x){ for(int i=pos; i<a.length ;i++){ if(a[i]%2 != x) return i; } return -1; } static int getBefore(int[] a , int pos , int x){ for(int i=pos; i>=0 ;i--) if(a[i]%2 != x) return i; return -1; } public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt() , even = 0; int[] a = new int[n]; for(int i=0; i<n ;i++) { a[i] = sc.nextInt(); if (a[i] % 2 == 0) even++; } int odd = n-even; if(Math.abs(even - odd) > 1) pw.println(-1); else{ long ans = (long) 1e+18; if(even>=odd){ int next = 0; long c = 0; for(int i=0; i<n ;i++){ if(a[i]%2 == 0){ c += Math.abs(i-next); next += 2; } } ans = Math.min(ans , c); } if(odd >= even){ int next = 0; long c = 0; for(int i=0; i<n ;i++){ if(a[i]%2 == 1){ c += Math.abs(i-next); next += 2; } } ans = Math.min(ans , c); } pw.println(ans); } } pw.flush(); } static class pair implements Comparable <pair>{ int x , y; pair(int x,int y){ this.x = x; this.y = y; } public int compareTo(pair p){ if(p.x > x) return -2; else if(p.x < x) return 2; else{ if(p.y > y) return -2; else return 2; } } public String toString(){ return x+" "+y; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws IOException { br = new BufferedReader(new FileReader(file)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String readAllLines(BufferedReader reader) throws IOException { StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line); content.append(System.lineSeparator()); } return content.toString(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
72b8ecaa044360801d2d74197dedf04e
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int T = in.nextInt(); for(int ttt = 1; ttt <= T; ttt++) { int n = in.nextInt(); int[] a = in.readInt(n); int e = 0, ans = 0; for(int val : a) if(val%2==0) e++; if((n%2==0 && e!=n/2) || (e!=n/2 && e!=n/2+1)) out.println(-1); else { if(n%2==0) { int m1 = 0, m2 = 0, cur = 0; for(int i = 0; i < n; i++) { if(a[i]%2==0) { if(i != cur) m1 += Math.abs(cur-i); cur+=2; } } cur = 0; for(int i = 0; i < n; i++) { if(a[i]%2==1) { if(i != cur) m2 += Math.abs(cur-i); cur+=2; } } ans = Math.min(m1, m2); } else { if(e==n/2) { int cur = 0; for(int i = 0; i < n; i++) { if(a[i]%2==1) { if(i != cur) ans += Math.abs(cur-i); cur+=2; } } } else { int cur = 0; for(int i = 0; i < n; i++) { if(a[i]%2==0) { if(i != cur) ans += Math.abs(cur-i); cur+=2; } } } } out.println(ans); } } out.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; } int[] readInt(int size) { int[] arr = new int[size]; for(int i = 0; i < size; i++) arr[i] = Integer.parseInt(next()); return arr; } long[] readLong(int size) { long[] arr = new long[size]; for(int i = 0; i < size; i++) arr[i] = Long.parseLong(next()); return arr; } int[][] read2dArray(int rows, int cols) { int[][] arr = new int[rows][cols]; for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) arr[i][j] = Integer.parseInt(next()); } return arr; } } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
8967af0468db892ef1309894947dd6b3
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args) { FastReader in = new FastReader(); int T = in.nextInt(); while(T-- > 0) { int n = in.nextInt(); int[] a = in.readInt(n); int e = 0; for(int v : a) if(v%2==0) e++; if(Math.max(e, n-e) > (n+1)/2) System.out.println(-1); else { if(n%2==0) { int c1 = 0, c2 = 0; // c1 = moves to move all evens to even positions int cur = 0; for(int i = 0; i < n; i++) { if(a[i]%2==0) { if(i < cur) { c1 += cur-i; } else if(i > cur) { c1 += i-cur; } cur += 2; } } // c2 = moves to move all evens to odd positions cur = 1; for(int i = 0; i < n; i++) { if(a[i]%2==0) { if(i < cur) { c2 += cur-i; } else if(i > cur) { c2 += i-cur; } cur += 2; } } System.out.println(Math.min(c1, c2)); } else { if(e > n-e) { int cur = 0, c1 = 0; for(int i = 0; i < n; i++) { if(a[i]%2==0) { if(i < cur) { c1 += cur-i; } else if(i > cur) { c1 += i-cur; } cur += 2; } } System.out.println(c1); } else { int cur = 1, c1 = 0; for(int i = 0; i < n; i++) { if(a[i]%2==0) { if(i < cur) { c1 += cur-i; } else if(i > cur) { c1 += i-cur; } cur += 2; } } System.out.println(c1); } } } } } 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; } int[] readInt(int size) { int[] arr = new int[size]; for(int i = 0; i < size; i++) arr[i] = Integer.parseInt(next()); return arr; } long[] readLong(int size) { long[] arr = new long[size]; for(int i = 0; i < size; i++) arr[i] = Long.parseLong(next()); return arr; } int[][] read2dArray(int rows, int cols) { int[][] arr = new int[rows][cols]; for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) arr[i][j] = Integer.parseInt(next()); } return arr; } } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
0d2d017f72c826d1566e10bc45cc0a38
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; import java.util.Vector; public class Deltix2 { public static void main(String [] args) { FastReader fs = new FastReader(); int t = fs.nextInt(); for (int i = 0; i < t; i++) { int n = fs.nextInt(); long arr[] = new long[n]; int eo[] = new int[n]; int odd = 0, even = 0; for (int j = 0; j < n; j++) { arr[j] = fs.nextInt(); if (arr[j] % 2 == 0) { even++; eo[j] = 0; } else { odd++; eo[j] = 1; } } if (Math.abs(odd - even) > 1) { System.out.println(-1); continue; } if (odd > even) { System.out.println(solve(eo, n, 1)); } else if (odd < even) { System.out.println(solve(eo, n, 0)); } else { int a = solve(eo, n, 0); int b = solve(eo, n, 1); System.out.println(Math.min(a, b)); } } } static int solve (int arr[], int n, int fl) { int res = 0; // int counter = 0; Queue<Pair> q = new LinkedList<>(); for (int i = 0; i < n; i++) { if (arr[i] != fl) { if (!q.isEmpty() && q.peek().key == arr[i]) { res += i-q.remove().val; } else { int key = arr[i] == 0 ? 1 : 0; q.add(new Pair(key, i)); } } fl = fl == 0 ? 1 : 0; } return res; } static class Pair { int key; int val; Pair(int key, int value) { this.key = key; this.val = value; } } static void swap (int arr[], int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } static int gcd (int a, int b) { if (b == 0) { return a; } return gcd(b, a%b); } static void pa(int arr[]) { System.out.println(Arrays.toString(arr)); } static void pa(String arr[]) { System.out.println(Arrays.toString(arr)); } static int[] sieve(int n) { int prime[] = new int[n]; Arrays.fill(prime, 1); for (int i = 2; i < n; i++) { if (prime[i] == 1) { for (int j = i*i; i <= n; j+=i) { prime[i] = 0; } } } return prime; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
aeba5a9d57725ca8d3088f24794c4a1a
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class b { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); int tc = Integer.parseInt(br.readLine()); for (int tt = 0; tt < tc; tt++) { int n = Integer.parseInt(br.readLine()); st = new StringTokenizer(br.readLine()); List<Integer> list = new ArrayList<>(); int[] cnt = new int[2]; //1010101010 or 010101010 only possible //positions List<Integer> ones = new ArrayList<>(); List<Integer> zeros = new ArrayList<>(); int idx = 0; while (st.hasMoreTokens()) { int parity = Integer.parseInt(st.nextToken()) % 2; list.add(parity); cnt[parity]++; if (parity == 0) { zeros.add(idx); } else { ones.add(idx); } idx++; } if (Math.abs(cnt[0] - cnt[1]) >= 2) { System.out.println(-1); continue; } int[] answer = new int[]{(int)2e9,(int)2e9}; //10101010 if (ones.size() >= zeros.size()) { int diffSum=0; for (int i = 0, pos = 0; i < ones.size(); i++, pos += 2) { int position = ones.get(i); diffSum += Math.abs(position - pos); } answer[0] = diffSum; } //01010101 if (ones.size() <= zeros.size()) { int diffSum=0; for (int i = 0, pos = 0; i < zeros.size(); i++, pos += 2) { int position = zeros.get(i); diffSum += Math.abs(position - pos); } answer[1] = diffSum; } if (Math.min(answer[0], answer[1]) == (int) 2e9) { System.out.println(-1); } else { System.out.println(Math.min(answer[0], answer[1])); } } } private static int gcd(int a, int b) { if (a % b == 0) return b; else return gcd(b, a % b); } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
a01c4becdf14be5de0d4c87bb378f138
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.time.LocalTime; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class B { public static void main(String[] args) { FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int T = 1; T = scan.nextInt(); for(int tt=0; tt<T; tt++) { n = scan.nextInt(); int [] a = scan.readArray(n); ArrayList<Integer> even = new ArrayList<>(), odd = new ArrayList<>(); for(int i=0; i<n; i++) { if(a[i] % 2== 0) even.add(i); else odd.add(i); } if(Math.abs(even.size() - odd.size()) > 1) System.out.println(-1); else { long ans = Long.MAX_VALUE; if(even.size() >= odd.size()) ans = Math.min(ans, getMoves(true, even, odd)); if(odd.size() >= even.size()) ans = Math.min(ans, getMoves(false, even, odd)); System.out.println(ans /2); } } } static int n; static long getMoves(boolean evenTurn, ArrayList<Integer> even, ArrayList<Integer> odd) { long moves = 0; int p1 = 0, p2 = 0; for(int i=0; i<n; i++) { if(evenTurn) { moves += Math.abs(even.get(p1++) - i); evenTurn = false; } else { moves += Math.abs(odd.get(p2++) - i); evenTurn = true; } } return moves; } static int gcd(int a, int b) { if(b == 0) return a; return gcd(b, a % b); } /* static class IntComparator implements Comparator<Integer> { public int compare(Integer o1, Integer o2) { // return Integer.compare(a[o1], a[o2]); return 0; } } */ public static void printIntArray(int [] a) { for(int i: a) System.out.print(i + " "); System.out.println(); } public static void swapInt(int a, int b) { int temp = a; a = b; b = temp; } public static void sort(int [] a) { ArrayList<Integer> b = new ArrayList<>(); for(int i: a) b.add(i); Collections.sort(b); for(int i=0; i<a.length; i++) a[i]= b.get(i); } public static void reverse(int [] a) { ArrayList<Integer> b = new ArrayList<>(); for(int i: a) b.add(i); Collections.reverse(b); for(int i=0; i<a.length; i++) a[i]= b.get(i); } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while(!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int [] readArray(int n) { int [] a = new int[n]; for(int i=0; i<n ; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } } /* fun main(args: Array<String>) { Main.main(args); } */
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
04dff09b37c1552da0613948b6f9263a
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Coder { // static int find(int parent[], int i){ // if(parent[i]!=i) // parent[i]=find(parent, parent[i]); // return parent[i]; // } // static void union(int parent[], int rank[], int x, int y){ // int xr=find(parent, x); // int yr=find(parent, y); // if(rank[xr]<rank[yr]){ // parent[xr]=yr; // }else if(rank[yr]<rank[xr]){ // parent[yr]=xr; // }else{ // parent[xr]=yr; // rank[yr]++; // } // } // static void extendedGcd(long a, long b, long ar[]){ // if(b==0){ // ar[0]=1; // ar[1]=0; // ar[2]=a; // return; // } // extendedGcd(b, a%b, ar); // long temp=ar[1]; // ar[1]=(ar[0]- ar[1]*(a/b)); // ar[0]=temp; // return; // } // // non prime b; // static long invmod(long a, long b){ // long ar[]=new long[3]; // extendedGcd(a, b, ar); // return ar[0]; // } // static long pow(long a, long b){ // long res=1; // while(b>0){ // if(b%2==1){ // res = (res * a)%mod; // b--; // }else{ // a = (a*a)%mod; // b=b>>1; // } // } // return res; // } // static long combination(int a, int b){ // long val1=fact[a]; // long val2=ifact[a-b]; // long val3=ifact[b]; // return (((val1 * val2)%mod) * val3)%mod; // } // static void cal(){ // fact[0]=ifact[0]=1; // for(int i=1;i<sz;i++){ // fact[i]=(i*fact[i-1])%mod; // } // ifact[sz-1]=pow(fact[sz-1], mod-2); // for(int i=sz-2;i>0;i--){ // ifact[i]=((i+1)*ifact[i+1])%mod; // } // } static StringBuffer str=new StringBuffer(); static long a[]; static int n; static void solve(){ List<Integer> odd=new ArrayList<>(); List<Integer> even=new ArrayList<>(); for(int i=0;i<n;i++){ if(a[i]%2==1) odd.add(i); else even.add(i); } if(Math.abs(odd.size()-even.size())>1){ str.append(-1).append("\n"); return; } long sum=0; if(odd.size()>=even.size()){ int cnt=0; for(int i=0;i<odd.size();i++){ sum+=Math.abs(odd.get(i)-cnt); cnt+=2; } cnt=1; for(int i=0;i<even.size();i++){ sum+=Math.abs(even.get(i)-cnt); cnt+=2; } } long sum1=0; if(even.size()>=odd.size()){ int cnt=0; for(int i=0;i<even.size();i++){ sum1+=Math.abs(even.get(i)-cnt); cnt+=2; } cnt=1; for(int i=0;i<odd.size();i++){ sum1+=Math.abs(odd.get(i)-cnt); cnt+=2; } } if(odd.size()>even.size()){ str.append(sum/2).append("\n"); }else if(even.size()>odd.size()){ str.append(sum1/2).append("\n"); }else{ str.append(Math.min(sum, sum1)/2).append("\n"); } } public static void main(String[] args) throws java.lang.Exception { BufferedReader bf; PrintWriter pw; boolean lenv=false; if(lenv){ bf = new BufferedReader( new FileReader("input.txt")); pw=new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); }else{ bf = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new OutputStreamWriter(System.out)); } int q = Integer.parseInt(bf.readLine().trim()); while (q-- > 0) { n=Integer.parseInt(bf.readLine().trim()); a=new long[n]; String s[]=bf.readLine().trim().split("\\s+"); for(int i=0;i<n;i++) a[i]=Long.parseLong(s[i]); solve(); } pw.print(str); pw.flush(); // System.out.print(str); } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
d180b3df6d6d8f3d251671747e83439f
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.util.*; import java.io.*; public class sortings { static Scanner sc=new Scanner(System.in); static PrintWriter pw=new PrintWriter(System.out); static BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); public static void main(String []args) throws IOException { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int [] a=new int [n]; int counteven=0,countodd=0; int p1=0,p2=0,p3=0,p4=0; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(a[i]%2==0) { counteven++; } else { countodd++; } } if(counteven>countodd) { p1=0;p2=1; } else if(counteven==countodd) { p1=0;p2=1;p3=1;p4=0; } else { p1=1;p2=0; } int [] ans=new int [n],ans2=new int [n]; for(int i=0;i<n;i++) { if(a[i]%2==0) { ans[i]=p1; p1+=2; } else { ans[i]=p2; p2+=2; } if(n%2==0) { if(a[i]%2==0) { ans2[i]=p3; p3+=2; } else { ans2[i]=p4; p4+=2; } } } boolean f=true; if(n%2==0) { if(counteven==countodd) { f=false; } } else { if(Math.abs(counteven-countodd)==1) f=false; } if(f) pw.println(-1); else { count=0; //pw.println(Arrays.toString(ans)); mergesort(ans); long x=count; if(n%2!=0) pw.println(x); else { count=0; //pw.println(Arrays.toString(ans2)); mergesort(ans2); pw.println(Math.min(count, x)); } } } pw.flush(); } static long count; public static void merge(int []a,int start,int mid,int end) { int []b=new int[end-start+1]; int ind1=start,ind2=mid+1; int cur=0; while(ind1<mid+1 || ind2<end+1) { if(ind1==mid+1) { for(;ind2<end+1;ind2++) { b[cur++]=a[ind2]; } } else if(ind2==end+1) { for(;ind1<mid+1;ind1++) { b[cur++]=a[ind1]; } } else { if(a[ind1]>a[ind2]) { b[cur++]=a[ind2++]; count+=mid-ind1+1; } else { b[cur++]=a[ind1++]; } } } for(int i=0;i<b.length;i++) { a[i+start]=b[i]; } } public static void sort(int []a,int start,int end ) { if(end==start) return; int mid=(start+end)/2; sort(a, start, mid); sort(a, mid+1, end); merge(a, start, mid, end); //pw.println(Arrays.toString(s)); } public static void mergesort(int []a) { sort(a, 0, a.length-1); } static long count2=0; public static void insertionSort(int []a) { int n=a.length; for(int i=1;i<n;i++) { int j=i-1; int key=a[i]; while(j>-1 && a[j]>key) { a[j+1]=a[j]; j--; //count2++; } a[j+1]=key; } } static class pair implements Comparable<pair> { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Double(x).hashCode() * 31 + new Double(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String readAllLines(BufferedReader reader) throws IOException { StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line); content.append(System.lineSeparator()); } return content.toString(); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
dad8a69e9d3e7d256f8a30986a104544
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; import java.io.PrintWriter; public class G_TakeYourPlaces { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); int evenC = 0; int oddC = 0; int[] arr = new int[n]; for (int i = 0; i < n; i++) { int x = sc.nextInt(); if(x % 2 == 0) evenC++; else oddC++; arr[i] = x; } if ( Math.abs(evenC - oddC) > 1 ){ pw.println(-1); continue; } int c; if(evenC > oddC){ c = even(arr); } else if(oddC > evenC){ c = odd(arr); } else{ c = Math.min(even(arr), odd(arr)); } pw.println(c); } pw.flush(); } public static int even(int[] arr){ int result = 0; int currI = 0; int n = arr.length; for (int i = 0; i < n; i++) { if(arr[i] % 2 == 0){ result += Math.abs( currI - i ); currI += 2; } } return result; } public static int odd(int[] arr){ int result = 0; int currI = 0; int n = arr.length; for (int i = 0; i < n; i++) { if(arr[i] % 2 == 1){ result += Math.abs( currI - i ); currI += 2; } } return result; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
de9cadac9b008817123cf7e17bed6564
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.*; import java.util.*; public class _1556b { FastScanner scn; PrintWriter w; PrintStream fs; long MOD = 1000000007; int N=100000+10; long mul(long x, long y) {long res = x * y; return (res >= MOD ? res % MOD : res);} long power(long x, long y) {if (y < 0) return 1; long res = 1; x %= MOD; while (y!=0) {if ((y & 1)==1)res = mul(res, x); y >>= 1; x = mul(x, x);} return res;} void ruffleSort(int[] a) {int n=a.length;Random r=new Random();for (int i=0; i<a.length; i++) {int oi=r.nextInt(n), temp=a[i];a[i]=a[oi];a[oi]=temp;}Arrays.sort(a);} boolean LOCAL; void debug(Object... o){if(LOCAL)System.err.println(Arrays.deepToString(o));} void solve(){ int t=scn.nextInt(); while(t-->0) { int n=scn.nextInt(),no=0,ne=0; long[] ar=new long[n]; for(int i=0;i<n;i++){ ar[i]=scn.nextLong(); if((ar[i]&1)==0) ne++; else no++; } int ct=0; if(ne==no+1){ long ans=0; for(int i=0;i<n;i++){ if((ar[i]&1)==0) {ans+=Math.abs(i-ct); ct+=2;} } w.println(ans); }else if(ne==no){ long eans=0; for(int i=0;i<n;i++){ if((ar[i]&1)==0) {eans+=Math.abs(i-ct); ct+=2;} } ct=0; long oans=0; for(int i=0;i<n;i++){ if((ar[i]&1)!=0) {oans+=Math.abs(i-ct); ct+=2;} } w.println(Math.min(eans, oans)); }else if(no==ne+1){ long ans=0; for(int i=0;i<n;i++){ if((ar[i]&1)!=0) {ans+=Math.abs(i-ct); ct+=2;} } w.println(ans); }else w.println(-1); } } void run() { try { long ct = System.currentTimeMillis(); scn = new FastScanner(new File("input.txt")); w = new PrintWriter(new File("output.txt")); fs=new PrintStream("error.txt"); System.setErr(fs); LOCAL=true; solve(); w.close(); System.err.println(System.currentTimeMillis() - ct); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { scn = new FastScanner(System.in); w = new PrintWriter(System.out); LOCAL=false; solve(); w.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new _1556b().runIO(); } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
591a8b1861e58aa46e5f1e21047ea43a
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args)throws IOException { FastScanner scan = new FastScanner(); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); int t = scan.nextInt(); for(int tt = 0;tt<t;tt++) { int n = scan.nextInt(); int arr[] = new int[n]; int zerocount = 0, onecount = 0; for(int i = 0;i<n;i++) { arr[i] = scan.nextInt()%2; if(arr[i]%2==0) zerocount++; else onecount++; } if(Math.abs(zerocount - onecount) > 1) { output.write("-1\n"); continue; } int arr2[] = arr.clone(); int count1 = 0, count2 = 0; int i = 0, j = 1; //0 1 0 1 .. while(i<n && j<n) { if(i%2 == arr[i]) { i++; j++; } else if(arr[j]!=arr[i]){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; count1+= (j-i); i++; } else { j++; } } i = 0; j= 1; arr = arr2.clone(); while(i<n && j<n) { if(i%2 != arr[i]) { i++; j++; } else if(arr[j]!=arr[i]){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; count2+= (j-i); i++; } else { j++; } } if(zerocount == onecount) output.write(Math.min(count1, count2) + "\n"); else if(zerocount > onecount) output.write(count1 + "\n"); else output.write(count2 + "\n"); } output.flush(); } public static int[] sort(int arr[]) { List<Integer> list = new ArrayList<>(); for(int i:arr) list.add(i); Collections.sort(list); for(int i = 0;i<list.size();i++) { arr[i] = list.get(i); } return arr; } public static int gcd(int a, int b) { if(a == 0) return b; return gcd(b%a, a); } public static void printArray(int arr[]) { for(int i:arr) System.out.print(i+" "); System.out.println(); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
ed65da4b5a1fb57065137f8a1fe71a8c
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args)throws IOException { FastScanner scan = new FastScanner(); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); int t = scan.nextInt(); for(int tt = 0;tt<t;tt++) { int n = scan.nextInt(); int arr[] = new int[n]; int zerocount = 0, onecount = 0; for(int i = 0;i<n;i++) { arr[i] = scan.nextInt()%2; if(arr[i]%2==0) zerocount++; else onecount++; } if(Math.abs(zerocount - onecount) > 1) { output.write("-1\n"); continue; } int arr2[] = arr.clone(); int count1 = 0, count2 = 0; int i = 0, j = 1; //0 1 0 1 .. while(i<n && j<n) { if(i%2 == arr[i]) { i++; j++; } else if(arr[j]!=arr[i]){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; count1+= (j-i); i++; } else { j++; } } i = 0; j= 1; arr = arr2.clone(); while(i<n && j<n) { if(i%2 != arr[i]) { i++; j++; } else if(arr[j]!=arr[i]){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; count2+= (j-i); i++; } else { j++; } } if(zerocount == onecount) output.write(Math.min(count1, count2) + "\n"); else if(zerocount > onecount) output.write(count1 + "\n"); else output.write(count2 + "\n"); } output.flush(); } public static int[] sort(int arr[]) { List<Integer> list = new ArrayList<>(); for(int i:arr) list.add(i); Collections.sort(list); for(int i = 0;i<list.size();i++) { arr[i] = list.get(i); } return arr; } public static int gcd(int a, int b) { if(a == 0) return b; return gcd(b%a, a); } public static void printArray(int arr[]) { for(int i:arr) System.out.print(i+" "); System.out.println(); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output
PASSED
2dbd9e07aeb61410cdff356b743d21ec
train_107.jsonl
1630247700
William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
256 megabytes
import java.util.*; public class Ques2 { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while(t-->0) { int n = scn.nextInt(); int arr[] = new int[n]; for(int i =0; i<n; i++) { arr[i] =scn.nextInt(); } int even = 0; int odd = 0; StringBuilder s = new StringBuilder(); for(int i =0; i<n; i++) { if(arr[i]%2==0) { s.append('1'); even++; }else { s.append('0'); odd++; } } int diff = Math.abs(even-odd); if(n == 1) { System.out.println(0); }else if(diff>1) { System.out.println(-1); }else { StringBuilder s1 = new StringBuilder(); StringBuilder s2 = new StringBuilder(); ArrayList<Integer> o = new ArrayList<>(); ArrayList<Integer> e = new ArrayList<>(); if(even==odd) { for(int i =0; i<n; i++) { if(i%2==0) { s1.append(1); }else { s1.append(0); } } for(int i =0; i<n; i++) { if(i%2==0) { s2.append(0); }else { s2.append(1); } } int a1= check(o, e, s, s1); int a2 = check(o, e, s, s2); System.out.println(Math.min(a1, a2)); }else if(even>odd) { for(int i =0; i<n; i++) { if(i%2==0) { s1.append(1); }else { s1.append(0); } } int a1= check(o, e, s, s1); System.out.println(a1); }else if(odd>even) { for(int i =0; i<n; i++) { if(i%2==0) { s2.append(0); }else { s2.append(1); } } int a2 = check(o, e, s, s2); System.out.println(a2); } } } } public static int check(ArrayList<Integer> o,ArrayList<Integer> e, StringBuilder s , StringBuilder s1 ) { for(int i =0; i<s.length(); i++) { if(s.charAt(i)!=s1.charAt(i)) { if(s1.charAt(i)=='0') { o.add(i); }else { e.add(i); } } } Collections.sort(o); Collections.sort(e); int ans =0; for(int i =0; i<o.size(); i++) { ans += Math.abs(o.get(i)-e.get(i)); } o.clear(); e.clear(); return ans; } }
Java
["5\n3\n6 6 1\n1\n9\n6\n1 1 1 2 2 2\n2\n8 6\n6\n6 2 3 4 5 1"]
1 second
["1\n0\n3\n-1\n2"]
NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$ swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$ swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$ swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$
Java 8
standard input
[ "implementation" ]
be51a3e4038bd9a3f6d4993b75a20d1c
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,300
For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.
standard output