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
64f53f5f99e06fe2b01a17be27146b25
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.io.*; import java.util.*; public class Main { private static PrintWriter out = new PrintWriter(System.out); private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer st; public static void main(String[] args) throws IOException { st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); ArrayList<Integer> a = new ArrayList<>(n); st = new StringTokenizer(in.readLine()); for (int i = 0; i < n; i++) { a.add(Integer.parseInt(st.nextToken())); } int minE = Collections.min(a); long res = 0; for (int i : a) { i -= minE; if (i % k != 0) { res = -1; break; } res += i / k; } out.println(res); out.flush(); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 109)Β β€” the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
standard output
PASSED
02fd4b8b22d364437ccbab30daba2887
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class A793 { private static long mod = 1000000007; public static void main(String[] args) { InputReader in=new InputReader(System.in); PrintWriter pw=new PrintWriter(System.out); int n=in.nextInt(); int k=in.nextInt(); int[] a=new int[n]; long sum=0; long min=Integer.MAX_VALUE; for(int i=0;i<n;i++) { a[i]=in.nextInt(); if(a[i]<min) min=a[i]; } boolean flag=true; for(int i=0;i<n;i++) { if((a[i]-min)%k!=0) { pw.println(-1); flag=false; break; } else sum+=(a[i]-min); } if(flag==true) pw.println(sum/k); pw.flush(); pw.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static ArrayList<Integer> primeFactorization(int n) { ArrayList<Integer> a =new ArrayList<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } 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 LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static int modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } 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; } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 109)Β β€” the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
standard output
PASSED
b3647c9d10a9ef28fd5db0ab8b7f185a
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.Scanner; import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Check2 implements Runnable{ static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static LinkedList <Integer> adj[]; static int co=0,f=0; static void Check2(int n){ adj=new LinkedList[n+1]; for(int i=0;i<=n;i++){ adj[i]=new LinkedList(); } } static void add(int i,int j){ adj[i].add(j); adj[j].add(i); } public static void main(String[] args) throws Exception { new Thread(null, new Check2(), "Check2", 1<<26).start();// to increse stack size in java } public void run(){ /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ //Scanner in=new Scanner(System.in); InputReader in=new InputReader(System.in); PrintWriter w=new PrintWriter(System.out); int n=in.nextInt(); long k=in.nextLong(); long s=0; long min=Long.MAX_VALUE; long a[]=new long[n+1]; int flag=0; int flag2=0; for(int i=1;i<=n;i++) { a[i]=in.nextInt(); } Arrays.sort(a); for(int i=1;i<n;i++) { if((a[i+1]-a[i])%k!=0) { flag=1; } } if(flag==1)w.println(-1); else{ min=a[1]; long ans=0; for(int i=1;i<=n;i++){ if(a[i]!=min){ ans=ans+(a[i]-min)/k; } } w.println(ans); } w.close(); } long gcd(long a,long b){ if(b==0){ return a; } else return gcd(b,a%b); } static void dfs(int i,int v[]){ if(v[i]==1){ return ; } else{ v[i]=1; Iterator <Integer>p=adj[i].iterator(); while(p.hasNext()){ Integer ne=p.next(); dfs(ne,v); } } } static class node{ int y; int val; node(int a,int b){ y=a; val=b; } } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 109)Β β€” the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
standard output
PASSED
9c16a5ead679ab05a428250a879df666
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.io.IOException; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; import java.util.concurrent.ThreadLocalRandom; public class A { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long k = sc.nextLong(); long a[] = new long[(int) n]; for (int i = 0; i < a.length; i++) { a[i] = sc.nextLong(); } boolean flag = true; long count = 0; shuffleArray(a); Arrays.sort(a); for (int i = 0; i < a.length - 1; i++) { if ((a[i + 1] - a[i]) % k != 0) { flag = false; break; } else { count += (a[i + 1] - a[0]) / k; } } if (flag) System.out.println(count); else System.out.println(-1); } static void shuffleArray(long[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); int a = (int) ar[index]; ar[index] = ar[i]; ar[i] = a; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream System) { br = new BufferedReader(new InputStreamReader(System)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() { for (long i = 0; i < 3e9; i++) ; } } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 109)Β β€” the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
standard output
PASSED
17e410c001ed9d05e11d624d759b217d
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.Arrays; import java.util.Collections; import java.util.Scanner; import java.util.Vector; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Vector<Integer> tab = new Vector(); int j = 1, n = sc.nextInt(); int k = sc.nextInt(); long count = 0; sc.nextLine(); for (int i = 0; i < n ; i++) { tab.add(sc.nextInt()); } Collections.sort(tab); int curr = tab.get(0); for (; j < n; j++) { if(((tab.get(j) - curr) % k) != 0) { System.out.println(-1); break; } count += (tab.get(j) - curr) / k; } if(j == n) { System.out.println(count); } } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 109)Β β€” the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
standard output
PASSED
1486a3733ec84c2d7a4abeee75fde4ec
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.Scanner; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { try { Scanner sc = new Scanner(System.in); int n,k,i,flag; long min,s; n=sc.nextInt(); k=sc.nextInt(); long a [] =new long[n]; a[0]=sc.nextInt(); min=a[0]; for(i=1;i<n;i++) {a[i]=sc.nextInt(); if(a[i]<min) min=a[i]; } flag=1; s=0; for(i=0;i<n;i++) { if((a[i]-min)%k !=0) { flag=0; break; } s=s+(a[i]-min)/k; } if(flag==1) System.out.println(s); else System.out.println("-1"); } catch(Exception e) { } } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 109)Β β€” the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
standard output
PASSED
6099732aeba60e4fa91c8a516f54effc
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.Scanner; /** * * @author οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ */ public class JavaClass1 { public static void main(String[] args) { Scanner in=new Scanner(System.in); int a=in.nextInt(); int k=in.nextInt(); long[] t=new long[a]; boolean possible=true; for(int i=0;i<a;i++) {t[i]=in.nextLong();} long min=t[0]; for(int i=0;i<a;i++) {if (t[i]<min) min=t[i];} long e=0; for(int i=0;i<a;i++) {if ((t[i]-min)%k==0) e+=(t[i]-min)/k; else {possible=false;break;} } if (possible) System.out.println(e); else System.out.println(-1); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 109)Β β€” the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
standard output
PASSED
70c3dc7fab0c9c1bcd753ab5f316361f
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.lang.reflect.Array; import java.util.*; /** * Created by Debabrata on 4/10/2017. */ public class demo7 { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int N=scan.nextInt(); int k=scan.nextInt(); int array[]=new int[N]; int a; int min=Integer.MAX_VALUE; long flag=0,sum=0; for(int i=0;i<N;i++) { a=scan.nextInt(); array[i]=a; if(a<min) min=a; if(a%k!=array[0]%k) flag=1; } if(flag==1) System.out.println(-1); else if(flag==0){ for(int i=0;i<N;i++) { sum+=(array[i]-min); } System.out.println(sum/k); } } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 109)Β β€” the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
standard output
PASSED
0246371a20ee41b98dfcd62367ce1d22
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.*; import java.math.BigInteger; public class A { static Scanner in = new Scanner(System.in); static BigInteger n,k; static ArrayList<BigInteger> prices = new ArrayList<>(),max=new ArrayList<>(); static BigInteger x; public static void main(String[] args) { n = new BigInteger(in.next()); k = new BigInteger(in.next()); BigInteger i = new BigInteger("0"); while(i.compareTo(n)==-1){ prices.add(new BigInteger(in.next())); i=i.add(BigInteger.ONE); } Collections.sort(prices); BigInteger min=prices.get(0),p; x=new BigInteger("0"); for(int j=1;j<prices.size();j++){ p=prices.get(j); if((p.subtract(min)).mod(k).compareTo(BigInteger.ZERO)!=0){ System.out.println("-1"); return; } x=x.add(p.subtract(min).divide(k)); } System.out.println(x); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 109)Β β€” the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
standard output
PASSED
5f38163d3d710649686846fe8c669fda
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
// CodeForces Round #815 A TODO import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class OlegShares { int n; int k; int []a; long nSec; // number unique private void readData(BufferedReader bin) throws IOException { String s = bin.readLine(); String[] ss = s.split(" "); // read a b n = Integer.parseInt(ss[0]); k = Integer.parseInt(ss[1]); // read a a = new int[n]; s = bin.readLine(); ss = s.split(" "); for (int i=0; i<n; i++) { a[i] = Integer.parseInt(ss[i]); } } void printRes() { System.out.println(nSec); } private void calculate() { // find smallest price int sml = 1000111222; for (int i=0; i < n; i++){ if (a[i] < sml) { sml = a[i]; } } // count seconds for (int i=0; i < n; i++){ // how much we want to change price int d = (a[i] - sml); if (d % k == 0){ nSec += d/k; } else { nSec = -1; return; } } } public static void main(String[] args) throws IOException { // BufferedReader bin = new BufferedReader(new FileReader("cactus.in")); BufferedReader bin = new BufferedReader(new InputStreamReader(System.in)); OlegShares l = new OlegShares(); l.readData(bin); l.calculate(); l.printRes(); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 109)Β β€” the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
standard output
PASSED
52382f7bae74285ba2d345cd05559e1e
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
// CodeForces Round #580 C done, no problem. import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; public class OlegAndShares { int n,k; // number vertices, max cats long []a; long numSec; private void readData(BufferedReader bin) throws IOException { String s = bin.readLine(); String []ss = s.split(" "); n = Integer.parseInt(ss[0]); k = Integer.parseInt(ss[1]); // reading a a = new long[n]; s = bin.readLine(); ss = s.split(" "); for (int i=0; i<n; i++) { a[i] = Integer.parseInt(ss[i]); } } void printRes() { System.out.println(numSec); } private void calculate() { numSec = 0; long minA = 2000111333; for (int i = 0; i < n; i++) { if (a[i]<minA) { minA = a[i]; } } for (int i = 0; i < n; i++) { long d = a[i]-minA; if (d % k != 0) { numSec = -1; return; } numSec += d/k; } } public static void main(String[] args) throws IOException { // BufferedReader bin = new BufferedReader(new FileReader("cactus.in")); BufferedReader bin = new BufferedReader( new InputStreamReader(System.in)); OlegAndShares l = new OlegAndShares(); l.readData(bin); l.calculate(); l.printRes(); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 109)Β β€” the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
standard output
PASSED
1b5ed97ea61d4f44cf649d5f8d856683
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.io.BufferedReader; import java.io.File; 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.HashSet; import java.util.Scanner; import java.util.StringTokenizer; public class A{ public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n= in.nextInt(); int k= in.nextInt(); Integer [] a= new Integer[n]; for (int i = 0; i < a.length; i++) { a[i]= in.nextInt(); } Arrays.sort(a); int min = a[0]; long res=0; for (int i = 1; i < a.length; i++) { if((a[i]-min)%k!=0){ System.out.println(-1); return; } res+= a[i]-min; } res/=k; System.out.println(res); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } public String next() throws IOException { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); return next(); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 109)Β β€” the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
standard output
PASSED
11650f4cbc2931c5f6b6bf398bf99c6d
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
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.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class B { public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out,true); int n=sc.nextInt(); TreeSet<Integer> [] bids=new TreeSet[n]; for(int i=0;i<n;i++) bids[i]=new TreeSet<Integer>(); int [] max=new int [n]; for(int i=0;i<n;i++){ int a=sc.nextInt()-1; int b=sc.nextInt(); bids[a].add(b); max[a]=b; } Comparator<Integer> com=new Comparator<Integer>() { public int compare(Integer a, Integer b) { return max[a]-max[b]; } }; TreeSet<Integer> auction=new TreeSet<Integer>(com); for(int i=0;i<n;i++){ if(max[i]>0) auction.add(i); } int q=sc.nextInt(); while(q-->0){ int c=sc.nextInt(); int [] tmp=new int [c]; for(int i=0;i<c;i++) tmp[i]=sc.nextInt()-1; for(int i=0;i<c;i++) auction.remove(tmp[i]); if(auction.isEmpty()){ pw.println("0 0"); }else{ int first=auction.pollLast(); if(auction.isEmpty()) pw.println((first+1)+" "+bids[first].first()); else{ int second=auction.last(); pw.println((first+1)+" "+bids[first].higher(max[second])); } auction.add(first); } for(int i=0;i<c;i++){ if(max[tmp[i]]>0) auction.add(tmp[i]); } } pw.flush(); pw.close(); } 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
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
23d869fe88e119e59b3ae30e3ce0a253
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Solution { private static class Player { Player(int n, int first) { this.n = n; bids = new ArrayList<>(); bids.add(first); } int n; List<Integer> bids; int last() { return bids.get(bids.size() - 1); } int getMax() { return -last(); } public String toString() { return "" + n; } } public static void main(String[] args) { MyScanner in = new MyScanner(); int n = in.nextInt(); Map<Integer, Player> playerMap = new HashMap<>(); for (int i = 0; i < n; i++) { int number = in.nextInt(); int bid = in.nextInt(); if (!playerMap.containsKey(number)) { Player p = new Player(number, bid); playerMap.put(number, p); } else { playerMap.get(number).bids.add(bid); } } TreeSet<Player> players = new TreeSet<>(Comparator.comparingInt(Player::getMax)); for (Player p: playerMap.values()) { players.add(p); } int q = in.nextInt(); List<String> answer = new ArrayList<>(q); for (int i = 0; i < q; i++) { int m = in.nextInt(); List<Player> excluded = new ArrayList<>(m); for (int j = 0; j < m; j++) { int number = in.nextInt(); if (playerMap.containsKey(number)) { Player player = playerMap.get(number); excluded.add(player); players.remove(player); } } if (players.isEmpty()) answer.add("0 0"); else if (players.size() == 1) answer.add("" + players.first().n + " " + players.first().bids.get(0)); else { Player first = players.first(); int shouldBeMore = players.higher(first).last(); int right = first.bids.size(); int left = -1; while (right - left > 1) { int middle = (right + left) / 2; if (first.bids.get(middle) < shouldBeMore) left = middle; else right = middle; } answer.add("" + first.n + " " + first.bids.get(right)); } players.addAll(excluded); } System.out.println(String.join("\n", answer)); } 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
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
18a6d876b431fcce1d1855317b4660b3
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.*; import java.util.*; public class Mainn { FastReader scn; PrintWriter out; String INPUT = ""; class pair implements Comparable<pair> { int bid = 0, ind = 0; TreeSet<Integer> list = new TreeSet<>(); public int compareTo(pair o) { return this.bid - o.bid; } // public String toString() { // return ind + " " + bid + " " + list.toString(); // } } void solve() { int n = scn.nextInt(); TreeSet<pair> set = new TreeSet<>(); pair[] arr = new pair[n + 1]; int[] map = new int[n + 1]; for (int i = 0; i < n; i++) { int x = scn.nextInt(); if (arr[x] == null) { arr[x] = new pair(); } int y = scn.nextInt(); arr[x].ind = x; arr[x].bid = Math.max(arr[x].bid, y); arr[x].list.add(y); map[x] = Math.max(map[x], y); } for (int i = 1; i <= n; i++) { if (arr[i] != null) { set.add(arr[i]); } } int q = scn.nextInt(); while (q-- > 0) { int m = scn.nextInt(); pair[] rem = new pair[m]; for (int i = 0; i < m; i++) { int k = scn.nextInt(); if (map[k] == 0) { continue; } pair p = new pair(); p.bid = map[k]; rem[i] = set.ceiling(p); set.remove(rem[i]); } if (set.size() == 0) { out.println(0 + " " + 0); } else if (set.size() == 1) { out.println(set.first().ind + " " + set.first().list.first()); } else { pair p = set.pollLast(); int max = set.last().bid; set.add(p); out.println(set.last().ind + " " + set.last().list.ceiling(max)); } for (int i = 0; i < m; i++) { if (rem[i] != null) { set.add(rem[i]); } } } } void run() throws Exception { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) throws Exception { new Mainn().run(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] 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; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
2952f4e12abb8e7431ce1f15228db3ff
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.*; import java.util.stream.IntStream; public class D { public static void main(String[] args) { // Scanner sc = new Scanner(System.in); FastScanner sc = new FastScanner(); int n = sc.nextInt(); // TreeMap<Integer, Integer> bids = new TreeMap<>(); TreeSet<Integer>[] bids = new TreeSet[n + 1]; for (int i = 0; i < n + 1; i++) { bids[i] = new TreeSet<>(); } int[] highest = new int[n + 1]; for (int i = 0; i < n; i++) { int bidder = sc.nextInt(); int bidAmount = sc.nextInt(); highest[bidder] = bidAmount; bids[bidder].add(bidAmount); } Integer[] lul = new Integer[n + 1]; for (int i = 0; i < lul.length; i++) { lul[i] = i; } Arrays.sort(lul, new Comparator<Integer>(){ @Override public int compare(Integer a, Integer b) { return Integer.compare(highest[a], highest[b]); } }); StringBuilder sb = new StringBuilder(); int numQueries = sc.nextInt(); for (int q = 0; q < numQueries; q++) { int k = sc.nextInt(); int winnerIdx = 0; int winningBid = 0; Set<Integer> excluded = new HashSet<>(); for (int i = 0; i < k; i++) { int toExclude = sc.nextInt(); if (highest[toExclude] > 0) { excluded.add(toExclude); } } // O(k) int secondPlaceIdx = 0; for (int i = n; i > 0; i--) { int bidder = lul[i]; if (highest[bidder] == 0) { break; } if (!excluded.contains(bidder)) { if (winnerIdx == 0) { winnerIdx = bidder; } else { secondPlaceIdx = bidder; break; } } } int needToBeat = highest[secondPlaceIdx]; if (winnerIdx > 0) { winningBid = bids[winnerIdx].tailSet(needToBeat, false).first(); } sb.append(winnerIdx).append(' ').append(winningBid); sb.append('\n'); } System.out.print(sb); } static void shuffle(int[] arr) { Random rng = new Random(); int length = arr.length; for (int idx = 0; idx < arr.length; idx++) { int toSwap = idx + rng.nextInt(length-idx); int tmp = arr[idx]; arr[idx] = arr[toSwap]; arr[toSwap] = tmp; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
62539602602cf7828b68f6ef23536517
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class Main { static class Man implements Comparable<Man>{ int idx ; TreeSet<Integer> bids; Man (int i , TreeSet<Integer> b) { idx = i; bids = b; } @Override public int compareTo(Man man) { int f = man.bids.last() , s = bids.last(); return f == s? (idx - man.idx) : f - s; } @Override public boolean equals(Object o) { return (new Man(idx , bids)).compareTo((Man)(o)) == 0; } } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); StringBuilder sb = new StringBuilder(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); TreeSet<Integer> treeSets [] = new TreeSet[n]; for (int i = 0 ; i < n ; ++ i) treeSets[i] = new TreeSet<>(); for (int i = 0 ; i < n ; ++ i) treeSets[sc.nextInt() - 1].add(sc.nextInt()); int max [] = new int[n]; for (int i = 0 ; i < n ; ++ i) if (!treeSets[i].isEmpty()) max[i] = treeSets[i].last(); TreeSet<Integer> men = new TreeSet<>(new Comparator<Integer>() { @Override public int compare(Integer t1, Integer t2) { return max[t2] - max[t1]; } }); for (int i = 0 ; i < n ; ++ i) if (!treeSets[i].isEmpty()) men.add(i); int q = sc.nextInt(); while (q -- > 0) { int k = sc.nextInt(); int remove [] = new int[k]; for (int i = 0 ; i < k ; ++ i) { remove[i] = sc.nextInt() - 1; if (!treeSets[remove[i]].isEmpty()) men.remove(remove[i]); } if (men.isEmpty()) {out.println("0 0");} else { int winner = men.first(); men.remove(men.first()); if (men.isEmpty()) {out.printf("%d %d\n" , winner + 1 , treeSets[winner].first());} else { int beforeWinner = men.first(); out.println((winner + 1) + " " + treeSets[winner].higher(max[beforeWinner])); } men.add(winner); } for (int i = 0 ; i < k ; ++ i) if (!treeSets[remove[i]].isEmpty()) men.add(remove[i]); } out.flush(); out.close(); } 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
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
bafe26a3fb87c05fbbf93a7f8835a31c
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.math.*; import java.io.*; import java.util.*; public class C749D { public static long[] fact, factInv; public static int N,M,K; public static long MOD = 1000000007; public static void main(String[] args) throws IOException { InputReader in = new InputReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); N = in.nextInt(); Pair[] ar = new Pair[N]; for(int i=0;i<N;i++) ar[i]=new Pair(0, i+1); for(int i=0;i<N;i++){ int[] car = in.nextIntAr(); car[0]--; ar[car[0]].set.add(car[1]); ar[car[0]].a = Math.max(ar[car[0]].a, car[1]); } Arrays.sort(ar); int Q = in.nextInt(); for(int i = 0;i<Q;i++){ int[] car=in.nextIntAr(); HashSet<Integer> set = new HashSet<Integer>(); for(int j = 1; j <= car[0]; j++) set.add(car[j]); int first = -1; int second = -1; boolean maxFound = false; for(int j=0;j<N;j++) { if(!set.contains(ar[j].b)) { if(!maxFound) { first = j; maxFound = true; } else { second = j; break; } } } if(first == -1) out.println("0 0"); else if(ar[first].a == 0) out.println("0 0"); else if(second == -1 || ar[second].a == 0) out.println(ar[first].b + " " + ar[first].set.first()); else out.println(ar[first].b + " " + ar[first].set.higher(ar[second].a)); } out.close(); } public static void setUpChoose(int t) { fact = new long[t+1]; factInv = new long[t+1]; fact[0] = 1; factInv[0] = 1; for(int x = 1;x <= t; x++) { fact[x] = (x * fact[x-1]) % MOD; factInv[x] = pow (fact[x],MOD-2); } } public static long choose(int x,int y) { if(y > x) return 0; long a = fact[x]; long b = factInv[y]; long c = factInv[x-y]; a = (a * b) % MOD; a = (a * c) % MOD; return a; } public static long pow(long a,long b) { if(b == 1) return a; long c = b / 2; long temp = pow(a,c) % MOD; temp = (temp * temp) % MOD; if(b % 2 == 1) temp = (temp * a) % MOD; return temp % MOD; } public static boolean isPrime(long x) { for(int y = 2; y <= Math.sqrt(x); y++) if(x % y == 0) return false; return true; } } class InputReader { private BufferedReader br; public InputReader(InputStreamReader in) { br = new BufferedReader(in); } public int nextInt() { try { return Integer.parseInt(br.readLine()); } catch (IOException e) { throw new InputMismatchException(); } } public int[] nextIntAr() { try { String[] s = br.readLine().split(" "); int[] ret = new int[s.length]; for(int x = 0; x < s.length; x++) ret[x] = Integer.parseInt(s[x]); return ret; } catch (IOException e) { throw new InputMismatchException(); } } public long nextLong() { try { return Long.parseLong(br.readLine()); } catch (IOException e) { throw new InputMismatchException(); } } public long[] nextLongAr() { try { String[] s = br.readLine().split(" "); long[] ret = new long[s.length]; for(int x = 0;x<s.length;x++) ret[x] = Long.parseLong(s[x]); return ret; } catch (IOException e) { throw new InputMismatchException(); } } public String[] nextStringAr() { try { return br.readLine().split(" "); } catch (IOException e) { throw new InputMismatchException(); } } public String nextString() { try { return br.readLine(); } catch (IOException e) { throw new InputMismatchException(); } } } class Pair implements Comparable<Pair> { Integer a; Integer b; TreeSet<Integer> set; public Pair(int ma, int mb) { a = ma; b = mb; set = new TreeSet<Integer>(); } public int compareTo(Pair o) { if(a == o.a) return 0; return a < o.a ? 1 : -1; } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
3a650d5cabbf80ab8f5bbf96d35b5631
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.Comparator; import java.util.TreeSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.readInt(); TreeSet<Integer>[] men = new TreeSet[n + 1]; for (int i = 1; i <= n; i++) men[i] = new TreeSet<>(); for (int i = 0; i < n; i++) { men[in.readInt()].add(in.readInt()); } int[] max = new int[n + 1]; for (int i = 1; i <= n; i++) { if (men[i].size() > 0) max[i] = men[i].last(); } TreeSet<Integer> set = new TreeSet<>(new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return max[o2] - max[o1]; } }); for (int i = 1; i <= n; i++) { if (men[i].size() > 0) set.add(i); } int q = in.readInt(); while (q-- > 0) { int k = in.readInt(); int[] left = in.readIntArray(k); for (int i : left) { if (men[i].size() > 0) set.remove(i); } if (set.size() == 0) { out.println("0 0"); } else { int ans = set.first(); if (set.size() == 1) { out.println(ans + " " + men[ans].first()); } else { int x = set.pollFirst(); int last = set.first(); out.println(ans + " " + men[ans].higher(men[last].last())); set.add(x); } } for (int i : left) { if (men[i].size() > 0) set.add(i); } } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] readIntArray(int size) { int[] ans = new int[size]; for (int i = 0; i < size; i++) ans[i] = readInt(); return ans; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
a8a86057ed277b5c2e1db98b74dc1273
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
//JDope import java.util.*; import java.io.*; import java.math.*; public class D{ public static void main(String[] omkar) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); StringBuilder sb = new StringBuilder(); int n = Integer.parseInt(st.nextToken()); TreeSet<Integer>[] sets = new TreeSet[n]; for(int i = 0; i < n; i++) { sets[i] = new TreeSet<Integer>(); } int x, y, max1, max2, ind, p1, p2; Set<Integer> people = new HashSet<Integer>(); for(int i = 0; i < n; i++) { st = new StringTokenizer(in.readLine()); x = Integer.parseInt(st.nextToken()); y = Integer.parseInt(st.nextToken()); people.add(x-1); sets[x-1].add(y); } Pair[] pairs = new Pair[people.size()]; int count = 0; for(int i = 0; i < n; i++) { if(people.contains(i)) { pairs[count] = new Pair(sets[i].last(), i); count++; } } Arrays.sort(pairs); st = new StringTokenizer(in.readLine()); int q = Integer.parseInt(st.nextToken()); int k; Set set; for(int j = 0; j < q; j++) { set = new HashSet<Integer>(); st = new StringTokenizer(in.readLine()); k = Integer.parseInt(st.nextToken()); for(int i = 0; i < k; i++) { x = Integer.parseInt(st.nextToken())-1; if(people.contains(x)) { set.add(x); } } if(set.size() == people.size()) { sb.append("0 0\n"); } else { max1 = -1; max2 = -1; p1 = -1; p2 = -1; ind = pairs.length-1; while(max2 == -1 && ind >= 0) { if(!set.contains(pairs[ind].b)) { if(max1 == -1) { max1 = pairs[ind].b; p1 = pairs[ind].a; } else if(max2 == -1) { max2 = pairs[ind].b; p2 = pairs[ind].a; } } ind--; } if(max2 == -1) { sb.append((max1+1) + " " + sets[max1].first() + "\n"); } else { sb.append((max1+1) + " " + sets[max1].ceiling(p2) + "\n"); } } } System.out.println(sb); } public static int[] readArr(int N, BufferedReader in, StringTokenizer st) throws Exception { int[] arr = new int[N]; st = new StringTokenizer(in.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); return arr; } static class Pair implements Comparable<Pair> { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Pair other) { if (a != other.a) { return a - other.a; } else { return b - other.b; }}} }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
13dcc890e21dc8f8a4d9fedaba2734ec
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import static java.lang.Math.*; public class D implements Runnable { public static void main(String[] args) { new Thread(null, new D(), "", 1 << 28).start(); } public void run() { Scanner sc = new Scanner(); int n = sc.nextInt(); TreeSet<Bid>[] bidsOfUser = new TreeSet[n]; for (int i = 0; i < n; i++) { bidsOfUser[i] = new TreeSet<Bid>((u, v) -> u.bid - v.bid); } for (int i = 0; i < n; i++) { int user = sc.nextInt() - 1; int bid = sc.nextInt(); bidsOfUser[user].add(new Bid(user, bid)); } PriorityQueue<Bid> max = new PriorityQueue<>((u, v) -> v.bid - u.bid); for (TreeSet<Bid> t : bidsOfUser) { if (!t.isEmpty()) { max.offer(t.last()); } } StringBuilder res = new StringBuilder(); int q = sc.nextInt(); while (q-- > 0) { int k = sc.nextInt(); HashSet<Integer> idsToRemove = new HashSet<>(); for (int i = 0; i < k; i++) { idsToRemove.add(sc.nextInt() - 1); } ArrayList<Bid> reserve = new ArrayList<>(); while (!max.isEmpty() && idsToRemove.contains(max.peek().id)) { reserve.add(max.poll()); } if (max.isEmpty()) { res.append("0 0\n"); } else { Bid winner = max.poll(); reserve.add(winner); while (!max.isEmpty() && idsToRemove.contains(max.peek().id)) { reserve.add(max.poll()); } Bid winningBid; if (max.isEmpty()) { winningBid = bidsOfUser[winner.id].ceiling(new Bid(0, 0)); } else { Bid runnerUp = max.poll(); reserve.add(runnerUp); winningBid = bidsOfUser[winner.id].ceiling(runnerUp); } res.append(winningBid.id + 1).append(" ").append(winningBid.bid) .append("\n"); } max.addAll(reserve); } System.out.println(res); } class Bid { final int id, bid; Bid(int i, int b) { id = i; bid = b; } } class Scanner { BufferedReader r; StringTokenizer t; Scanner() { r = new BufferedReader(new InputStreamReader(System.in), 1 << 15); t = null; } String next() { while (t == null || !t.hasMoreTokens()) { try { t = new StringTokenizer(r.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return t.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } BigInteger nextBigInteger() { return new BigInteger(next()); } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
6d1ceab2b166fd998906a58de4bcea32
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import static java.lang.Math.*; public class D implements Runnable { public static void main(String[] args) { new Thread(null, new D(), "", 1 << 28).start(); } public void run() { Scanner sc = new Scanner(); int n = sc.nextInt(); TreeSet<Bid>[] bidsOfUser = new TreeSet[n]; for (int i = 0; i < n; i++) { bidsOfUser[i] = new TreeSet<Bid>((u, v) -> u.bid - v.bid); } for (int i = 0; i < n; i++) { int user = sc.nextInt() - 1; int bid = sc.nextInt(); bidsOfUser[user].add(new Bid(user, bid)); } PriorityQueue<Bid> max = new PriorityQueue<>((u, v) -> v.bid - u.bid); for (TreeSet<Bid> t : bidsOfUser) { if (!t.isEmpty()) { max.offer(t.last()); } } StringBuilder res = new StringBuilder(); int q = sc.nextInt(); while (q-- > 0) { int k = sc.nextInt(); HashSet<Integer> idsToRemove = new HashSet<>(); for (int i = 0; i < k; i++) { idsToRemove.add(sc.nextInt() - 1); } ArrayList<Bid> reserve = new ArrayList<>(); while (!max.isEmpty() && idsToRemove.contains(max.peek().id)) { reserve.add(max.poll()); } if (max.isEmpty()) { res.append(String.format("%d %d\n", 0, 0)); } else { Bid winner = max.poll(); reserve.add(winner); while (!max.isEmpty() && idsToRemove.contains(max.peek().id)) { reserve.add(max.poll()); } Bid winningBid; if (max.isEmpty()) { winningBid = bidsOfUser[winner.id].ceiling(new Bid(0, 0)); } else { Bid runnerUp = max.poll(); reserve.add(runnerUp); winningBid = bidsOfUser[winner.id].ceiling(runnerUp); } res.append(String.format("%d %d\n", winningBid.id + 1, winningBid.bid)); } max.addAll(reserve); } System.out.println(res); } class Bid { final int id, bid; Bid(int i, int b) { id = i; bid = b; } } class Scanner { BufferedReader r; StringTokenizer t; Scanner() { r = new BufferedReader(new InputStreamReader(System.in), 1 << 15); t = null; } String next() { while (t == null || !t.hasMoreTokens()) { try { t = new StringTokenizer(r.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return t.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } BigInteger nextBigInteger() { return new BigInteger(next()); } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
aace17b7677e487accc086755b6a28c0
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.util.TreeSet; import java.util.List; import java.util.ArrayList; import java.util.Collections; public class Main{ static int n; static int[] max; public static void main(String[] args){ FastScanner sc = new FastScanner(); n = sc.nextInt(); List< List< Integer > > bids = new ArrayList< >(); for(int i = 0; i < n; i++){ bids.add(new ArrayList< >()); } max = new int[n]; for(int i = 0; i < n; i++){ int a = sc.nextInt() - 1, b = sc.nextInt(); max[a] = Math.max(max[a], b); bids.get(a).add(b); } for(int i = 0; i < n; i++){ Collections.sort(bids.get(i)); } TreeSet< Pair > set = new TreeSet< >(); for(int i = 0; i < n; i++){ if(max[i] != 0){ set.add(new Pair(i, max[i])); } } StringBuilder sb = new StringBuilder(); int q = sc.nextInt(); for(int i = 0; i < q; i++){ int k = sc.nextInt(); int[] l = new int[k]; for(int j = 0; j < k; j++){ l[j] = sc.nextInt() - 1; if(max[l[j]] != 0){ set.remove(new Pair(l[j], max[l[j]])); } } if(!set.isEmpty()){ Pair win = set.last(); Pair sec = set.lower(win); if(sec == null){ if(Collections.binarySearch(bids.get(win.i), win.bid) >= 0){ sb.append((win.i + 1) + " " + bids.get(win.i).get(0)); } else{ sb.append((win.i + 1) + " " + win.bid); } } else{ int j = Collections.binarySearch(bids.get(win.i), sec.bid); j = -j - 1; sb.append((win.i + 1) + " " + bids.get(win.i).get(j)); } sb.append(System.lineSeparator()); } else{ sb.append("0 0" + System.lineSeparator()); } for(int j = 0; j < k; j++){ if(max[l[j]] != 0){ set.add(new Pair(l[j], max[l[j]])); } } } System.out.println(sb); } static class Pair implements Comparable< Pair >{ int i; int bid; Pair(int i, int bid){ this.i = i; this.bid = bid; } @Override public int compareTo(Pair p){ if(bid == p.bid){ return Integer.compare(i, p.i); } return Integer.compare(bid, p.bid); } @Override public boolean equals(Object obj){ if(!(obj instanceof Pair)){ return false; } Pair p = (Pair)obj; return bid == p.bid && i == p.i; } } } class FastScanner { private static final InputStream in = System.in; private static final PrintWriter out = new PrintWriter(System.out); private final byte[] buffer = new byte[2048]; private int p = 0; private int buflen = 0; public FastScanner(){ } private boolean hasNextByte() { if(p < buflen){ return true; } p = 0; try{ buflen = in.read(buffer); }catch (IOException e) { e.printStackTrace(); } if(buflen <= 0){ return false; } return true; } public boolean hasNext() { while(hasNextByte() && !isPrint(buffer[p])){ p++; } return hasNextByte(); } private boolean isPrint(int ch) { if(ch >= '!' && ch <= '~'){ return true; } return false; } private int nextByte() { if(!hasNextByte()){ return -1; } return buffer[p++]; } public String next() { if(!hasNext()){ throw new NoSuchElementException(); } StringBuilder sb = new StringBuilder(); int b = -1; while(isPrint((b = nextByte()))){ sb.appendCodePoint(b); } return sb.toString(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
2863ada5441c0faa61ad8201a2a52890
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); Bidder[] tmpBidders = new Bidder[n + 1]; for (int i = 0; i < n; i++) { int id = in.nextInt(); int bid = in.nextInt(); if (tmpBidders[id] == null) tmpBidders[id] = new Bidder(id); tmpBidders[id].addBid(bid); } List<Bidder> bidders = new ArrayList<>(); for (int i = 0; i <= n; i++) { if (tmpBidders[i] != null) bidders.add(tmpBidders[i]); } Collections.sort(bidders); int q = in.nextInt(); int numberOfBidder = bidders.size(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < q; i++) { int k = in.nextInt(); HashSet<Integer> set = new HashSet<>(); for (int j = 0; j < k; j++) { set.add(in.nextInt()); } int personID = 0; int money = 0; Bidder first = null, second = null; for (int l = 0; l < numberOfBidder; l++) { Bidder curBidder = bidders.get(l); if (!set.contains(curBidder.id)) { if (first == null) first = curBidder; else if (second == null) { second = curBidder; break; } } } if (first == null) { sb.append(personID + " " + money + "\n"); continue; } if (second == null) { sb.append(first.id + " " + first.bids.first() + "\n"); continue; } sb.append(first.id + " " + first.bids.higher(second.bids.last()) + "\n"); } out.println(sb); } class Bidder implements Comparable<Bidder> { int id; TreeSet<Integer> bids; public Bidder(int id) { this.id = id; bids = new TreeSet<>(); } public void addBid(int bid) { bids.add(bid); } public int compareTo(Bidder o) { return o.bids.last() - this.bids.last(); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
8f7f3c5d743924a661357f81c9d231e8
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import sun.reflect.generics.tree.Tree; import java.io.*; import java.text.DecimalFormat; import java.util.*; import java.awt.Point; public class Newbie { static InputReader sc = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { solver s = new solver(); int t = 1; while (t > 0) { s.sol(); t--; } out.close(); } /* static class descend implements Comparator<pair1> { public int compare(pair1 o1, pair1 o2) { if (o1.pop != o2.pop) return (int) (o1.pop - o2.pop); else return o1.in - o2.in; } }*/ static class InputReader { public BufferedReader br; public StringTokenizer token; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream), 32768); token = null; } public String sn() { while (token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } public int ni() { return Integer.parseInt(sn()); } public String snl() throws IOException { return br.readLine(); } public long nlo() { return Long.parseLong(sn()); } public double nd() { return Double.parseDouble(sn()); } public int[] na(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.ni(); return a; } public long[] nal(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = sc.nlo(); return a; } } static class ascend implements Comparator<pair> { public int compare(pair o1, pair o2) { return o2.b - o1.b; } } static class extra { static boolean v[] = new boolean[100001]; static List<Integer> l = new ArrayList<>(); static int t; static void shuffle(int a[]) { for (int i = 0; i < a.length; i++) { int t = (int) Math.random() * a.length; int x = a[t]; a[t] = a[i]; a[i] = x; } } static void shufflel(long a[]) { for (int i = 0; i < a.length; i++) { int t = (int) Math.random() * a.length; long x = a[t]; a[t] = a[i]; a[i] = x; } } static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } static boolean valid(int i, int j, int r, int c) { if (i >= 0 && i < r && j >= 0 && j < c) { // System.out.println(i+" /// "+j); return true; } else { // System.out.println(i+" //f "+j); return false; } } static void seive() { for (int i = 2; i < 101; i++) { if (!v[i]) { t++; l.add(i); for (int j = 2 * i; j < 101; j += i) v[j] = true; } } } static int binary(LinkedList<Integer> a, long val, int n) { int mid = 0, l = 0, r = n - 1, ans = 0; while (l <= r) { mid = (l + r) >> 1; if (a.get(mid) == val) { r = mid - 1; ans = mid; } else if (a.get(mid) > val) r = mid - 1; else { l = mid + 1; ans = l; } } return (ans + 1); } static long fastexpo(long x, long y) { long res = 1; while (y > 0) { if ((y & 1) == 1) { res *= x; } y = y >> 1; x = x * x; } return res; } static long lfastexpo(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) { res = (res * x) % p; } y = y >> 1; x = (x * x) % p; } return res; } /* void dijsktra(int s, List<pair> l[], int n) { PriorityQueue<pair> pq = new PriorityQueue<>(new ascend()); int dist[] = new int[100005]; boolean v[] = new boolean[100005]; for (int i = 1; i <= n; i++) dist[i] = 1000000000; dist[s] = 0; for (int i = 1; i < n; i++) { if (i == s) pq.add(new pair(s, 0)); else pq.add(new pair(i, 1000000000)); } while (!pq.isEmpty()) { pair node = pq.remove(); v[node.a] = true; for (int i = 0; i < l[node.a].size(); i++) { int v1 = l[node.a].get(i).a; int w = l[node.a].get(i).b; if (v[v1]) continue; if ((dist[node.a] + w) < dist[v1]) { dist[v1] = dist[node.a] + w; pq.add(new pair(v1, dist[v1])); } } } }*/ } static class pair { int a; int b; public pair(int a, int b) { this.a = a; this.b = b; } } static class pair1 { pair p; int in; public pair1(pair a, int n) { this.p = a; this.in = n; } } static int inf = 5000013; static class solver { DecimalFormat df = new DecimalFormat("0.00000000"); extra e = new extra(); long mod = (long) (1000000007); void sol() throws IOException { int n = sc.ni(); HashMap<Integer, TreeSet<Integer>> dic = new HashMap<>(); TreeMap<Integer, Integer> map = new TreeMap<>(); for (int i = 0; i < n; i++) { int id = sc.ni(); int val = sc.ni(); dic.putIfAbsent(id, new TreeSet<>()); dic.get(id).add(val); } for (int h : dic.keySet()) { map.put(dic.get(h).last(), h); } int q = sc.ni(); while (q-- > 0) { int k = sc.ni(); int p[] = new int[k]; int i = 0; while (k-- > 0) { p[i] = sc.ni(); if (dic.containsKey(p[i])) map.remove(dic.get(p[i]).last()); i++; } int size = map.size(); if (size == 0) out.println(0 + " " + 0); else if (size == 1) { int val = map.lastKey(); int id = map.get(val); out.println(id + " " + dic.get(id).first()); } else { int id1 = map.get(map.lastKey()); map.remove(map.lastKey()); int val = map.lastKey(); out.println(id1 + " " + dic.get(id1).higher(val)); map.put(dic.get(id1).last(), id1); } for (int j = 0; j < i; j++) { if(dic.containsKey(p[j])) map.put(dic.get(p[j]).last(), p[j]); } } } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
6a052890513bfdabdab993f1da6a66dd
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.util.SortedSet; import java.util.Set; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.TreeMap; import java.util.StringTokenizer; import java.util.Map; import java.util.Map.Entry; import java.io.BufferedReader; import java.util.Collections; import java.util.SortedMap; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Wolfgang Beyer */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int winner; int second; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); SortedMap<Integer, Integer> maxBids = new TreeMap<>(Collections.reverseOrder()); List<SortedSet<Integer>> bids = new ArrayList<>(); for (int i = 0; i < n; i++) { bids.add(new TreeSet<Integer>()); } for (int i = 0; i < n; i++) { int bidder = in.nextInt() - 1; int bid = in.nextInt(); bids.get(bidder).add(bid); } for (int i = 0; i < n; i++) { if (bids.get(i).size() > 0) { maxBids.put(bids.get(i).last(), i); } } int q = in.nextInt(); for (int i = 0; i < q; i++) { //out.println("query " + i); Set<Integer> query = new HashSet<>(); int k = in.nextInt(); /*if (k == n) { out.println("0 0"); continue; }*/ for (int j = 0; j < k; j++) { query.add(in.nextInt() - 1); } //determine winner winner = -1; second = -1; for (Map.Entry<Integer, Integer> entry : maxBids.entrySet()) { if (!query.contains(entry.getValue())) { if (winner == -1) { winner = entry.getValue(); out.print((winner + 1) + " "); } else { int secondBid = entry.getKey(); second = entry.getValue(); SortedSet<Integer> tail = bids.get(winner).tailSet(secondBid); out.println(tail.first()); break; } } } if (winner == -1) { out.println("0 0"); } else if (second == -1) { out.println(bids.get(winner).first()); } //System.out.println(winner + 1); //determine winning bid } } } static class InputReader { private static BufferedReader in; private static StringTokenizer tok; public InputReader(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); } public int nextInt() { return Integer.parseInt(next()); } public String next() { try { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } } catch (IOException ex) { System.err.println("An IOException was caught :" + ex.getMessage()); } return tok.nextToken(); } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
a537d681d9cd8ab59b914748f170a336
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeSet; public class AuctionNlogN { private void solve() throws IOException { int n = readInt(); int[] maxBet = new int[n]; Arrays.fill(maxBet, -1); TreeSet<Integer>[] allBets = new TreeSet[n]; for (int man = 0; man < n; man++) { allBets[man] = new TreeSet<>(); } for (int i = 0; i < n; i++) { int man = readInt() - 1; int bet = readInt(); allBets[man].add(bet); maxBet[man] = bet; } TreeSet<Integer> set = new TreeSet<>((a, b) -> { int res = Integer.compare(maxBet[a], maxBet[b]); if (res == 0) { res = Integer.compare(a, b); } return res; }); for (int man = 0; man < n; man++) { if (allBets[man].size() > 0) { set.add(man); } } int q = readInt(); for (int i = 0; i < q; i++) { int cnt = readInt(); int[] absent = new int[cnt]; for (int j = 0; j < cnt; j++) { absent[j] = readInt() - 1; } for (int man : absent) { set.remove(man); } if (set.isEmpty()) { out.println("0 0"); } else { int winner = set.pollLast(); if (set.isEmpty()) { out.println((winner + 1) + " " + allBets[winner].first()); } else { int loser = set.last(); out.println((winner + 1) + " " + allBets[winner].higher(maxBet[loser])); } set.add(winner); } for (int man : absent) { if (allBets[man].size() > 0) { set.add(man); } } } } //------------------------------------------------------------------------------ public static void main(String[] args) { new AuctionNlogN().run(); } private void run() { try { initIO(); solve(); in.close(); out.close(); } catch (Throwable e) { throw new RuntimeException(e); } } private BufferedReader in; private StringTokenizer tok; private PrintWriter out; private void initIO() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // in = new BufferedReader(new FileReader(new File("input.txt"))); // out = new PrintWriter(new File("output.txt")); } private String readString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
2b18d89895264850a4238f54ec1a126d
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import javafx.scene.layout.Priority; import java.io.*; import java.lang.reflect.Array; import java.net.Inet4Address; import java.util.*; import java.lang.*; import java.util.HashMap; import java.util.PriorityQueue; public class templ implements Runnable { static class pair implements Comparable { int f,s; pair(int fi,int se) { f=fi; s=se; } public int compareTo(Object o) { pair pr=(pair)o; if(f>pr.f) return 1; else return -1; } public boolean equals(Object o) { pair ob=(pair)o; int ff; int ss; if(o!=null) { ff=ob.f; ss=ob.s; if((ff==this.f)&&(ss==this.s)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s).hashCode(); } } public class triplet implements Comparable { int f,s; int t; triplet(int f,int s,int t) { this.f=f; this.s=s; this.t=t; } public boolean equals(Object o) { triplet ob=(triplet)o; int ff,ss; int tt; if(o!=null) { ff=ob.f; ss=ob.s; tt=ob.t; if((ff==this.f)&&(ss==this.s)&&(tt==this.t)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s+" "+this.t).hashCode(); } public int compareTo(Object o) { triplet tr=(triplet)o; if(f>tr.f) return 1; else if(f==tr.f) { if(s>tr.s) return -1; else return 1; } else return -1; } } ArrayList<Integer>g[]; int m[]; pair tree[]; void build(int node,int start,int end) { if(start==end) { tree[node]=new pair(m[start],start); return; } int mid=(start+end)/2; build(2*node,start,mid); build(2*node+1,mid+1,end); if(tree[2*node].f>tree[2*node+1].f) { tree[node]=new pair(tree[2*node].f,tree[2*node].s); } else { tree[node]=new pair(tree[2*node+1].f,tree[2*node+1].s); } } pair query(int node,int start,int end,int l,int r) { if(end<l||r<start) return new pair(0,0); if(start>=l&&end<=r) return tree[node]; int mid=(start+end)/2; pair p1=query(2*node,start,mid,l,r); pair p2=query(2*node+1,mid+1,end,l,r); pair p3; if(p1.f>p2.f) p3=new pair(p1.f,p1.s); else p3=new pair(p2.f,p2.s); return p3; } void update(int node,int start,int end,int idx,int val) { if(idx<start||idx>end) return; if(start==end) { tree[node]=new pair(val,start); return; } int mid=(start+end)/2; update(2*node,start,mid,idx,val); update(2*node+1,mid+1,end,idx,val); if(tree[2*node].f>tree[2*node+1].f) { tree[node]=new pair(tree[2*node].f,tree[2*node].s); } else { tree[node]=new pair(tree[2*node+1].f,tree[2*node+1].s); } } int justlarge(int a,int start,int end,int val) { int p=0; while(start<=end) { int mid=(start+end)/2; if(g[a].get(mid)>val) { p=g[a].get(mid); end=mid-1; } else start=mid+1; } return p; } public static void main(String args[])throws Exception { new Thread(null,new templ(),"templ",1<<27).start(); } public void run() { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n=in.ni(); g=new ArrayList[n+1]; m=new int[n+1]; tree=new pair[4*n+1]; for(int i=1;i<=n;i++) g[i]=new ArrayList<>(); for(int i=1;i<=n;i++) { int x=in.ni(); int v=in.ni(); g[x].add(v); } for(int i=1;i<=n;i++) { Collections.sort(g[i]); int s=g[i].size(); if(s!=0) m[i]=g[i].get(s-1); } build(1,1,n); int q=in.ni(); while(q--!=0) { int k=in.ni(); ArrayList<Integer>al=new ArrayList<>(); for(int i=1;i<=k;i++) { int x=in.ni(); update(1,1,n,x,0); al.add(x); } pair max1=query(1,1,n,1,n); int a=max1.f; int b=max1.s; if(a==0) out.println("0 0"); else { update(1,1,n,b,0); al.add(b); pair max2=query(1,1,n,1,n); int aa=max2.f; int bb=max2.s; int kk=justlarge(b,0,g[b].size()-1,aa); out.println(b+" "+kk); } for(int i : al) update(1,1,n,i,m[i]); } out.close(); } catch(Exception e){ return; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
b15c10b5f7d1af9c9337288d27d7d3d0
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.PrintWriter; import java.util.*; /** * Created by leen on 26/12/2016. */ public class _749D { public static void main(String[] args) { Scanner scan = new Scanner(new BufferedInputStream(System.in,1024*64)); int n = scan.nextInt(); final Node[] nodes = new Node[n]; for(int i = 0; i < n; i++) nodes[i] = new Node(i); for(int i = 0; i < n; i++) { int idx = scan.nextInt(), bid = scan.nextInt(); nodes[idx-1].addBid(bid); } Node[] sortedNodes = Arrays.copyOf(nodes,nodes.length); Arrays.sort(sortedNodes); PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out,1024*64)); int q = scan.nextInt(); for(int i = 0; i < q; i++) { int k = scan.nextInt(); Integer[] removed = new Integer[k]; for(int j = 0; j < k; j++) removed[j] = scan.nextInt()-1; Arrays.sort(removed, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return nodes[o1].lastBid() - nodes[o2].lastBid(); } }); int biggestIdx = -1, secondBiggestIdx = -1; int p1 = k-1, p2 = n-1; while(p2 >= 0) { if(p1 < 0 || removed[p1] != sortedNodes[p2].index) { if(biggestIdx == -1) { biggestIdx = sortedNodes[p2].index; if(sortedNodes[p2].lastBid() == -1) break; p2--; } else { secondBiggestIdx = sortedNodes[p2].index; break; } } else { p1--; p2--; } } if(biggestIdx == -1 || nodes[biggestIdx].lastBid() == -1) pw.println("0 0"); else { if(secondBiggestIdx == -1 || nodes[secondBiggestIdx].lastBid() == -1) pw.println((biggestIdx+1) + " " + nodes[biggestIdx].firstBid()); else pw.println((biggestIdx+1) + " " + nodes[biggestIdx].higherBid(nodes[secondBiggestIdx].lastBid())); } } pw.flush(); } static final class Node implements Comparable<Node> { final int index; final List<Integer> bids = new ArrayList<Integer>(); Node(int index) { this.index = index; } void addBid(int bid) { bids.add(bid); } int higherBid(int otherBid) { return higher(bids, otherBid); } int firstBid() { return bids.isEmpty() ? -1 : bids.get(0); } int lastBid() { return bids.isEmpty() ? -1 : bids.get(bids.size()-1); } public int compareTo(Node o) { return lastBid() - o.lastBid(); } } static int higher(List<Integer> list, int target) { int low = 0, high = list.size(); while(low < high) { int mid = (low+high)/2; if(target < list.get(mid)) high = mid; else low = mid + 1; } return list.get(high); } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
18eac5b457179e19081ac4f9bf4e3914
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class CO_749D { static int imax=Integer.MAX_VALUE,imin=Integer.MIN_VALUE; static long lmax=Long.MAX_VALUE,lmin=Long.MIN_VALUE; static long mod=(long)1e9+7; static int max[]; public static void main (String[] args) throws java.lang.Exception { InputReader in =new InputReader(System.in); PrintWriter out=new PrintWriter(System.out); // int test=in.nextInt(); int test=1; int i=0,j=0; while(test-->0){ int n=in.nextInt(); max=new int[n+1]; TreeSet<Integer> arr[]=new TreeSet[n+1]; for(i=1;i<=n;i++){ arr[i]=new TreeSet<>(); } for(i=0;i<n;i++){ int num=in.nextInt(); int val=in.nextInt(); max[num]=Math.max(max[num],val); arr[num].add(val); } TreeSet<Integer> set=new TreeSet<>(new cmp1()); for(i=1;i<=n;i++){ if(max[i]==0)continue; set.add(i); } int q=in.nextInt(); ArrayList<Integer> list=new ArrayList<>(); // System.out.println(set); for(i=0;i<q;i++){ int k=in.nextInt(); for(j=0;j<k;j++){ int u=in.nextInt(); list.add(u); set.remove(u); } // System.out.println(set.size()+" "+set); if(set.size()==0){ out.println("0 0"); }else if(set.size()==1){ // System.out.println(set.first()+" "+i); if(max[set.first()]==0) out.println("0 0"); else out.println(set.first()+" "+arr[set.first()].first()); }else{ int tmp=set.pollLast(); out.println(tmp+" "+arr[tmp].higher(max[set.last()])); set.add(tmp); } for(j=0;j<k;j++){ set.add(list.get(j)); } list.clear(); } out.println(); } out.close(); } static class cmp1 implements Comparator<Integer>{ public int compare(Integer ob1,Integer ob2){ return max[ob1]-max[ob2]; } } static void print(long arr[],int len){ for(int i=0;i<len;i++) System.out.print(arr[i]+" "); System.out.println(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); //while (c != '\n' && c != '\r' && c != '\t' && c != -1) //c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (c != '\n' && c != '\r' && c != '\t' && c != -1); return res.toString(); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
e9c57ffd1e9b5f50947c46b4a1a34ad2
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.stream.IntStream; import java.util.Arrays; import java.util.HashMap; import java.io.IOException; import java.util.stream.Collectors; import java.io.InputStreamReader; import java.util.TreeSet; import java.util.Stack; import java.util.Objects; import java.util.stream.Stream; import java.util.Vector; import java.util.StringTokenizer; import java.util.Map; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); Map<Integer, TaskD.Bidder> bidders = new HashMap<>(); for (int i = 0; i < N; i++) { int idx = in.nextInt(); int bid = in.nextInt(); bidders.compute(idx, (k, v) -> { if (v == null) { v = new TaskD.Bidder(idx); } v.addBid(bid); return v; }); } TreeSet<TaskD.Bidder> winners = new TreeSet<>(); for (TaskD.Bidder bidder : bidders.values()) { winners.add(bidder); } int Q = in.nextInt(); for (int q = 0; q < Q; q++) { int K = in.nextInt(); Stack<Integer> removed = new Stack<>(); for (int i = 0; i < K; i++) { int idx = in.nextInt(); if (bidders.containsKey(idx)) { winners.remove(bidders.get(idx)); removed.push(idx); } } out.println(Arrays.stream(find(winners)).mapToObj(Objects::toString).collect(Collectors.joining(" "))); while (!removed.isEmpty()) { winners.add(bidders.get(removed.pop())); } } } private int[] find(TreeSet<TaskD.Bidder> winners) { if (winners.isEmpty()) { return new int[]{0, 0}; } TaskD.Bidder first = winners.first(); if (winners.size() == 1) { return new int[]{first.index, first.bids.first()}; } winners.pollFirst(); TaskD.Bidder second = winners.first(); winners.add(first); return new int[]{first.index, first.bids.ceiling(second.maximalBid)}; } private static class Bidder implements Comparable<TaskD.Bidder> { private int index; private int maximalBid; private TreeSet<Integer> bids = new TreeSet<>(); public Bidder(int index) { this.index = index; } public void addBid(int bid) { bids.add(bid); maximalBid = Math.max(maximalBid, bid); } public int compareTo(TaskD.Bidder that) { if (this.maximalBid > that.maximalBid) return -1; if (this.maximalBid < that.maximalBid) return +1; return this.index - that.index; } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
1da9c03449e5994b56d7f3937d2ac3f7
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; import java.util.HashMap; import java.util.TreeSet; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top * * @author toshif */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); HashMap<Integer, P> ts = new HashMap<>(); for (int i = 0; i < n; i++) { Integer idx = Integer.valueOf(in.next()); long val = Long.valueOf(in.next()); if (ts.get(idx) != null) { P p = ts.get(idx); p.vals.add(val); p.ma = p.vals.last(); } else { P p = new P(idx, val); ts.put(idx, p); } } TreeSet<P> ps = new TreeSet<>(); ps.addAll(ts.values()); int m = in.nextInt(); for (int i = 0; i < m; i++) { int k = Integer.valueOf(in.next()); ArrayList<P> exs = new ArrayList<>(); for (int j = 0; j < k; j++) { Integer idx = Integer.valueOf(in.next()); if (!ts.containsKey(idx)) continue; P p1 = ts.get(idx); exs.add(p1); ps.remove(p1); } if (ps.isEmpty()) { out.println("0 0"); ps.addAll(exs); continue; } // find the max P last = ps.last(); P second = ps.lower(last); Long bid = 0L; if (second != null) { Long secondVal = second.vals.last(); bid = last.vals.higher(secondVal); } else { bid = last.vals.first(); } out.println(last.idx + " " + bid); ps.addAll(exs); } } class P implements Comparable<P> { int idx; TreeSet<Long> vals = new TreeSet<>(); long ma = 0; public P(int idx, long val) { this.idx = idx; this.vals.add(val); this.ma = val; } public int compareTo(P o) { return Long.compare(this.ma, o.ma); } public boolean equals(Object obj) { return ma == ((P) obj).ma; } } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
c70224e41bc15de2695fe1e1343ca4fb
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.AbstractMap; import java.util.TreeMap; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.HashMap; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top * * @author toshif */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); // idx -> list HashMap<Integer, List<Long>> ts = new HashMap<>(); for (int i = 0; i < n; i++) { Integer idx = Integer.valueOf(in.next()); Long val = Long.valueOf(in.next()); if (!ts.containsKey(idx)) { ts.put(idx, new ArrayList<>()); } List<Long> vs = ts.get(idx); vs.add(val); } TreeMap<Long, List<Long>> ps = new TreeMap<>(); Map<Long, Integer> iv = new HashMap<>(); for (Map.Entry<Integer, List<Long>> entry : ts.entrySet()) { ps.put(entry.getValue().get(entry.getValue().size() - 1), entry.getValue()); iv.put(entry.getValue().get(entry.getValue().size() - 1), entry.getKey()); } // query int m = in.nextInt(); for (int i = 0; i < m; i++) { int k = Integer.valueOf(in.next()); HashMap<Long, List<Long>> exs = new HashMap<>(); for (int j = 0; j < k; j++) { Integer idx = Integer.valueOf(in.next()); if (!ts.containsKey(idx)) continue; List<Long> vs = ts.get(idx); Long val = vs.get(vs.size() - 1); exs.put(val, ps.get(val)); ps.remove(val); } if (ps.isEmpty()) { out.println("0 0"); ps.putAll(exs); continue; } // find the max Map.Entry<Long, List<Long>> last = ps.lastEntry(); Map.Entry<Long, List<Long>> second = ps.lowerEntry(last.getKey()); Long bid = 0L; if (second != null) { Long secondVal = second.getValue().get(second.getValue().size() - 1); bid = last.getValue().get(higher(last.getValue(), secondVal)); } else { bid = last.getValue().get(0); } out.println(iv.get(last.getKey()) + " " + bid); ps.putAll(exs); } } public static int higher(List<Long> a, Long e) { int lo = 0, hi = a.size() - 1; if (a.get(hi) <= e) return -1; while (hi - lo > 1) { int mid = (lo + hi) / 2; if (a.get(mid) <= e) { lo = mid; } else { hi = mid; } } if (a.get(lo) > e) return lo; else return hi; } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
dc9111608cebe34bab7469f073e61c69
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.Scanner; import java.util.HashMap; import java.util.TreeSet; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top * * @author toshif */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); HashMap<Integer, P> ts = new HashMap<>(); for (int i = 0; i < n; i++) { Integer idx = Integer.valueOf(in.next()); long val = Long.valueOf(in.next()); if (ts.get(idx) != null) { P p = ts.get(idx); p.valsList.add(val); p.ma = p.valsList.get(p.valsList.size() - 1); } else { P p = new P(idx, val); ts.put(idx, p); } } TreeSet<P> ps = new TreeSet<>(); ps.addAll(ts.values()); int m = in.nextInt(); for (int i = 0; i < m; i++) { int k = Integer.valueOf(in.next()); ArrayList<P> exs = new ArrayList<>(); for (int j = 0; j < k; j++) { Integer idx = Integer.valueOf(in.next()); if (!ts.containsKey(idx)) continue; P p1 = ts.get(idx); exs.add(p1); ps.remove(p1); } if (ps.isEmpty()) { out.println("0 0"); ps.addAll(exs); continue; } // find the max P last = ps.last(); P second = ps.lower(last); Long bid = 0L; if (second != null) { Long secondVal = second.valsList.get(second.valsList.size() - 1); bid = binarySearch_Higher(last.valsList, secondVal); } else { bid = last.valsList.get(0); } out.println(last.idx + " " + bid); ps.addAll(exs); } } Long binarySearch_Higher(List<Long> list, Long e) { int lo = 0; int hi = list.size() - 1; for (int i = 0; i < 100; i++) { if (lo == hi) break; int mid = (lo + hi) / 2; Long midVal = list.get(mid); if (midVal < e) { if (lo == mid) break; lo = mid; } else { if (hi == mid) break; hi = mid; } } if (list.get(lo) > e) return list.get(lo); return list.get(hi); } class P implements Comparable<P> { int idx; List<Long> valsList = new ArrayList<>(); long ma = 0; public P(int idx, long val) { this.idx = idx; this.valsList.add(val); this.ma = val; } public int compareTo(P o) { return Long.compare(this.ma, o.ma); } public boolean equals(Object obj) { return ma == ((P) obj).ma; } } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
3554417f911fbab46b38430fb8f5e636
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.Scanner; import java.util.HashMap; import java.util.TreeSet; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top * * @author toshif */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); // idx -> list HashMap<Integer, P> ts = new HashMap<>(); for (int i = 0; i < n; i++) { Integer idx = Integer.valueOf(in.next()); Long val = Long.valueOf(in.next()); if (!ts.containsKey(idx)) { P p = new P(); p.idx = idx; ts.put(idx, p); } P p = ts.get(idx); p.vs.add(val); p.ma = val; } TreeSet<P> ps = new TreeSet<>(); ps.addAll(ts.values()); // query int m = in.nextInt(); for (int i = 0; i < m; i++) { int k = Integer.valueOf(in.next()); List<P> exs = new ArrayList<>(); for (int j = 0; j < k; j++) { Integer idx = Integer.valueOf(in.next()); if (!ts.containsKey(idx)) continue; P p = ts.get(idx); ps.remove(p); exs.add(p); } if (ps.isEmpty()) { out.println("0 0"); ps.addAll(exs); continue; } // find the max P last = ps.last(); P second = ps.lower(last); Long bid = 0L; if (second != null) { bid = last.vs.higher(second.ma); } else { bid = last.vs.first(); } out.println(last.idx + " " + bid); ps.addAll(exs); } } class P implements Comparable<P> { int idx; TreeSet<Long> vs = new TreeSet<>(); long ma; public int compareTo(P o) { return Long.compare(ma, o.ma); } public boolean equals(Object obj) { return ma == ((P) obj).ma; } } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
d385529ccfef29cbacdd623177d619f1
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Set; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.util.LinkedList; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyBufferedReader in = new MyBufferedReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, MyBufferedReader in, PrintWriter out) { int n = in.getAnInt(); int COLOR = 0; int BID = 1; ArrayList<ArrayList<Integer>> bidsPerColor = new ArrayList<>(); for (int i = 0; i < n; i++) { bidsPerColor.add(new ArrayList<>()); } ArrayList<Integer> sortedByLastOcc = new ArrayList<>(); for (int i = 0; i < n; i++) { int[] data = in.getALineOfInts(2); int color = data[COLOR] - 1; int bid = data[BID]; if (bidsPerColor.get(color).isEmpty()) { sortedByLastOcc.add(color); } bidsPerColor.get(color).add(bid); } Collections.sort(sortedByLastOcc, new Comparator<Integer>() { public int compare(Integer c1, Integer c2) { ArrayList<Integer> c1Poss = bidsPerColor.get(c1); ArrayList<Integer> c2Poss = bidsPerColor.get(c2); return c1Poss.get(c1Poss.size() - 1) - c2Poss.get(c2Poss.size() - 1); } }); int q = in.getAnInt(); for (int i = 0; i < q; i++) { int[] data = in.getALineOfInts(false); int k = data[0]; Set<Integer> remColors = new HashSet<>(); for (int j = 1; j <= k; j++) { int colorToRem = data[j] - 1; if (bidsPerColor.get(colorToRem).size() > 0) { remColors.add(colorToRem); } } if (remColors.size() == sortedByLastOcc.size()) { out.println("0 0"); continue; } int l = sortedByLastOcc.size() - 1; while (l >= 0 && remColors.contains(sortedByLastOcc.get(l))) { l--; } int lastColor = sortedByLastOcc.get(l); if (remColors.size() == sortedByLastOcc.size() - 1) { out.println((lastColor + 1) + " " + bidsPerColor.get(lastColor).get(0)); continue; } l--; while (l >= 0 && remColors.contains(sortedByLastOcc.get(l))) { l--; } int secondToLast = sortedByLastOcc.get(l); ArrayList<Integer> secondToLastBids = bidsPerColor.get(secondToLast); int secondToLastLastBid = secondToLastBids.get(secondToLastBids.size() - 1); ArrayList<Integer> lastColorBids = bidsPerColor.get(lastColor); int start = 0; int end = lastColorBids.size(); while (start < end) { int mid = (start + end) / 2; if (lastColorBids.get(mid) > secondToLastLastBid) { end = mid; } else { start = mid + 1; } } out.println((lastColor + 1) + " " + lastColorBids.get(start)); } } } static class MyBufferedReader { BufferedReader in; public MyBufferedReader(InputStream s) { this.in = new BufferedReader(new InputStreamReader(s)); } public int getAnInt() { int res = -1; try { res = Integer.parseInt(new StringTokenizer(in.readLine()).nextToken()); } catch (IOException e) { e.printStackTrace(); } return res; } public int[] getALineOfInts(int numExpected) { int[] res = new int[numExpected]; StringTokenizer st = null; try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } for (int i = 0; i < numExpected; i++) res[i] = Integer.parseInt(st.nextToken()); return res; } public int[] getALineOfInts(boolean ignoreLast) { List<Integer> listRes = new LinkedList<Integer>(); StringTokenizer st = null; try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } while (st.hasMoreTokens()) listRes.add(Integer.parseInt(st.nextToken())); int[] arrayRes; if (ignoreLast) arrayRes = new int[listRes.size() - 1]; else arrayRes = new int[listRes.size()]; int i = 0; for (int elem : listRes) { if (ignoreLast && i == listRes.size() - 1) break; arrayRes[i] = elem; i++; } return arrayRes; } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
e235b8ff432418d65148d0c034e78b37
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class q4 { //static ArrayList<Integer> g[]; static int n; static int[] mxdeal; static int[] made; static int[] price; static TreeSet<Integer> ts[]; static TreeSet<Integer> tm; public static void main(String[] ags) { InputReader in=new InputReader(System.in); PrintWriter pw=new PrintWriter(System.out); n=in.nextInt(); mxdeal=new int[n]; ts=new TreeSet[n]; for(int i=0;i<n;i++) { ts[i]=new TreeSet<Integer>(); } tm=new TreeSet<Integer>(); Arrays.fill(mxdeal, -1); made=new int[n]; price=new int[n]; for(int i=0;i<n;i++) { made[i]=in.nextInt()-1; price[i]=in.nextInt(); ts[made[i]].add(i); mxdeal[made[i]]=i; } for(int i=0;i<n;i++) { if(mxdeal[i]!=-1) { tm.add(mxdeal[i]); } } tm.add(-1); int q=in.nextInt(); SparshTable sp=new SparshTable(mxdeal); while(q-->0) { int k=in.nextInt(); int[] qr=new int[k]; ArrayList<Integer> rem=new ArrayList<Integer>(); for(int i=0;i<k;i++) { qr[i]=in.nextInt()-1; if(mxdeal[qr[i]]!=-1) { rem.add(mxdeal[qr[i]]); tm.remove(mxdeal[qr[i]]); } } Arrays.sort(qr); int max=-1; int cur=0; for(int i=0;i<k;i++) { max=Math.max(max, sp.query(cur, qr[i]-1)); cur=qr[i]+1; } max=Math.max(max, sp.query(qr[k-1]+1, n-1)); if(max==-1) { pw.println(0+" "+0); } else { tm.remove(mxdeal[made[max]]); rem.add(mxdeal[made[max]]); max=ts[made[max]].ceiling(tm.last()); pw.println((made[max]+1)+" "+price[max]); } for(int i=0;i<rem.size();i++) { tm.add(rem.get(i)); } } //int[] a=readint(in,n); // for(int i=0;i<n;i++) // { // g[i]=new ArrayList<Integer>(); // } // for(int i=0;i<n-1;i++) // { // int u=in.nextInt()-1; // int v=in.nextInt()-1; // g[u].add(v); // g[v].add(u); // } // PriorityQueue<Integer> pq=new PriorityQueue<Integer>(); pw.close(); } static class SparshTable { int n; int logmax=20; int[] logtable; int[] arr; int[][] sp; SparshTable(int[] arr) { this.n=arr.length; logtable=new int[n+1]; for(int i=2;i<=n;i++) { logtable[i]=logtable[i/2]+1; } sp=new int[n][logmax+1]; for(int i=0;i<n;i++) { sp[i][0]=arr[i]; } for(int j=1;(1<<j)<=n;j++) { for (int i = 0; i + (1 << j) - 1 < n; i++) { sp[i][j] = Math.max(sp[i + (1 << (j - 1))][j - 1],sp[i][j - 1]); } } } public int query(int i,int j) { if(i>j || i<0) { return -1; } int k=logtable[j-i+1]; return Math.max(sp[i][k],sp[j-(1<<k)+1][k]); } } // public static void dfs(int u,int p) // { // visited[u]=true; // for(int i=0;i<g[u].size();i++){ // int v=g[u].get(i); // if(!visited[v]) // { // dfs(v,u); // } // } // } public static int[] readint(InputReader in,int n) { int[] a=new int[n]; for(int i=0;i<n;i++) { a[i]=in.nextInt(); } return a; } public static long[] readlong(InputReader in,int n) { long[] a=new long[n]; for(int i=0;i<n;i++) { a[i]=in.nextLong(); } return a; } public static void addhm(HashMap<Integer,Integer> hm,int k) { int cc=0; if(hm.containsKey(k)) { cc=hm.get(k); } hm.put(k, cc+1); } public static void removehm(HashMap<Integer,Integer> hm,int k) { int cc=hm.get(k); if(cc==1) { hm.remove(k); } else { hm.put(k,cc-1); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
698883cb862543fdb24113becc1be220
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.*; import java.util.*; public class D { InputStream is; int __t__ = 1; int __f__ = 0; int __FILE_DEBUG_FLAG__ = __f__; String __DEBUG_FILE_NAME__ = "src/D3"; FastScanner in; PrintWriter out; int[] a, b; class Trie { int p1; // max 1st int p2; // max 2nd HashMap<Integer, Trie> childs = new HashMap<>(); Trie(int ptr, int ptr2) { this.p1 = ptr; this.p2 = ptr2; childs = new HashMap<>(); } public void add(int at, int[] l, boolean[] used) { if (at == l.length) return; used[l[at]] = true; if (!childs.containsKey(l[at])) childs.put(l[at], new Trie(p1, p2)); Trie c = childs.get(l[at]); while (used[a[c.p1]]) c.p1--; c.p2 = Math.max(c.p1 - 1, 0); while (c.p2 > 0) { if (a[c.p1] == a[c.p2]) { c.p1 = c.p2; } else { if (!used[a[c.p2]]) break; } c.p2--; } c.add(at + 1, l, used); used[l[at]] = false; } public int get(int at, int[] l) { if (at == l.length) return p1; return childs.get(l[at]).get(at + 1, l); } } public void solve() { int n = in.nextInt(); a = new int[n+1]; b = new int[n+1]; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); b[i] = in.nextInt(); } Trie trie = new Trie(n, n); int Q = in.nextInt(); boolean[] used = new boolean[n+1]; for (int q = 0; q < Q; q++) { int k = in.nextInt(); int[] l = new int[k]; for (int i = 0; i < k; i++) { l[i] = in.nextInt(); } trie.add(0, l, used); int idx = trie.get(0, l); out.println(a[idx] + " " + b[idx]); } out.close(); } public void run() { if (__FILE_DEBUG_FLAG__ == __t__) { try { is = new FileInputStream(__DEBUG_FILE_NAME__); } catch (FileNotFoundException e) { // TODO θ‡ͺε‹•η”Ÿζˆγ•γ‚ŒγŸ catch ブロック e.printStackTrace(); } System.out.println("FILE_INPUT!"); } else { is = System.in; } in = new FastScanner(is); out = new PrintWriter(System.out); solve(); } public static void main(String[] args) { new D().run(); } public void mapDebug(int[][] a) { System.out.println("--------map display---------"); for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.printf("%3d ", a[i][j]); } System.out.println(); } System.out.println("----------------------------"); System.out.println(); } public void debug(Object... obj) { System.out.println(Arrays.deepToString(obj)); } class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; //stream = new FileInputStream(new File("dec.in")); } int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { return nextIntArray(n, 0); } int[] nextIntArray(int n, int margin) { int[] array = new int[n + margin]; for (int i = 0; i < n; i++) array[i + margin] = nextInt(); return array; } int[][] nextIntMap(int n, int m) { int[][] map = new int[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextIntArray(m); } return map; } long nextLong() { return Long.parseLong(next()); } long[] nextLongArray(int n) { return nextLongArray(n, 0); } long[] nextLongArray(int n, int margin) { long[] array = new long[n + margin]; for (int i = 0; i < n; i++) array[i + margin] = nextLong(); return array; } long[][] nextLongMap(int n, int m) { long[][] map = new long[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextLongArray(m); } return map; } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { return nextDoubleArray(n, 0); } double[] nextDoubleArray(int n, int margin) { double[] array = new double[n + margin]; for (int i = 0; i < n; i++) array[i + margin] = nextDouble(); return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][m]; for (int i = 0; i < n; i++) { map[i] = in.nextDoubleArray(m); } return map; } String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) array[i] = next(); return array; } String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
652db71e4db4564c21f92a57807449be
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.util.*; import java.io.*; public class CF749D_2{ public static int index; public static void main(String[] args)throws Exception { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(); ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); ArrayList<TreeSet<Pair>> node = new ArrayList<TreeSet<Pair>>(); for(int i = 0; i <= n; i++){ list.add(new ArrayList<Integer>()); node.add(new TreeSet<Pair>()); } // TreeSet<Pair> set = new TreeSet<Pair>(); Pair[] a = new Pair[n]; TreeSet<Pair> maxPair = new TreeSet<Pair>(); for(int i = 0; i < n; i++){ Pair p = new Pair(in.nextInt(), in.nextInt()); list.get(p.a).add(i); //set.add(p); node.get(p.a).add(p); a[i] = p; } for(int i = 1; i <= n; i++){ if(list.get(i).size() == 0) continue; maxPair.add(a[list.get(i).get(list.get(i).size()-1)]); } int k = in.nextInt(); int [] x = new int[n+1]; for(int q = 0; q < k; q++){ int m = in.nextInt(); for(int i = 0; i < m; i++){ x[i] = in.nextInt(); if(list.get(x[i]).size() == 0) continue; int j = list.get(x[i]).size()-1; //System.err.println(x[i]+" "+j); int idx = list.get(x[i]).get(j); maxPair.remove(a[idx]); } //System.out.println(maxPair); if(maxPair.size() == 0) pw.println("0 0"); else{ if(maxPair.size() == 1) { Pair temp = maxPair.first(); pw.println(node.get(temp.a).first()); } else{ Pair secondMax = maxPair.lower(maxPair.last()); Pair ans = node.get(maxPair.last().a).higher(secondMax); pw.println(ans); } } for(int i = 0; i < m; i++){ if(list.get(x[i]).size() == 0) continue; int j = list.get(x[i]).size()-1; int idx = list.get(x[i]).get(j); maxPair.add(a[idx]); } } pw.close(); } static class Pair implements Comparable<Pair>{ public int a, b; public Pair(int aa, int bb){ a = aa; b = bb; } @Override public int hashCode() { return Long.valueOf((a * 31 + b)).hashCode(); } @Override public boolean equals( Object p){ if(this == p) return true; if(p == null ) return false; if (getClass() != p.getClass()) return false; Pair pp = (Pair) p; return a == pp.a && b == pp.b; } public int compareTo(Pair p){ return b - p.b; } public String toString(){ return a+" "+b; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next()throws Exception { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public String nextLine()throws Exception { String line = null; tokenizer = null; line = reader.readLine(); return line; } public int nextInt()throws Exception { return Integer.parseInt(next()); } public double nextDouble() throws Exception{ return Double.parseDouble(next()); } public long nextLong()throws Exception { return Long.parseLong(next()); } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
9dd866532bd2b122d66a69d5b61e45dd
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeSet; public class AuctionNlogN { private void solve() throws IOException { int n = readInt(); int[] maxBet = new int[n]; Arrays.fill(maxBet, -1); TreeSet<Integer>[] allBets = new TreeSet[n]; for (int man = 0; man < n; man++) { allBets[man] = new TreeSet<>(); } for (int i = 0; i < n; i++) { int man = readInt() - 1; int bet = readInt(); allBets[man].add(bet); maxBet[man] = bet; } TreeSet<Integer> set = new TreeSet<>((a, b) -> { int res = Integer.compare(maxBet[a], maxBet[b]); if (res == 0) { res = Integer.compare(a, b); } return res; }); for (int man = 0; man < n; man++) { if (allBets[man].size() > 0) { set.add(man); } } int q = readInt(); for (int i = 0; i < q; i++) { int cnt = readInt(); int[] absent = new int[cnt]; for (int j = 0; j < cnt; j++) { absent[j] = readInt() - 1; } for (int man : absent) { set.remove(man); } if (set.isEmpty()) { out.println("0 0"); } else { int winner = set.pollLast(); if (set.isEmpty()) { out.println((winner + 1) + " " + allBets[winner].first()); } else { int loser = set.last(); out.println((winner + 1) + " " + allBets[winner].higher(maxBet[loser])); } set.add(winner); } for (int man : absent) { if (allBets[man].size() > 0) { set.add(man); } } } } //------------------------------------------------------------------------------ public static void main(String[] args) { new AuctionNlogN().run(); } private void run() { try { initIO(); solve(); in.close(); out.close(); } catch (Throwable e) { throw new RuntimeException(e); } } private BufferedReader in; private StringTokenizer tok; private PrintWriter out; private void initIO() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // in = new BufferedReader(new FileReader(new File("input.txt"))); // out = new PrintWriter(new File("output.txt")); } private String readString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
573656e75caeb0afacd4383dec38fa16
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.*; import java.util.*; public class SingleTest { public static void main(String[] args){ InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); int test_cases = 1; Solver s = new Solver(); for (int i = 1; i <= test_cases; i++) s.solve(1, in, out); out.close(); } } class Solver { static class Pair { TreeSet<Integer> s; int id; Pair() { s = new TreeSet<>(); } } public void solve(int test_number, InputReader in, PrintWriter out){ int n = in.nextInt(); int m = 0; int[] idx = new int[200005]; int[] bdx = new int[200005]; int[] found = new int[200005]; for (int i = 0; i < n; i++) { int id = in.nextInt() - 1; int bid = in.nextInt(); if (found[id] == 0) { m++; found[id] = 1; } idx[i] = id; bdx[i] = bid; } Pair[] v = new Pair[m]; for (int i = 0; i < m; i++) { v[i] = new Pair(); } Pair[] u = new Pair[200005]; for (int i = 0; i < u.length; i++) u[i] = new Pair(); for (int i = 0; i < n; i++) { int id = idx[i]; int bid = bdx[i]; if (id >= u.length) throw new RuntimeException("HEY!"); u[id].s.add(bid); u[id].id = id + 1; } int w = 0; for (int i = 0; i < n; i++) { if (u[i].s.size() > 0) { if (w >= v.length) throw new RuntimeException("HEY?"); v[w++] = u[i]; } } Arrays.sort(v, 0, m, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if (o1.s.size() > 0 && o2.s.size() > 0) return (o1.s.last() - o2.s.last()); else return 1; } }); // for (int i = 0; i < m; i++) { // out.print(v[i].id + " "); // for (Object x : v[i].s) out.print(x + " "); // out.println(); // } int q = in.nextInt(); boolean[] can_have = new boolean[200005]; Arrays.fill(can_have, true); while (q-- > 0) { int k = in.nextInt(); int[] b = new int[k]; for (int i = 0; i < k; i++) { b[i] = in.nextInt() - 1; if (b[i] >= can_have.length) continue; can_have[b[i]] = false; } int pos1 = -1, pos2 = -1; for (int i = m - 1; i >= 0; i--) { if (pos1 == -1 || pos2 == -1) { if (can_have[v[i].id - 1]) { if (pos1 == -1) { pos1 = i; } else if (pos2 == - 1) { pos2 = i; } } } else break; } if (pos1 == - 1 && pos2 == -1) { out.println("0 0"); } else if (pos1 != -1 && pos2 == -1) { if (pos1 >= v.length || v[pos1].s == null) throw new RuntimeException("HYUY"); out.println(v[pos1].id + " " + v[pos1].s.first()); } else { if (pos1 >= v.length || v[pos1].s == null) throw new RuntimeException("HYUY0"); out.println(v[pos1].id + " " +v[pos1].s.higher(v[pos2].s.last())); } for (int i = 0; i < k; i++) { if (b[i] < can_have.length) can_have[b[i]] = true; } } } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
f0613f17be9e47b5ffa4278b4fe782b7
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.* ; import java.util.* ; public class Codeshefcode{ public static void main(String[] args) throws IOException{ Solver Machine = new Solver() ; Machine.Solve() ; Machine.Finish() ; } } class Solver{ final long r = 1000000007 ; FasterScanner ip = new FasterScanner() ; PrintWriter op = new PrintWriter(System.out) ; MyList adj[] ; void Solve() throws IOException{ int N = ip.i() ; adj = new MyList[N+1] ; for(int i=1 ; i<=N ; i++){ adj[i] = new MyList() ; } for(int i=0 ; i<N ; i++){ int x = ip.i() ; long y = ip.l() ; adj[x].add(y) ; } TreeSet<pair> set = new TreeSet<pair>() ; for(int i=1 ; i<=N ; i++){ if(adj[i].size()!=0) set.add(new pair(i,adj[i].get(adj[i].size()-1))) ; } int q = ip.i() ; while(q--!=0){ int k = ip.i() ; int l[] = new int[k] ; for(int i=0 ; i<k ; i++){ l[i] = ip.i() ; if(adj[l[i]].size()!=0) set.remove(new pair(l[i],adj[l[i]].get(adj[l[i]].size()-1))) ; } pair p = set.pollLast() ; if(p==null){ op.println("0 0") ; }else{ int ind = p.getx() ; pair p1 = set.size()==0 ? null : set.last() ; if(p1==null){ op.println(ind+" "+adj[ind].get(0)) ; }else{ int ans = -(Collections.binarySearch(adj[ind],p1.gety())+1) ; op.println(ind+" "+adj[ind].get(ans)) ; } set.add(p) ; } for(int i=0 ; i<k ; i++) if(adj[l[i]].size()!=0) set.add(new pair(l[i],adj[l[i]].get(adj[l[i]].size()-1))) ; } } void Finish(){ op.flush(); op.close(); } } @SuppressWarnings("serial") class MyList extends ArrayList<Long>{ } class pair implements Comparable<pair>{ private int x ; private long y ; pair(int a,long b){ x=a ; y=b ; } public int getx(){ return x ; } public long gety(){ return y ; } @Override public int compareTo(pair p){ if(this.y<p.y) return -1 ; if(this.y==p.y){ if(this.x<p.x) return -1 ; if(this.x==p.x) return 0 ; return 1 ; } return 1 ; } } class ModOp{ final static private long r=1000000007 ; static long D(long a , long b){ return (a*ModInverse(b))%r ; } static long m(long a , long b){ return (a*b)%r ; } static long ModInverse(long a ){ return FastPowr(a,r-2) ; } static long FastPowr(long a , long b){ if(b==0) return 1 ; if(b==1) return a ; long halfpow = FastPowr(a,b/2) ; if(b%2==0) return (halfpow*halfpow)%r ; else return (((halfpow*halfpow)%r)*a)%r ; } } class FasterScanner { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FasterScanner() { this(System.in); } public FasterScanner(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 S(){ int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); }while (!isSpaceChar(c)); return res.toString(); } public long l(){ 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 i(){ 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; } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
73f31760fab47a3f0380eb38fa290240
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) { ConsoleIO io = new ConsoleIO(); new Main(io).solve(); io.close(); } ConsoleIO io; Main(ConsoleIO io) { this.io = io; } long MOD = 1_000_000_007; int N, M, W, K, Q; class Edge{ public Edge(int n1, int n2, int id){ this.n1 = n1; this.n2 = n2; this.id = id; } public int n1; public int n2; public int id; } ArrayList<ArrayList<Edge>> gr = new ArrayList<>(); class Bid{ public int id; public int money; } Bid[] bids; public void solve() { int N = io.ri(); bids = new Bid[N+1]; ArrayList<ArrayList<Integer>> all = new ArrayList<>(); for(int i = 0;i<=N;i++) all.add(new ArrayList<>()); for(int i = 1;i<=N;i++) { Bid b = new Bid(); b.id = io.ri(); b.money = io.ri(); bids[i] = b; all.get(b.id).add(i); } boolean[] used = new boolean[N+1]; ArrayList<Integer> list = new ArrayList<>(); ArrayList<Integer> maxs = new ArrayList<>(); for(int i = N;i>0;i--){ int id = bids[i].id; if(used[id])continue; used[id] = true; list.add(id); maxs.add(i); } Q = io.ri(); int[] map = new int[N+1]; int[] buf = new int[N]; StringBuilder sb = new StringBuilder(); for(int i = 0;i<Q;i++){ int k = io.ri(); for(int j = 0;j<k;j++){ int t = io.ri(); buf[j] = t; map[t] = 1; } int num = 0; int more = 0; int first = 0; for(int j = 0;j<list.size();j++) { int v = list.get(j); if (map[v] == 0) { if(first == 0) { num = v; first = 1; } else { more = maxs.get(j); break; } } } for(int j = 0;j<k;j++) map[buf[j]] = 0; if(num == 0){ if(i>0)sb.append(System.lineSeparator()); sb.append("0 0"); continue; } ArrayList<Integer> a = all.get(num); int left = 0, right = a.size(); while(left <right){ int mm = (left+right)/2; if(a.get(mm)>more)right = mm; else left = mm+1; } if(i>0)sb.append(System.lineSeparator()); sb.append(num + " " + bids[a.get(left)].money); } io.writeLine(sb.toString()); } } class ConsoleIO { BufferedReader br; PrintWriter out; public ConsoleIO(){br = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);} public void flush(){this.out.flush();} public void close(){this.out.close();} public void writeLine(String s) {this.out.println(s);} public void writeInt(int a) {this.out.print(a);this.out.print(' ');} public void writeWord(String s){ this.out.print(s); } public void writeIntArray(int[] a, int k, String separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k; i++) { if (i > 0) sb.append(separator); sb.append(a[i]); } this.writeLine(sb.toString()); } public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }} public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}} public long[] readLongArray() { String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length]; for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]); return r; } public int[] readIntArray() { String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length]; for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]); return r; } public int[] readIntArray(int n) { int[] res = new int[n]; char[] all = this.readLine().toCharArray(); int cur = 0;boolean have = false; int k = 0; boolean neg = false; for(int i = 0;i<all.length;i++){ if(all[i]>='0' && all[i]<='9'){ cur = cur*10+all[i]-'0'; have = true; }else if(all[i]=='-') { neg = true; } else if(have){ res[k++] = neg?-cur:cur; cur = 0; have = false; neg = false; } } if(have)res[k++] = neg?-cur:cur; return res; } public int ri() { try { int r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public long readLong() { try { long r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public String readWord() { try { boolean start = false; StringBuilder sb = new StringBuilder(); while (true) { int c = br.read(); if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') { sb.append((char)c); start = true; } else if (start || c == -1) return sb.toString(); } } catch (Exception ex) { return ""; } } public char readSymbol() { try { while (true) { int c = br.read(); if (c != ' ' && c != '\r' && c != '\n' && c != '\t') { return (char) c; } } } catch (Exception ex) { return 0; } } public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }} } class Pair { public Pair(int a, int b) {this.a = a;this.b = b;} public int a; public int b; } class Tri { public Tri(int a, int b, int c) {this.a = a;this.b = b;this.c = c;} public int a; public int b; public int c; } class PairLL { public PairLL(long a, long b) {this.a = a;this.b = b;} public long a; public long b; }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
343b62f18477236df11ec9b862668717
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * @author pttrung */ public class D_Round_388_Div2 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int[] data = new int[n]; ArrayList<Integer>[] t = new ArrayList[n]; Arrays.fill(data, -1); int[][] store = new int[n][2]; TreeSet<int[]> q = new TreeSet<>(new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { // TODO Auto-generated method stub return Integer.compare(o1[1], o2[1]); } }); for (int i = 0; i < n; i++) { t[i] = new ArrayList(); } for (int i = 0; i < n; i++) { int u = in.nextInt() - 1; int v = in.nextInt(); store[i][0] = u; store[i][1] = v; t[u].add(i); data[u] = i; } for (int i = 0; i < n; i++) { if (data[i] != -1) { q.add(new int[]{i, data[i]}); } } int z = in.nextInt(); for (int i = 0; i < z; i++) { int k = in.nextInt(); int[][] tmp = new int[k][2]; for (int j = 0; j < k; j++) { int v = in.nextInt() - 1; tmp[j][0] = v; tmp[j][1] = data[v]; } Arrays.sort(tmp, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { // TODO Auto-generated method stub return Integer.compare(o2[1], o1[1]); } }); for (int j = 0; j < k && !q.isEmpty(); j++) { if (q.last()[0] == tmp[j][0]) { q.pollLast(); } else { break; } } if (!q.isEmpty()) { int last = q.last()[0]; int lastIndex = t[last].size() - 1; int st = 0; int ed = t[last].size() - 1; int re = 0; while (st <= ed) { int mid = (st + ed) >> 1; int total = 0; int dif = t[last].get(lastIndex) - t[last].get(mid) - (lastIndex - mid); for (int j = 0; j < k; j++) { int v = tmp[j][0]; total += getCount(t[last].get(mid), t[last].get(lastIndex), t[v]); } // System.out.println(mid + " " + total + " " + i + " " + dif + " " + t[last].get(lastIndex) + " " + t[last].get(mid) + " " + lastIndex); if (total < dif) { re = mid + 1; st = mid + 1; } else { ed = mid - 1; } } out.println(((last + 1)) + " " + store[t[last].get(re)][1]); } else { out.println("0 0"); } for (int j = 0; j < k; j++) { if (tmp[j][1] != -1) { q.add(tmp[j]); } } } out.close(); } static int getCount(int st, int ed, ArrayList<Integer> list) { int s = 0; int e = list.size() - 1; int a = -1; while (s <= e) { int mid = (s + e) >> 1; if (list.get(mid) >= st) { a = mid; e = mid - 1; } else { s = mid + 1; } } s = 0; e = list.size() - 1; int b = -1; while (s <= e) { int mid = (s + e) >> 1; if (list.get(mid) <= ed) { b = mid; s = mid + 1; } else { e = mid - 1; } } if (a != -1 && b != -1) { return Math.max(0, b - a + 1); } return 0; } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
7626a8fe2a23055546a6226f487512cd
train_002.jsonl
1482165300
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi &lt; bi + 1 for all i &lt; n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i &lt; n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.
256 megabytes
import java.io.*; import java.util.*; /** * Created by WiNDWAY on 12/19/16. */ public class Codeforces_round_388_div_2_LeavingAuction { public static void main(String[] args) throws IOException { Reader input = new Reader(); out = new PrintWriter(new BufferedOutputStream(System.out), true); int n = input.nextInt(); HashMap<Integer, ArrayList<Integer>> map = new HashMap<>(); HashMap<Integer, Integer> highBidding = new HashMap<>(); HashMap<Integer, Integer> biddingHistory = new HashMap<>(); for (int i = 0; i < n; i++) { int player = input.nextInt(); int amount = input.nextInt(); if (!map.containsKey(player)) { map.put(player, new ArrayList<>()); highBidding.put(player, amount); } highBidding.put(player, Math.max(amount, highBidding.get(player))); map.get(player).add(amount); biddingHistory.put(amount, player); } ArrayList<Integer> highestBidList = new ArrayList<>(highBidding.keySet()); Collections.sort(highestBidList, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return highBidding.get(o1).compareTo(highBidding.get(o2)); } }); int situations = input.nextInt(); for (int i = 0; i < situations; i++) { int remove = input.nextInt(); HashSet<Integer> removedPlayers = new HashSet<>(); for (int j = 0; j < remove; j++) { int player = input.nextInt(); removedPlayers.add(player); } ArrayList<Integer> topWinners = new ArrayList<>(); int loopIndex = highestBidList.size() - 1; while (topWinners.size() < 2 && loopIndex >= 0) { int playerID = highestBidList.get(loopIndex); if (!removedPlayers.contains(playerID)) { topWinners.add(playerID); } loopIndex--; } if (topWinners.size() == 1) { int winner = topWinners.get(0); ArrayList<Integer> list = map.get(winner); out.println(winner + " " + list.get(0)); } else if (topWinners.isEmpty()) { out.println("0 0"); } else { int firstWinner = topWinners.get(0); int secondWinner = topWinners.get(1); if (map.get(firstWinner).get(map.get(firstWinner).size() - 1) > map.get(secondWinner).get(map.get(secondWinner).size() - 1)) { ArrayList<Integer> secondList = map.get(secondWinner); int biggestSecondElement = secondList.get(secondList.size() - 1); int index = ~Collections.binarySearch(map.get(firstWinner), biggestSecondElement); out.println(firstWinner + " " + map.get(firstWinner).get(index)); } else { ArrayList<Integer> firstList = map.get(firstWinner); int biggestFirstElement = firstList.get(firstList.size() - 1); int index = ~Collections.binarySearch(map.get(secondWinner), biggestFirstElement); out.println(secondWinner + " " + map.get(secondWinner).get(index)); } } } out.close(); } public static PrintWriter out; 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(); } } }
Java
["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"]
2 seconds
["2 100000\n1 10\n3 1000", "0 0\n1 10"]
NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10 000 2 100 000 Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1 000 3 1 000 000 The winner is participant 3 with the bid 1 000.
Java 8
standard input
[ "data structures", "binary search" ]
33ec0c97192b7b9e2ebff32f8ea4681c
The first line of the input contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109, bi &lt; bi + 1)Β β€” the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≀ q ≀ 200 000)Β β€” the number of question you have in mind. Each of next q lines contains an integer k (1 ≀ k ≀ n), followed by k integers lj (1 ≀ lj ≀ n)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.
2,000
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
standard output
PASSED
152e4923b53d0dcecff62d8453ac33fe
train_002.jsonl
1521905700
An atom of element X can exist in n distinct states with energies E1 &lt; E2 &lt; ... &lt; En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i &lt; j &lt; k. After that the following process happens: initially the atom is in the state i, we spend Ek - Ei energy to put the atom in the state k, the atom emits a photon with useful energy Ek - Ej and changes its state to the state j, the atom spontaneously changes its state to the state i, losing energy Ej - Ei, the process repeats from step 1. Let's define the energy conversion efficiency as , i.Β e. the ration between the useful energy of the photon and spent energy.Due to some limitations, Arkady can only choose such three states that Ek - Ei ≀ U.Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class tlevelLaserTPointer { static int n, u; static int[] energies; public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); n = Integer.parseInt(st.nextToken()); u = Integer.parseInt(st.nextToken()); st = new StringTokenizer(in.readLine()); energies = new int[n]; for(int i = 0; i < n; i++){ energies[i] = Integer.parseInt(st.nextToken()); } in.close(); BigDecimal ans = BigDecimal.ONE.negate(); //Calculation: BigDecimal energy = BigDecimal.valueOf(energies[r] - energies[i + 1]).divide(BigDecimal.valueOf(energies[r] - energies[i]), 20, RoundingMode.UP); int k = 0; for(int i = 0; i < n - 1; i++){ k = Math.max(k, i); while(k < n && energies[k] - energies[i] <= u){ k++; } k--; if(k == i || k == i + 1){ continue; } BigDecimal amount = BigDecimal.valueOf(energies[k] - energies[i + 1]).divide(BigDecimal.valueOf(energies[k] - energies[i]), 20, RoundingMode.UP); if(amount.compareTo(ans) > 0){ ans = amount; } } System.out.print(ans); } }
Java
["4 4\n1 3 5 7", "10 8\n10 13 15 16 17 19 20 22 24 25", "3 1\n2 5 10"]
1 second
["0.5", "0.875", "-1"]
NoteIn the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to .In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to .
Java 11
standard input
[ "two pointers", "binary search", "greedy" ]
74ed99af5a5ed51c73d68f7d4ff2c70e
The first line contains two integers n and U (3 ≀ n ≀ 105, 1 ≀ U ≀ 109) β€” the number of states and the maximum possible difference between Ek and Ei. The second line contains a sequence of integers E1, E2, ..., En (1 ≀ E1 &lt; E2... &lt; En ≀ 109). It is guaranteed that all Ei are given in increasing order.
1,600
If it is not possible to choose three states that satisfy all constraints, print -1. Otherwise, print one real number Ξ·Β β€” the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10 - 9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .
standard output
PASSED
ecc73627a0dc10e8cc97090cbb28747e
train_002.jsonl
1521905700
An atom of element X can exist in n distinct states with energies E1 &lt; E2 &lt; ... &lt; En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i &lt; j &lt; k. After that the following process happens: initially the atom is in the state i, we spend Ek - Ei energy to put the atom in the state k, the atom emits a photon with useful energy Ek - Ej and changes its state to the state j, the atom spontaneously changes its state to the state i, losing energy Ej - Ei, the process repeats from step 1. Let's define the energy conversion efficiency as , i.Β e. the ration between the useful energy of the photon and spent energy.Due to some limitations, Arkady can only choose such three states that Ek - Ei ≀ U.Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints.
256 megabytes
import java.io.*; import java.util.*; public class Main { static class PairComparator implements Comparator<Pair> { @Override public int compare(Pair x, Pair y) { if (x.val < y.val) return -1; if (x.val > y.val) return 1; if (x.val == y.val) { if (x.ind < y.ind) return -1; if (x.ind > y.ind) return 1; } return 0; } } static class Pair { int ind, val; Pair(int i, int v) { ind = i; val = v; } } static int[] vis; static long sum=0; static boolean dfs(int curr, List<Integer >[] tree, int minV, int[] p){ if (p[curr]==-1){ int minCurr = Integer.MAX_VALUE; for (int i=0;i<tree[curr].size();i++){ minCurr = Math.min(minCurr, p[tree[curr].get(i)]); } p[curr] = minCurr; } if (p[curr]<minV)return false; if (p[curr]!=Integer.MAX_VALUE)sum+=p[curr] - minV; for (int i=0;i<tree[curr].size();i++){ if (!dfs(tree[curr].get(i), tree, p[curr]==-1?minV:p[curr], p)){ return false; } } return true; } static void func() throws Exception { int n = sc.nextInt(); int u = sc.nextInt(); int[] arr = sc.intArr(n); Arrays.sort(arr); TreeSet<Integer > set = new TreeSet<>(); for (int i=0;i<n;i++){ set.add(arr[i]); } double maxE = 0; for (int i=0;i<n-2;i++){ int Ei = arr[i]; int Ej = arr[i+1]; int Ek = set.lower(Ei+u+1); if (Ek!=Ej){ double eff = (double)(Ek-Ej)/(double)(Ek-Ei); maxE = Math.max(eff,maxE); } } if (maxE==0)pw.println(-1); else pw.println(maxE); } /* * */ static PrintWriter pw; static MScanner sc; public static void main(String[] args) throws Exception { pw = new PrintWriter(System.out); sc = new MScanner(System.in); int tests = 1; // tests =sc.nextInt(); //comment this line while (tests-- > 0) { func(); pw.flush(); } } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public long[] longArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[] in = new Integer[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[] in = new Long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void shuffle(int[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * (i + 1)); int tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } static void shuffle(long[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * (i + 1)); long tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } }
Java
["4 4\n1 3 5 7", "10 8\n10 13 15 16 17 19 20 22 24 25", "3 1\n2 5 10"]
1 second
["0.5", "0.875", "-1"]
NoteIn the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to .In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to .
Java 11
standard input
[ "two pointers", "binary search", "greedy" ]
74ed99af5a5ed51c73d68f7d4ff2c70e
The first line contains two integers n and U (3 ≀ n ≀ 105, 1 ≀ U ≀ 109) β€” the number of states and the maximum possible difference between Ek and Ei. The second line contains a sequence of integers E1, E2, ..., En (1 ≀ E1 &lt; E2... &lt; En ≀ 109). It is guaranteed that all Ei are given in increasing order.
1,600
If it is not possible to choose three states that satisfy all constraints, print -1. Otherwise, print one real number Ξ·Β β€” the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10 - 9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .
standard output
PASSED
b22f1667024e4959629a2f0118bac7cc
train_002.jsonl
1521905700
An atom of element X can exist in n distinct states with energies E1 &lt; E2 &lt; ... &lt; En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i &lt; j &lt; k. After that the following process happens: initially the atom is in the state i, we spend Ek - Ei energy to put the atom in the state k, the atom emits a photon with useful energy Ek - Ej and changes its state to the state j, the atom spontaneously changes its state to the state i, losing energy Ej - Ei, the process repeats from step 1. Let's define the energy conversion efficiency as , i.Β e. the ration between the useful energy of the photon and spent energy.Due to some limitations, Arkady can only choose such three states that Ek - Ei ≀ U.Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class ThreeLevelLaser942B { /* 1) keep an int[] of the max Ek selected for the particular value as Ei 1. back-to-front, while the cur. val of Ek works, continue 2. else binary search to find the max value possible 2) for (int i = 0; i < m.length-1; i++) max(bin[i]-val[i+1]/val[i]) */ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int u = Integer.parseInt(st.nextToken()); int[] vals = new int[n]; st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) vals[i] = Integer.parseInt(st.nextToken()); int[] maxEk = new int[n]; Arrays.fill(maxEk, -1); int cont = vals[n-1]; for (int i = n-1; i >= 0; i--){ if (vals[i] + u < cont || cont==-1) cont = binary(i, u, vals); maxEk[i] = cont; } double max = -1; for (int i = 0; i < n-1; i++){ if (maxEk[i]==-1 || maxEk[i]==vals[i+1]) continue; double r = (double)(maxEk[i]-vals[i+1])/(double)(maxEk[i]-vals[i]); max = Math.max(max, r); } pw.println(max); br.close(); pw.flush(); } private static int binary(int i, int u, int[] vals){ int res = -1; int li = i, hi = vals.length-1; while (li<=hi){ int mi = li + (hi-li)/2; if (vals[mi]>vals[i]+u)hi = mi-1; else{ res = Math.max(res, mi); li = mi+1; } } return res == -1 ? -1 : vals[res]; } }
Java
["4 4\n1 3 5 7", "10 8\n10 13 15 16 17 19 20 22 24 25", "3 1\n2 5 10"]
1 second
["0.5", "0.875", "-1"]
NoteIn the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to .In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to .
Java 11
standard input
[ "two pointers", "binary search", "greedy" ]
74ed99af5a5ed51c73d68f7d4ff2c70e
The first line contains two integers n and U (3 ≀ n ≀ 105, 1 ≀ U ≀ 109) β€” the number of states and the maximum possible difference between Ek and Ei. The second line contains a sequence of integers E1, E2, ..., En (1 ≀ E1 &lt; E2... &lt; En ≀ 109). It is guaranteed that all Ei are given in increasing order.
1,600
If it is not possible to choose three states that satisfy all constraints, print -1. Otherwise, print one real number Ξ·Β β€” the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10 - 9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .
standard output
PASSED
4713c1a0150713b8cbcfbbe5868dc492
train_002.jsonl
1520696100
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times: A BC B AC C AB AAA empty string Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Vadim Semenov */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static final class TaskD { public void solve(int __, InputReader in, PrintWriter out) { char[] fst = in.next().toCharArray(); char[] snd = in.next().toCharArray(); int[] af = calcOne(fst); int[] as = calcOne(snd); int[] sumf = calcParity(fst); int[] sums = calcParity(snd); int queries = in.nextInt(); for (int q = 0; q < queries; ++q) { int l1 = in.nextInt(); int r1 = in.nextInt(); int l2 = in.nextInt(); int r2 = in.nextInt(); // count of A at suffix int fstSuffix = Math.min(r1 - l1 + 1, af[r1]); int sndSuffix = Math.min(r2 - l2 + 1, as[r2]); // count of B and C in substring int fstQty = sumf[r1] - sumf[l1 - 1]; int sndQty = sums[r2] - sums[l2 - 1]; boolean possible = true; if (fstSuffix < sndSuffix) { possible = false; } else { boolean canAdd = false; if (fstSuffix > sndSuffix) { canAdd = true; if (fstSuffix % 3 != sndSuffix % 3) { fstQty += 2; // apply A -> BC } } // now endings are same if (fstQty > sndQty || (fstQty == 0 && sndQty != 0 && !canAdd)) { possible = false; // cannot delete B or C, cannot crete from nowhere } else if (fstQty % 2 != sndQty % 2) { possible = false; // only A -> BC transformation } } out.print(possible ? "1" : "0"); } out.println(); } private int[] calcOne(char[] string) { int[] a = new int[string.length + 1]; for (int i = 1; i <= string.length; ++i) { if (string[i - 1] == 'A') { a[i] = 1 + a[i - 1]; } } return a; } private int[] calcParity(char[] string) { int[] sum = new int[string.length + 1]; for (int i = 1; i <= string.length; ++i) { sum[i] = sum[i - 1]; if (string[i - 1] != 'A') { sum[i]++; } } return sum; } } static class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readLine()); } return tokenizer.nextToken(); } public String readLine() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
Java
["AABCCBAAB\nABCB\n5\n1 3 1 2\n2 2 2 4\n7 9 1 1\n3 4 2 3\n4 5 1 3"]
2 seconds
["10011"]
NoteIn the first query we can achieve the result, for instance, by using transitions .The third query asks for changing AAB to AΒ β€” but in this case we are not able to get rid of the character 'B'.
Java 8
standard input
[ "constructive algorithms", "implementation", "strings" ]
98e3182f047a7e7b10be7f207b219267
The first line contains a string S (1 ≀ |S| ≀ 105). The second line contains a string T (1 ≀ |T| ≀ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'. The third line contains the number of queries Q (1 ≀ Q ≀ 105). The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times? Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U. It is guaranteed that 1 ≀ a ≀ b ≀ |S| and 1 ≀ c ≀ d ≀ |T|.
2,500
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
standard output
PASSED
b808e572f0a4986741e3c9f570e3aea9
train_002.jsonl
1520696100
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times: A BC B AC C AB AAA empty string Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); // Start ------------------------------------- String s = sc.nextLine(),t = sc.nextLine(); int l= s.length(),k= t.length(); int[] total_S = new int [l+10]; int[] total_T = new int [k+10]; int[] lastB_S = new int [l+10]; int[] lastB_T = new int [k+10]; total_S[0]=0; total_T[0]=0; lastB_S[0]=0; lastB_T[0]=0; for(int i=0; i<l; ++i) { if(s.charAt(i)== 'A') { total_S[i+1] = total_S[i]+1; lastB_S[i+1]=lastB_S[i]; }else{ total_S[i+1]=total_S[i]; lastB_S[i+1]=i+1; } } for(int i=0; i<k; ++i) { if(t.charAt(i)== 'A') { total_T[i+1] = total_T[i]+1; lastB_T[i+1]= lastB_T[i]; }else{ total_T[i+1]=total_T[i]; lastB_T[i+1]=i+1; } } int q=sc.nextInt(),a,b,c,d; char[] ans= new char [q]; for(int i=0;i<q;++i) { a=sc.nextInt();b=sc.nextInt();c=sc.nextInt();d=sc.nextInt(); int x=total_S[b]-total_S[a-1],y=total_T[d]-total_T[c-1]; int tx=b-Math.max(a-1, lastB_S[b]),ty=d-Math.max(c-1, lastB_T[d]); // if(s.charAt(b-1)!='A') tx=0; // if(t.charAt(d-1)!='A') ty=0; //out.println(x+" X "+y+" Y "+tx+" T "+ty); if((b-a-x-d+c+y)%2!=0) { ans[i]='0'; continue; } if(b-a+1-x==d-c+1-y) { if (ty>tx || (tx-ty)%3!=0 ) { ans[i]='0'; }else { ans[i]='1'; } }else if(b-a+1==x) { if(tx>ty) { ans[i]='1'; }else { ans[i]='0'; } }else if(b-a-x<d-c-y){ if(ty>tx) { ans[i]='0'; }else ans[i]='1'; }else { ans[i]='0'; } } out.println(ans); // End ------------------------------------- out.close(); } //-----------IO--------------------------------- public static PrintWriter out; 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
["AABCCBAAB\nABCB\n5\n1 3 1 2\n2 2 2 4\n7 9 1 1\n3 4 2 3\n4 5 1 3"]
2 seconds
["10011"]
NoteIn the first query we can achieve the result, for instance, by using transitions .The third query asks for changing AAB to AΒ β€” but in this case we are not able to get rid of the character 'B'.
Java 8
standard input
[ "constructive algorithms", "implementation", "strings" ]
98e3182f047a7e7b10be7f207b219267
The first line contains a string S (1 ≀ |S| ≀ 105). The second line contains a string T (1 ≀ |T| ≀ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'. The third line contains the number of queries Q (1 ≀ Q ≀ 105). The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times? Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U. It is guaranteed that 1 ≀ a ≀ b ≀ |S| and 1 ≀ c ≀ d ≀ |T|.
2,500
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
standard output
PASSED
d2a2c50bd8585a482f5bbe69b6441cd5
train_002.jsonl
1520696100
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times: A BC B AC C AB AAA empty string Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
256 megabytes
import java.io.*; import java.util.*; public class Main { public Main() throws IOException { } static void solve() throws IOException { String s = input.readLine(); String t = input.readLine(); rl(); int n = ni2(); int ls = s.length(); int lt = t.length(); int count_s[] = new int[ls]; // count the numbers of B and C in S int count_t[] = new int[lt]; for (int i = 0; i < ls; i++) { if (s.charAt(i) == 'B' || s.charAt(i) == 'C') { if (i == 0) count_s[i] = 1; else count_s[i] = count_s[i - 1] + 1; } else { if (i == 0) count_s[i] = 0; else count_s[i] = count_s[i - 1]; } } for (int i = 0; i < lt; i++) { if (t.charAt(i) == 'B' || t.charAt(i) == 'C') { if (i == 0) count_t[i] = 1; else count_t[i] = count_t[i - 1] + 1; } else { if (i == 0) count_t[i] = 0; else count_t[i] = count_t[i - 1]; } } int nearest_bs[] = new int[ls]; int nearest_bt[] = new int[lt]; for (int i = 0; i < ls; i++) { if (s.charAt(i) == 'B' || s.charAt(i) == 'C') { nearest_bs[i] = i; } else { if (i == 0) nearest_bs[i] = -1; else nearest_bs[i] = nearest_bs[i - 1]; } } for (int i = 0; i < lt; i++) { if (t.charAt(i) == 'B' || t.charAt(i) == 'C') { nearest_bt[i] = i; } else { if (i == 0) nearest_bt[i] = -1; else nearest_bt[i] = nearest_bt[i - 1]; } } for (int i = 0; i < n; i++) { rl(); int a = ni2() - 1, b = ni2() - 1, c = ni2() - 1, d = ni2() - 1; int bs = a > 0 ? count_s[b] - count_s[a - 1] : count_s[b]; int bt = c > 0 ? count_t[d] - count_t[c - 1] : count_t[d]; int as = Math.min(b - nearest_bs[b], b - a + 1); int at = Math.min(d - nearest_bt[d], d - c + 1); if (bs > bt) ans.append("0"); else if (bs == bt) { if (as >= at & (as - at) % 3 == 0) ans.append("1"); else ans.append("0"); } else { if ((bt - bs) % 2 != 0) ans.append("0"); else { if (bs == 0) { if (as > at) ans.append("1"); else ans.append("0"); } else { if (as >= at) ans.append("1"); else ans.append("0"); } } } } output.write(ans.toString()); output.flush(); output.close(); } public static void main(String[] args) throws IOException { new Main().solve(); } static BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); static StringBuilder ans = new StringBuilder(); static StringTokenizer stringTokenizer; static int ni1() throws IOException { return Integer.parseInt(input.readLine()); } static int ni2() throws IOException { return Integer.parseInt(stringTokenizer.nextToken()); } static long nl1() throws IOException { return Long.parseLong(input.readLine()); } static long nl2() { return Long.parseLong(stringTokenizer.nextToken()); } static void rl() throws IOException { stringTokenizer = new StringTokenizer(input.readLine()); } }
Java
["AABCCBAAB\nABCB\n5\n1 3 1 2\n2 2 2 4\n7 9 1 1\n3 4 2 3\n4 5 1 3"]
2 seconds
["10011"]
NoteIn the first query we can achieve the result, for instance, by using transitions .The third query asks for changing AAB to AΒ β€” but in this case we are not able to get rid of the character 'B'.
Java 8
standard input
[ "constructive algorithms", "implementation", "strings" ]
98e3182f047a7e7b10be7f207b219267
The first line contains a string S (1 ≀ |S| ≀ 105). The second line contains a string T (1 ≀ |T| ≀ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'. The third line contains the number of queries Q (1 ≀ Q ≀ 105). The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times? Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U. It is guaranteed that 1 ≀ a ≀ b ≀ |S| and 1 ≀ c ≀ d ≀ |T|.
2,500
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
standard output
PASSED
b66cdbebd9425eee60855f8cc8e52631
train_002.jsonl
1520696100
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times: A BC B AC C AB AAA empty string Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
256 megabytes
import java.io.BufferedReader; // import java.io.FileInputStream; // import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import static java.lang.Math.min; import static java.util.Arrays.copyOf; import static java.util.Arrays.fill; import static java.util.Arrays.sort; import static java.util.Collections.reverseOrder; import static java.util.Collections.sort; public class Main { FastScanner in; PrintWriter out; private void solve() throws IOException { char[] s = in.next().toCharArray(); int[] prefS = new int[s.length + 1]; int[] suffS = new int[s.length + 1]; for (int i = 0; i < s.length; i++) { prefS[i + 1] = prefS[i] + (s[i] != 'A' ? 1 : 0); suffS[i + 1] = s[i] == 'A' ? suffS[i] + 1 : 0; } char[] t = in.next().toCharArray(); int[] prefT = new int[t.length + 1]; int[] suffT = new int[t.length + 1]; for (int i = 0; i < t.length; i++) { prefT[i + 1] = prefT[i] + (t[i] != 'A' ? 1 : 0); suffT[i + 1] = t[i] == 'A' ? suffT[i] + 1 : 0; } int sl, sr, tl, tr; int cntS, cntT; int sufS, sufT; for (int q = in.nextInt(); q-- > 0; ) { sl = in.nextInt(); sr = in.nextInt(); tl = in.nextInt(); tr = in.nextInt(); cntS = prefS[sr] - prefS[sl - 1]; cntT = prefT[tr] - prefT[tl - 1]; if (cntS > cntT || cntS % 2 != cntT % 2) out.print(0); else { sufS = min(suffS[sr], sr - sl + 1); sufT = min(suffT[tr], tr - tl + 1); if (sufS > sufT) out.print(cntS < cntT ? 1 : (sufS - sufT) % 3 == 0 ? 1 : 0); else out.print(sufS == sufT && (sufS < sr - sl + 1 || cntS == cntT) ? 1 : 0); } } } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next().replace(',', '.')); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["AABCCBAAB\nABCB\n5\n1 3 1 2\n2 2 2 4\n7 9 1 1\n3 4 2 3\n4 5 1 3"]
2 seconds
["10011"]
NoteIn the first query we can achieve the result, for instance, by using transitions .The third query asks for changing AAB to AΒ β€” but in this case we are not able to get rid of the character 'B'.
Java 8
standard input
[ "constructive algorithms", "implementation", "strings" ]
98e3182f047a7e7b10be7f207b219267
The first line contains a string S (1 ≀ |S| ≀ 105). The second line contains a string T (1 ≀ |T| ≀ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'. The third line contains the number of queries Q (1 ≀ Q ≀ 105). The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times? Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U. It is guaranteed that 1 ≀ a ≀ b ≀ |S| and 1 ≀ c ≀ d ≀ |T|.
2,500
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
standard output
PASSED
1c0a81132063e4757784956b443372d7
train_002.jsonl
1520696100
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times: A BC B AC C AB AAA empty string Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
256 megabytes
import java.io.*; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { String filename = ""; if (!filename.isEmpty()) { in = new BufferedReader(new FileReader(filename + ".in")); out = new PrintWriter(filename + ".out"); } else { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long[] readLongArray(int size) throws IOException { long[] res = new long[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Template().run(); // new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } int[] pref(char[] a) { int[] p = new int[a.length + 1]; for (int i = 0; i < a.length; i++) { p[i + 1] = p[i] + (a[i] != 'A' ? 1 : 0); } return p; } int[] coutnA(char[] a) { int[] cnt = new int[a.length + 1]; for (int i = 0; i < a.length; i++) { if (a[i] == 'A') { cnt[i + 1] = cnt[i] + 1; } else { cnt[i + 1] = 0; } } return cnt; } private void solve() throws IOException { char[] s = readString().toCharArray(); char[] t = readString().toCharArray(); int[] prefS = pref(s); int[] prefT = pref(t); int[] cntAS = coutnA(s); int[] cntAT = coutnA(t); int m = readInt(); for (int i = 0; i < m; i++) { int a = readInt(), b = readInt(), c = readInt(), d = readInt(); int cntBS = prefS[b] - prefS[a - 1]; int cntBT = prefT[d] - prefT[c - 1]; int len1 = b - a + 1; int len2 = d - c + 1; out.print(solve(cntBS, cntBT, Math.min(len1, cntAS[b]), Math.min(cntAT[d], len2))); } } int solve(int cntBS, int cntBT, int cntAS, int cntAT) { if (cntBS % 2 != cntBT % 2) return 0; if (cntBS > cntBT) return 0; if (cntBS == cntBT) { if (cntAS == cntAT) return 1; if (cntAS < cntAT) return 0; return (cntAS - cntAT) % 3 == 0 ? 1 : 0; } if (cntBS == 0) { if (cntAS - 1 < cntAT) return 0; } if (cntAS < cntAT) return 0; return 1; } }
Java
["AABCCBAAB\nABCB\n5\n1 3 1 2\n2 2 2 4\n7 9 1 1\n3 4 2 3\n4 5 1 3"]
2 seconds
["10011"]
NoteIn the first query we can achieve the result, for instance, by using transitions .The third query asks for changing AAB to AΒ β€” but in this case we are not able to get rid of the character 'B'.
Java 8
standard input
[ "constructive algorithms", "implementation", "strings" ]
98e3182f047a7e7b10be7f207b219267
The first line contains a string S (1 ≀ |S| ≀ 105). The second line contains a string T (1 ≀ |T| ≀ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'. The third line contains the number of queries Q (1 ≀ Q ≀ 105). The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times? Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U. It is guaranteed that 1 ≀ a ≀ b ≀ |S| and 1 ≀ c ≀ d ≀ |T|.
2,500
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
standard output
PASSED
4a032760abb4bc77979872d670226210
train_002.jsonl
1520696100
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times: A BC B AC C AB AAA empty string Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
256 megabytes
import java.util.*; import java.io.*; public class D { FastScanner in; PrintWriter out; boolean systemIO = true; public static void quickSort(int[] a, int from, int to) { if (to - from <= 1) { return; } int i = from; int j = to - 1; int x = a[from + (new Random()).nextInt(to - from)]; while (i <= j) { while (a[i] < x) { i++; } while (a[j] > x) { j--; } if (i <= j) { int t = a[i]; a[i] = a[j]; a[j] = t; i++; j--; } } quickSort(a, from, j + 1); quickSort(a, j + 1, to); } public class Pair { int x; int y; int time; public Pair(int x, int y, int time) { super(); this.x = x; this.y = y; this.time = time; } } public void solve() { String s = in.next(); String t = in.next(); int[] a1 = new int[s.length() + 1]; int[] c1 = new int[s.length() + 1]; int[] a2 = new int[t.length() + 1]; int[] c2 = new int[t.length() + 1]; for (int i = 0; i < s.length(); i++) { c1[i + 1] = c1[i]; if (s.charAt(i) == 'A') { a1[i + 1] = a1[i] + 1; } else { c1[i + 1]++; } } for (int i = 0; i < t.length(); i++) { c2[i + 1] = c2[i]; if (t.charAt(i) == 'A') { a2[i + 1] = a2[i] + 1; } else { c2[i + 1]++; } } int q = in.nextInt(); for (int i = 0; i < q; i++) { int l1 = in.nextInt() - 1; int r1 = in.nextInt() - 1; int l2 = in.nextInt() - 1; int r2 = in.nextInt() - 1; int n1 = Math.min(r1 - l1 + 1, a1[r1 + 1]); int n2 = Math.min(r2 - l2 + 1, a2[r2 + 1]); int b1 = c1[r1 + 1] - c1[l1]; int b2 = c2[r2 + 1] - c2[l2]; if (n2 > n1) { out.print(0); continue; } n1 -= n2; if (b1 == 0) { if (b2 == 0) { if (n1 % 3 == 0) { out.print(1); } else { out.print(0); } continue; } else { if (n1 == 0) { out.print(0); continue; } b1 = 2; n1 = 0; if (b2 >= b1 && (b2 - b1) % 2 == 0) { out.print(1); } else { out.print(0); } continue; } } else { if (n1 % 3 != 0) { b1 += 2; } if (b2 >= b1 && (b2 - b1) % 2 == 0) { out.print(1); } else { out.print(0); } continue; } } } public void run() { try { if (systemIO) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); } solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA public static void main(String[] args) { new D().run(); } }
Java
["AABCCBAAB\nABCB\n5\n1 3 1 2\n2 2 2 4\n7 9 1 1\n3 4 2 3\n4 5 1 3"]
2 seconds
["10011"]
NoteIn the first query we can achieve the result, for instance, by using transitions .The third query asks for changing AAB to AΒ β€” but in this case we are not able to get rid of the character 'B'.
Java 8
standard input
[ "constructive algorithms", "implementation", "strings" ]
98e3182f047a7e7b10be7f207b219267
The first line contains a string S (1 ≀ |S| ≀ 105). The second line contains a string T (1 ≀ |T| ≀ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'. The third line contains the number of queries Q (1 ≀ Q ≀ 105). The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times? Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U. It is guaranteed that 1 ≀ a ≀ b ≀ |S| and 1 ≀ c ≀ d ≀ |T|.
2,500
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
standard output
PASSED
7f73ceecfa15d88976444e6926735eca
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import static java.lang.System.in; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.util.AbstractList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import static java.util.Collections.list; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.Stream; import javax.xml.stream.events.Characters; import sun.security.util.Length; /** * * @author george */ public class main { public static boolean isPrime(long n) { if(n < 2) return false; if(n == 2 || n == 3) return true; if(n%2 == 0 || n%3 == 0) return false; long sqrtN = (long)Math.sqrt(n)+1; for(long i = 6L; i <= sqrtN; i += 6) { if(n%(i-1) == 0 || n%(i+1) == 0) return false; } return true; } private static long f(long l) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } static public class Princess{ public int rate;public int beauty;public int intellect;public int richness; public Princess(int sum,int a,int b,int c){ this.rate=sum; this.beauty=a; this.intellect=b; this.richness=c; } @Override public String toString() { return "Princess{" + "rate=" + rate + ", beauty=" + beauty + ", intellect=" + intellect + ", richness=" + richness + '}'; } } public static boolean contains(final int[] arr, final int key) { return Arrays.stream(arr).anyMatch(i -> i == key); } static boolean isSubSequence(String str1, String str2, int m, int n) { if (m == 0) return true; if (n == 0) return false; if (str1.charAt(m-1) == str2.charAt(n-1)) return isSubSequence(str1, str2, m-1, n-1); return isSubSequence(str1, str2, m, n-1); } static int gcdThing(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } public static boolean checkAnagram(String str1, String str2) { int i=0; for (char c : str1.toCharArray()) { i = str2.indexOf(c, i) + 1; if (i <= 0) { return false; } } return true; } /* Amusing Joke String a,b,c; a=s.next();b=s.next();c=s.next(); if((a.length()+b.length())!=c.length()){System.out.print("here");System.out.print("NO");} else{ boolean x= true; String agex=""; if(checkAnagram(a, c)==false){System.out.print("here1");x=false;} else{ char [] g=a.toCharArray(); Arrays.sort(g);String ge=new String(g);a=ge; g=b.toCharArray();Arrays.sort(g);ge=new String(b);b=ge; g=c.toCharArray();Arrays.sort(g);ge=new String(c);c=ge; if(isSubSequence(a, c, a.length(), c.length())){ StringBuilder sb = new StringBuilder(c);String temp=""; for (int i = 0; i < a.length(); i++) { temp+=a.charAt(i); c.replaceFirst(temp, "");temp=""; } } else{x=false;} if(isSubSequence(a, c, a.length(), c.length())){ StringBuilder sb = new StringBuilder(c); for (int i = 0; i < b.length(); i++) { String temp=""; temp+=b.charAt(i); c.replaceFirst(temp, "");temp=""; } } else{x=false;} if(c.length()!=0){x=false;} }if(x==false){System.out.print("NO");} else{System.out.print("YES");} } */ /*//t,l,r long t,l,r;t=s.nextLong();l=s.nextLong();r=s.nextLong(); long exp=0; // t0Β·f(l) + t1Β·f(l + 1) + ... + tr - lΒ·f(r). for (int i = 0; i <=r-l; i++) { exp+=((long)(Math.pow(t, i)))*f(l+i); } System.out.print(exp%(1000000007));*/ /* 489C int digits=s.nextInt();int sum=s.nextInt(); List <Integer>li=new ArrayList<Integer>(); int digitss=sum/9; int rem=digits%9; String z=String.join("", Collections.nCopies(digitss, "9")); String z+= String digit="9"; String x = String.join("", Collections.nCopies(digits, "9")); BigInteger num=BigInteger.valueOf(Long.parseLong(x)); x=num.toString();System.out.print(x); li.clear(); for (int i = 0; i < x.length(); i++) { li.add(x.charAt(i)-48); } Collections.sort(li); int zeros=0; //leading zeros String f=""; for (int i = 0; i < li.size(); i++) { if(li.get(0)==0){zeros++;li.remove(0);} else{f=li.get(0).toString(); break;} } String y=""; if(zeros!=0){ li.remove(0); y+=String.join("", Collections.nCopies(zeros, "0")); } y+=li.stream().map(Object::toString).collect(Collectors.joining()); System.out.print(y);System.out.print(" ");System.out.print(x); */ public static List primeFactors(Long num) { List<Long>Prime=new ArrayList<Long>(); // Print the number of 2s that divide n long tw=2; while (num%2==0) { Prime.add(tw); num /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (long i = 3; i <= Math.sqrt(num); i+= 2) { // While i divides n, print i and divide n while (num%i == 0) { Prime.add(i); num/= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (num> 2) Prime.add(num); return Prime; } public static String Winner(int [] arr) { int maxsum=-1; int temp=0; List<Integer> L=Arrays.stream(arr).boxed().collect(Collectors.toList()); int count=0; String winner="First"; while(L.isEmpty()!=true){ if(count%2==0){winner="First"; //take max odd interval for (int i = 0; i < L.size(); i++) { } } else{winner="Second"; } count++; } return winner; } public static String changeCharInPosition(int position, char ch, String str){ char[] charArray = str.toCharArray(); charArray[position] = ch; return new String(charArray); } /*int n=s.nextInt(); String x=s.next(); int k=s.nextInt(); int [] ind=new int[k]; char [] cho=new char[k]; String help; for (int i = 0; i < k; i++) { help=""; ind[i]=s.nextInt(); help=s.next(); cho[i]=help.charAt(0); } String substring=""; int maxcount=1; int tempcount=0; int occChar=0; help=""; for (int i = 0; i < k; i++) { substring=""; help=""; help+=cho[i]; occChar=x.length() - x.replace(help, "").length(); if((occChar+ind[i])>=n){System.out.println(n);continue;} for (int j = 0; j < n; j++) { if(x.charAt(j)!=cho[i]){continue;} for (int l = j+1; l < n; l++) { if(x.charAt(l)==cho[i]){substring=x.substring(j, l+1);System.out.println(substring); help="";help+=cho[i]; occChar=substring.length() - substring.replace(help, "").length(); tempcount=substring.length()-occChar; if(substring.length()>maxcount&&tempcount<=ind[i]){maxcount=tempcount;tempcount=0;} } } } // System.out.println(maxcount);maxcount=0; }*/ public static boolean CheckCanObtainYfromX(String y,String x){ boolean cond=true; String help=""; for (int i = 0; i < y.length(); i++) { help="";help+=y.charAt(i); if(y.contains(help)==false){x=x.replaceFirst(help,"A");cond=false;break;} } return cond; } public static int LongestPalindrome(String x){ int n=x.length(); boolean table[][] = new boolean[n][n]; int maxLength = 1; for (int i = 0; i < n; ++i) table[i][i] = true; int start = 0; for (int i = 0; i < n - 1; ++i) { if (x.charAt(i) == x.charAt(i + 1)) { table[i][i + 1] = true; start = i; maxLength = 2; } } for (int k = 3; k <= n; ++k) { for (int i = 0; i < n - k + 1; ++i) { int j = i + k - 1; if (table[i + 1][j - 1] && x.charAt(i) == x.charAt(j)) { table[i][j] = true; if (k > maxLength) { start = i; maxLength = k; } } } } return maxLength; } public static void main (String [] args) throws IOException { Scanner s=new Scanner(System.in); String x=s.next(); int k=s.nextInt(); int [] yes=new int[x.length()]; yes[0]=0; int [] arr=new int[k]; int [] l=new int[k]; int [] r=new int[k]; for (int i=1, j= 0,z=j+1; j < x.length()-1; j++,z++) { if(x.charAt(j)==x.charAt(z)){yes[i]=(yes[i-1]+1);i++;} else{yes[i]=yes[i-1];i++;} } for (int i = 0; i< k; i++) { l[i]=s.nextInt(); r[i]=s.nextInt(); } for (int i = 0; i < k; i++) { System.out.println(yes[r[i]-1]-yes[l[i]-1]); } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
e28c6481596de6b637eb6b24c9da3843
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.util.Scanner; public class IlyaandQueries_B { public static void main(String[] args) { Scanner console=new Scanner(System.in); String str=console.next(); int m=console.nextInt(); int arr[][]=new int[m][2]; int same[]=new int[str.length()]; int sum[]=new int[m]; int i,j; for(i=0;i<m;i++) for(j=0;j<2;j++) arr[i][j]=console.nextInt(); char a[]=str.toCharArray(); for(i=0;i<a.length-1;i++) if(a[i]==a[i+1]) {if(i==0) same[i]=1; else same[i]=same[i-1]+1;} else {if(i==0) same[i]=0; else same[i]=same[i-1];} same[a.length-1]=same[a.length-2]; for(i=0;i<m;i++) if(arr[i][0]-1==0) sum[i]=same[arr[i][1]-2]; else if((arr[i][1]-1)-(arr[i][0]-1)==1) {if(a[arr[i][0]-1]==a[arr[i][0]]) sum[i]=1;} else sum[i]=same[arr[i][1]-2]-same[arr[i][0]-2]; for(i=0;i<sum.length;i++) System.out.println(sum[i]); } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
85df31610c17335bf0de23def2baa643
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.util.Scanner; public class ilya { public static void main(String[] args) { EingabeReader reader = new EingabeReader(); String s = reader.nextString(); int testCases = reader.readInt(); int[] dp = new int[s.length()]; int sum = 0, index =1; for(int i = 1; i < s.length();i++) { if(s.charAt(i) == s.charAt(i-1)) dp[i] = dp[i-1] +1; else dp[i] = dp[i-1]; } outer: for(int tt = 0; tt < testCases;tt++) { int l = reader.readInt()-1, r = reader.readInt()-1; System.out.println(dp[r]-dp[l]); } } static class EingabeReader { Scanner sc = null; public EingabeReader() { sc = new Scanner(System.in); } public int readInt() { return Integer.parseInt(this.nextString()); } public double readDouble() { return Double.parseDouble(this.nextString()); } public String nextString() { return sc.next(); } public double[] readDoubleArray(int n) { double[] ar = new double[n]; for(int i = 0; i < n;i++) ar[i] = this.readDouble(); return ar; } public int[] readArray(int n) { int[] ar = new int[n]; for(int i = 0; i < n;i++) ar[i] = this.readInt(); return ar; } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
9c099d6044195043bf0ecc1ef92fbd47
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) throws java.lang.Exception { Scanner in = new Scanner(System.in); String ch = in.next(); int mat[] = new int[ch.length()]; mat[0] = 0; for (int j = 1; j < ch.length(); j++) { mat[j] = mat[j-1] + ((ch.charAt(j-1) == ch.charAt(j)) ? 1 : 0); } int n = in.nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { int a = in.nextInt();a--; int b = in.nextInt();b--; sb.append(mat[b]-mat[a]).append("\n"); } System.out.println(sb); } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
51f0cfd7d6547d21ff2a39e0c9d100c9
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.util.Scanner; public class Mainho { public static void main(String args[]) { Scanner scan = new Scanner(System.in); String s = scan.next(); int n = scan.nextInt(); int[] a = new int[s.length()]; for (int i = 1; i < s.length(); i++) { a[i] = a[i - 1]; if(s.charAt(i) == s.charAt(i - 1)){ a[i]++; } } for(int i = 0; i < n; i++){ System.out.println(-1 * a[scan.nextInt() - 1] + a[scan.nextInt() - 1]); } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
480e756c1b7f90944b2a9d1b1488e5cf
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class Queries { public static void main(String[] args) throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String line=in.readLine(); int n=Integer.parseInt(in.readLine()); int l=line.length(); int[] arr=new int[l]; int k =0; for (int i = 1; i < l; i++) { // if(line.charAt(i)==line.charAt(i-1)) k++; // arr[i]=k; arr[i]=line.charAt(i)==line.charAt(i-1)?arr[i-1]+1:arr[i-1]; } for (int i = 0; i < n; i++) { String s=in.readLine(); int a=Integer.parseInt(s.substring(0, s.indexOf(" ")))-1; int b=Integer.parseInt(s.substring(s.indexOf(" ")+1))-1; System.out.println(a==0?arr[b]:arr[b]-arr[a]); } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
6b7600d0c1ea9df5ea1d20d4544de0cf
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class Queries { public static void main(String[] args) throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String line=in.readLine(); int n=Integer.parseInt(in.readLine()); int l=line.length(); int[] arr=new int[l]; int k =0; for (int i = 1; i < l; i++) { if(line.charAt(i)==line.charAt(i-1)) k++; arr[i]=k; } for (int i = 0; i < n; i++) { String s=in.readLine(); int a=Integer.parseInt(s.substring(0, s.indexOf(" ")))-1; int b=Integer.parseInt(s.substring(s.indexOf(" ")+1))-1; System.out.println(a==0?arr[b]:arr[b]-arr[a]); } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
bb5cf94f0e7ef7ca60291a6c148f2fbd
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.StreamTokenizer; import java.io.Writer; import java.util.Scanner; public class Tmp { private static Reader reader = new InputStreamReader(System.in); private static Writer writer = new OutputStreamWriter(System.out); private static StreamTokenizer in = new StreamTokenizer(new BufferedReader(reader)); private static PrintWriter out = new PrintWriter(writer); private static int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } private static String nextString() throws IOException { in.nextToken(); return in.sval; } public static void main(String[] args) throws IOException { Scanner scan = new Scanner(System.in); String s = scan.next(); int n = scan.nextInt(); int[] sum = new int[s.length()]; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == s.charAt(i - 1)) { sum[i] = sum[i - 1] + 1; } else { sum[i] = sum[i - 1]; } } int k, l; for (int i = 0; i < n; i++) { k = scan.nextInt() - 1; l = scan.nextInt() - 1; out.println(sum[l] - sum[k]); } out.flush(); } public static int[] solve(String s, int[][] a) { int[] res = new int[a.length]; int sum = 0; for (int i = 0; i < a.length; i++) { for (int j = a[i][0]; j < a[i][1] && j < s.length(); j++) { if (s.charAt(j - 1) == s.charAt(j)) { sum++; } } res[i] = sum; sum = 0; } return res; } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
45dc2ea8bf4c0847a71fc4bce4ad6cc3
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.util.*; public class CodeForces { public static void main(String args[]) { Scanner sc=new Scanner(System.in); String s=sc.next(); StringBuilder sb=new StringBuilder(); int arr[]=new int[s.length()-1]; for(int i=0;i<s.length()-1;i++) { if(s.charAt(i)==s.charAt(i+1)) { arr[i]=1; } } int n=sc.nextInt(); for(int i=1;i<s.length()-1;i++) { arr[i]+=arr[i-1]; } for(int i=0;i<n;i++) { int l=sc.nextInt(); int r=sc.nextInt(); if(l==1) { sb.append(arr[r-2]).append("\n"); } else { sb.append(arr[r-2]-arr[l-2]).append("\n"); } } String printMe = sb.toString(); System.out.println(printMe); } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
f96d65aa40eaf7ed332dc15c9a94bb1f
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String a= in.next(); int arr[] = new int[a.length()]; arr[0]=0; for(int i=1;i<a.length();i++){ if(a.charAt(i)==a.charAt(i-1)){ arr[i]= arr[i-1]+1; } else arr[i]=arr[i-1]; } int n= in.nextInt(); while(n>0){ n--; int x=in.nextInt(); int y=in.nextInt(); System.out.println(arr[y-1]-arr[x-1]); } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
2289abc51034b7cfa3545f269cf5e792
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
//import javafx.util.Pair; import javax.swing.text.MaskFormatter; import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args){ Scanner in=new Scanner(System.in); String S=in.next(); int n=S.length(); char[]s=S.toCharArray(); int dp[]=new int[n+1]; int cnt=0; for(int i=n-1;i>0;i--) { if(s[i-1]==s[i]) { cnt++; } dp[i-1]=cnt; } int t=in.nextInt(); StringBuilder res=new StringBuilder(); while (t-->0) { int l=in.nextInt(); int r=in.nextInt(); res.append((dp[l-1]-dp[r-1])+"\n"); } System.out.println(res); } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
5f71cbb0d68b6874e9d1d1f621774409
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.util.*; import java.lang.*; public class Main { public static void main (String[] args) { Scanner in = new Scanner(System.in); String s = in.nextLine(); int len = s.length(); int[] arr = new int[len]; for (int i=1; i<len; i++){ if (s.charAt(i)==s.charAt(i-1)) arr[i]=arr[i-1] + 1; else arr[i]=arr[i-1]; } int m=in.nextInt(); for (int i=0; i<m; i++) System.out.println(-arr[in.nextInt()-1] + arr[in.nextInt()-1]); } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
e21baf1f90137acbaea7a60700f19e00
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; public class IlyaandQueries { public static void main(String[] args) throws IOException { Scanner scan= new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s= br.readLine(); int quiries= Integer.parseInt(br.readLine()); int[][] arr = new int[quiries][2]; for (int i = 0; i < arr.length; i++) { String temp = br.readLine(); arr[i][0] =Integer.parseInt(temp.split(" ")[0]); arr[i][1] = Integer.parseInt(temp.split(" ")[1]); } int [] preprocessing = prepro(new int[s.length()], quiries, s); int index=0; while(quiries-->0){ System.out.println(preprocessing[arr[index][1]-1] - preprocessing[arr[index][0]-1]); index++; } } static int[] prepro(int arr[],int quiries,String s){ int [] pre = new int[s.length()]; pre[0]=0; int left =1; int right = s.length(); int localMax = 0; while(left<right){ if(s.charAt(left-1) == s.charAt(left)){ localMax++; } pre[left]=localMax; left++; } return pre; } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
017442e34a16047e2a800c8d949170b6
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.BufferedReader; // 313B import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Liya_and_Queries_dp_implementation { static final int N_INF=-99999; static int dp[]=new int[100009]; public static void main(String[] args) throws IOException { FastReader sc=new FastReader(); int i,l,r; char s[]=sc.nextLine().toCharArray(); int len=s.length; Arrays.fill(dp,0); for(i=0;i<len-1;++i) { if(s[i]==s[i+1]) dp[i+1]=dp[i]+1; else dp[i+1]=dp[i]; } int m=sc.nextInt(); for(i=0;i<m;++i) { l=sc.nextInt(); r=sc.nextInt(); System.out.println(dp[r-1]-dp[l-1]); } } 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
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
d7fce8e1cbfed923bc419afada59b111
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
// 313B import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Liya_and_Queries_dp_implementation { static final int N_INF=-99999; public static void main(String[] args) throws IOException { FastReader sc=new FastReader(); int i,l,r; char s[]=sc.nextLine().toCharArray(); int len=s.length; int dp[]=new int[len]; Arrays.fill(dp,0); for(i=1;i<len;++i) { if(s[i]==s[i-1]) dp[i]=dp[i-1]+1; else dp[i]=dp[i-1]; } int m=sc.nextInt(); for(i=0;i<m;++i) { l=sc.nextInt(); r=sc.nextInt(); System.out.println(dp[r-1]-dp[l-1]); } } 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
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
cf6531d20814320d13a8d1f19932325f
train_002.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.awt.Point; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.*; import java.util.*; public class Main { ////// static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } ////// public static long modularExponentiation(long x, long n, long M) { long result = 1; while (n > 0) { if (n % 2 == 1) result = (result * x) % M; x = (x * x) % M; n = n / 2; } return result; } public static long modularExponentiation1(long x, long n) { long result = 1; while (n > 0) { if (n % 2 == 1) result = (result * x); x = (x * x); n = n / 2; } return result; } ///// static public int fun(int num) { int prod = 1; while (num > 0) { if (num % 10 != 0) { prod = prod * (num % 10); } num = num / 10; } return prod; } public static boolean dfs(int x, int find, boolean[] visited, int[][] matrix) { boolean ans = false; if (x == find) { ans = true; return true; } for (int i = 0; i < 26; i++) { if (visited[i] == false && matrix[x][i] == 1) { visited[i] = true; ans = ans || dfs(i, find, visited, matrix); } } return ans; } static int lis(int arr[], int n, int k, int b) { int lis[] = new int[n]; int i, j, max = 0; /* Initialize LIS values for all indexes */ for (i = 0; i < n; i++) lis[i] = 1; /* Compute optimized LIS values in bottom up manner */ for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] >= k * arr[j] + b && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick maximum of all LIS values */ for (i = 0; i < n; i++) if (max < lis[i]) max = lis[i]; return max; } public static void main(String[] args) throws IOException { FastReader scan = new FastReader(); PrintWriter pw = new PrintWriter(System.out); // int N=scan.nextInt(); // int U=scan.nextInt(); // int flag=0; // int[] A=new int[N]; // for(int i=0;i<N;i++){ // A[i]=scan.nextInt(); // if(i>=2){ // if(A[i]-A[i-2]<=U){ // flag=1; // } // } // } // //// // if(flag==0){ // System.out.println("-1"); // return; // } // // //int i=0,j=2; // //int sum=A[2]-A[0]; // double e=0; // //e=Math.max((double)(A[j]-A[i+1])/(double)(A[j]-A[i]),e); // for(int i=0;i<N-2;i++){ // int j=i+2; // while(j!=N&&A[j]-A[i]<=U){ // j++; // } // j--; //// if(A[j]-A[i]>U){ //// continue; //// } // e=Math.max((double)(A[j]-A[i+1])/(double)(A[j]-A[i]),e); // } // // // pw.println(e); String inp = null; inp = scan.next(); int N = 0; N = scan.nextInt(); String[] A = inp.split("", 0); int[] dp = new int[A.length]; dp[0] = 0; for (int i = 1; i < A.length; i++) { dp[i] = A[i].equals(A[i - 1]) ? 1 + dp[i - 1] : dp[i - 1]; } while (N-- > 0) { int L = 0, R = 0; L = scan.nextInt(); R = scan.nextInt(); pw.println(dp[R-1] - dp[L-1]); } pw.close(); } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
59c25eb33e0ff809625f476d6be263b1
train_002.jsonl
1330804800
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second t, and the call continues for d seconds, then Mr. Jackson is busy at seconds t, t + 1, ..., t + d - 1, and he can start a new call at second t + d. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most k calls. Note that a call which comes while he is busy talking can be ignored as well.What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.
256 megabytes
//package vkqual1; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Locale; import java.util.StringTokenizer; public class Main { private void solve() throws IOException { int n = nextInt(); int k = nextInt(); if (n == 0) { println("86400"); return; } int[] t = new int[n + 1]; int[] l = new int[n + 1]; for (int i = 0; i < n; i++) { t[i] = nextInt(); l[i] = nextInt(); } t[n] = 86401; l[n] = 1; int[][] d = new int[n][k + 1]; d[0][0] = t[0] + l[0]; if (k > 0) { d[0][1] = 1; } for (int i = 1; i < n; i++) { d[i][0] = Math.max(d[i - 1][0], t[i]) + l[i]; for (int j = 1; j <= k; j++) { if (j > i + 1) { break; } if (j == i + 1) { d[i][j] = 1; } else { d[i][j] = Math.min(Math.max(d[i - 1][j], t[i]) + l[i], d[i - 1][j - 1]); } // System.err.println(i + " " + j + " " + d[i][j]); } } int res = 0; if (k == 0) { res = t[0] - 1; for (int i = k; i < n; i++) { res = Math.max(res, t[i + 1] - d[i][k]); } } else { for (int i = k - 1; i < n; i++) { res = Math.max(res, t[i + 1] - d[i][k]); } } println(res); } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private void print(Object o) { writer.print(o); } private void println(Object o) { writer.println(o); } private void printf(String format, Object... o) { writer.printf(format, o); } public static void main(String[] args) { long time = System.currentTimeMillis(); Locale.setDefault(Locale.US); new Main().run(); System.err.printf("%.3f\n", 1e-3 * (System.currentTimeMillis() - time)); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; private void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); System.exit(13); } } }
Java
["3 2\n30000 15000\n40000 15000\n50000 15000", "5 1\n1 20000\n10000 10000\n20000 20000\n25000 10000\n80000 60000"]
3 seconds
["49999", "39999"]
NoteIn the first sample the most convenient way is to ignore the first two calls.In the second sample it is best to ignore the third call. In this case Mr. Jackson will have been speaking: first call: from 1-st to 20000-th second, second call: from 20001-st to 30000-th second, fourth call: from 30001-st to 40000-th second (the third call is ignored), fifth call: from 80000-th to 139999-th second. Thus, the longest period of free time is from the 40001-th to the 79999-th second.
Java 6
standard input
[ "dp", "sortings", "*special" ]
936f883476039e9e5b698a1d45cbe61a
The first input line contains a pair of integers n, k (0 ≀ k ≀ n ≀ 4000) separated by a space. Following n lines contain the description of calls for today. The description of each call is located on the single line and consists of two space-separated integers ti and di, (1 ≀ ti, di ≀ 86400). All ti are distinct, the calls are given in the order of strict increasing ti. Scheduled times of calls [ti, ti + di - 1] can arbitrarily intersect.
1,900
Print a number from 0 to 86400, inclusive β€” the maximally possible number of seconds for Mr. Jackson to sleep today.
standard output
PASSED
9da7aefe98139079d71379f7938cfa3a
train_002.jsonl
1330804800
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second t, and the call continues for d seconds, then Mr. Jackson is busy at seconds t, t + 1, ..., t + d - 1, and he can start a new call at second t + d. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most k calls. Note that a call which comes while he is busy talking can be ignored as well.What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.
256 megabytes
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class E implements Runnable{ final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new Thread(null, new E(), "", 256 * (1L << 20)).start(); } long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory(){ memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } void debug(Object... objects){ if (DEBUG){ for (Object o: objects){ System.err.println(o.toString()); } } } public void run(){ try{ timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); time(); memory(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } boolean DEBUG = false; void solve() throws IOException{ int n = readInt(); int k = readInt(); if (n == 0){ out.print(86400); return; } int[] t = new int[n+1]; int[] d = new int[n+1]; for (int i = 1; i <= n; i++){ t[i] = readInt(); d[i] = readInt(); } long[][] dp = new long[n+1][k+1]; Arrays.fill(dp[0], Integer.MAX_VALUE); dp[0][0] = 1; long max = t[1] - 1; for (int i = 1; i <= n; i++){ Arrays.fill(dp[i], Integer.MAX_VALUE); dp[i][0] = max(dp[i-1][0], t[i]) + d[i]; int begin = (int) dp[i][0]; int end = begin; if (i + k + 1 > n){ end = 86401; }else{ end = t[i+k+1]; } max = max(max, end - begin); for (int j = 1; j <= min(i, k); j++){ dp[i][j] = min(dp[i-1][j-1], max(dp[i-1][j], t[i]) + d[i]); begin = (int) dp[i][j]; end = begin; if (i + k - j + 1 > n){ end = 86401; }else{ end = t[i+k-j+1]; } max = max(max, end - begin); } } out.print(max); } }
Java
["3 2\n30000 15000\n40000 15000\n50000 15000", "5 1\n1 20000\n10000 10000\n20000 20000\n25000 10000\n80000 60000"]
3 seconds
["49999", "39999"]
NoteIn the first sample the most convenient way is to ignore the first two calls.In the second sample it is best to ignore the third call. In this case Mr. Jackson will have been speaking: first call: from 1-st to 20000-th second, second call: from 20001-st to 30000-th second, fourth call: from 30001-st to 40000-th second (the third call is ignored), fifth call: from 80000-th to 139999-th second. Thus, the longest period of free time is from the 40001-th to the 79999-th second.
Java 6
standard input
[ "dp", "sortings", "*special" ]
936f883476039e9e5b698a1d45cbe61a
The first input line contains a pair of integers n, k (0 ≀ k ≀ n ≀ 4000) separated by a space. Following n lines contain the description of calls for today. The description of each call is located on the single line and consists of two space-separated integers ti and di, (1 ≀ ti, di ≀ 86400). All ti are distinct, the calls are given in the order of strict increasing ti. Scheduled times of calls [ti, ti + di - 1] can arbitrarily intersect.
1,900
Print a number from 0 to 86400, inclusive β€” the maximally possible number of seconds for Mr. Jackson to sleep today.
standard output
PASSED
bd0fbc02d7fca07d3ac55559a7b9f55a
train_002.jsonl
1330804800
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second t, and the call continues for d seconds, then Mr. Jackson is busy at seconds t, t + 1, ..., t + d - 1, and he can start a new call at second t + d. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most k calls. Note that a call which comes while he is busy talking can be ignored as well.What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.
256 megabytes
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class E { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } int[] readArr(int n) throws IOException{ int[] res = new int[n]; for(int i = 0; i < n; i++){ res[i] = readInt(); } return res; } long[] readArrL(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++){ res[i] = readLong(); } return res; } long memoryTotal, memoryFree; void memory(){ memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public static void main(String[] args){ new E().run(); } public void run(){ try{ long t1 = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = "+(t2-t1)); memory(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } void solve() throws IOException{ int n = readInt(); int k = readInt(); int[] t = new int[n+1]; int[] d = new int[n+1]; for(int i = 0; i < n; i++){ t[i+1] = readInt(); d[i+1] = readInt(); } if(k == n){ out.println(86400); return; } int[] dl = new int[k+1]; dl[0] = 0; int max = -1; int prev = 0, cur = 0; /*for(int i = 1; i <= n; i++){ dl[i][0] = max(dl[i-1][0], t[i]) + d[i]; max = max(max, t[min(i+k+1, n)] - max(dl[i][0],1)); for(int j = 1; j <= i && j <= k; j++){ dl[i][j] = min(dl[i-1][j-1], max(dl[i-1][j], t[i]) + d[i]); max = max(max, t[min(i+k-j+1,n)] - max(dl[i][j],1)); } }*/ for(int i = 1; i <= n; i++){ prev = max(dl[0], t[i]) + d[i]; if(i+k+1 <= n) max = max(max, t[min(i+k+1, n)] - max(prev,1)); else max = max(max, 86401 - max(prev,1)); for(int j = 1; j <= i && j <= k; j++){ cur = min(dl[j-1], max(dl[j], t[i]) + d[i]); if(i+k-j+1 > n) max = max(max, 86401 - max(cur,1)); else max = max(max, t[min(i+k-j+1,n)] - max(cur,1)); dl[j-1] = prev; prev = cur; } dl[min(i,k)] = prev; } out.println(max(max,0)); } void maxHepify(int[] a, int i, int length){ int l = (i<<1) + 1; int r = (i<<1) + 2; int largest = i; if(l < length && a[l] > a[largest]) largest = l; if(r < length && a[r] > a[largest]) largest = r; if(largest != i){ a[largest] += a[i]; a[i] = a[largest] - a[i]; a[largest] -= a[i]; maxHepify(a, largest, length); } } void buildMaxHeap(int[] a){ for(int i = a.length/2 - 1; i >= 0; i--){ maxHepify(a, i, a.length); } } void heapSort(int[] a){ buildMaxHeap(a); for(int i = a.length - 1; i > 0; i--){ a[i] += a[0]; a[0] = a[i] - a[0]; a[i] -= a[0]; maxHepify(a, 0, i); } } int[] zFunction(char[] s){ int[] z = new int[s.length]; z[0] = 0; for (int i=1, l=0, r=0; i<s.length; ++i) { if (i <= r) z[i] = min (r-i+1, z[i-l]); while (i+z[i] < s.length && s[z[i]] == s[i+z[i]]) ++z[i]; if (i+z[i]-1 > r){ l = i; r = i+z[i]-1; } } return z; } int[] prefixFunction(char[] s){ int[] pr = new int[s.length]; for (int i = 1; i< s.length; ++i) { int j = pr[i-1]; while (j > 0 && s[i] != s[j]) j = pr[j-1]; if (s[i] == s[j]) ++j; pr[i] = j; } return pr; } int ModExp(int a, int n, int mod){ int res = 1; while (n!=0) if ((n & 1) != 0) { res = (res*a)%mod; --n; } else { a = (a*a)%mod; n >>= 1; } return res; } public static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int leftIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } boolean isPrime(int a){ for(int i = 2; i <= sqrt(a); i++) if(a % i == 0) return false; return true; } static double distance(long x1, long y1, long x2, long y2){ return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } static long gcd(long a, long b){ if(min(a,b) == 0) return max(a,b); return gcd(max(a, b) % min(a,b), min(a,b)); } static long lcm(long a, long b){ return a * b /gcd(a, b); } } /*class Treap<K extends Comparable<K>>{ public K x; public double y; public Treap<K> left; public Treap<K> right; public Treap(K x, double y, Treap<K> left, Treap<K> right) { this.x = x; this.y = y; this.left = left; this.right = right; } public static <K extends Comparable<K>> Treap<K> merge(Treap<K> l, Treap<K> r){ if(l == null) return r; if(r == null) return l; if(l.y > r.y){ return new Treap<K>(l.x, l.y, l.left, merge(l.right, r)); } else{ return new Treap<K>(r.x, r.y, merge(l, r.left), r.right); } } public void split(K x, Treap<K> left, Treap<K> right){ Treap<K> newTreap = null; if(this.x.compareTo(x) <= 0){ if(this.right == null){ right = null; } else{ right.split(x, newTreap, right); } left = new Treap<K>(this.x, this.y, left, newTreap); } else{ if(this.left == null){ left = null; } else{ left.split(x, left, newTreap); } right = new Treap<K>(x, y, newTreap, right); } } public Treap<K> add(K x){ Treap<K> left = null, right = null; this.split(x, left, right); Treap<K> temp = new Treap<K>(x, random(), null, null); return merge(merge(left, temp), right); } @SuppressWarnings("null") public Treap<K> remove(K x){ Treap<K> left = null, temp = null, right = null; this.split(x, left, right); right.split(x, temp, right); return merge(left, right); } public static <K extends Comparable<K>> Treap<K> build(K[] a){ Treap<K> temp = new Treap<K>(a[0], random(), null, null); for(int i = 1; i < a.length; i++){ temp = temp.add(a[i]); } return temp; } }*/
Java
["3 2\n30000 15000\n40000 15000\n50000 15000", "5 1\n1 20000\n10000 10000\n20000 20000\n25000 10000\n80000 60000"]
3 seconds
["49999", "39999"]
NoteIn the first sample the most convenient way is to ignore the first two calls.In the second sample it is best to ignore the third call. In this case Mr. Jackson will have been speaking: first call: from 1-st to 20000-th second, second call: from 20001-st to 30000-th second, fourth call: from 30001-st to 40000-th second (the third call is ignored), fifth call: from 80000-th to 139999-th second. Thus, the longest period of free time is from the 40001-th to the 79999-th second.
Java 6
standard input
[ "dp", "sortings", "*special" ]
936f883476039e9e5b698a1d45cbe61a
The first input line contains a pair of integers n, k (0 ≀ k ≀ n ≀ 4000) separated by a space. Following n lines contain the description of calls for today. The description of each call is located on the single line and consists of two space-separated integers ti and di, (1 ≀ ti, di ≀ 86400). All ti are distinct, the calls are given in the order of strict increasing ti. Scheduled times of calls [ti, ti + di - 1] can arbitrarily intersect.
1,900
Print a number from 0 to 86400, inclusive β€” the maximally possible number of seconds for Mr. Jackson to sleep today.
standard output
PASSED
c08ed093c4c226cdc24a005e47a3d37c
train_002.jsonl
1330804800
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second t, and the call continues for d seconds, then Mr. Jackson is busy at seconds t, t + 1, ..., t + d - 1, and he can start a new call at second t + d. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most k calls. Note that a call which comes while he is busy talking can be ignored as well.What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class E { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int []t = new int [n+1], d = new int [n+1]; for (int i = 1; i <=n; i++) { t[i] = sc.nextInt(); d[i] = sc.nextInt(); } int [][]dp = new int [n+1][n+1]; int INF = (int)1e9; for (int i = 1; i <=n; i++) { Arrays.fill(dp[i], INF); } dp[0][0] = 1; if (n > 0){ dp[1][0] = t[1]+d[1]; dp[1][1] = 1; } for (int i = 2; i <=n; i++) { for (int j = 0; j <=n; j++) { dp[i][j] = Math.max(dp[i-1][j], t[i])+d[i]; if (j > 0) dp[i][j] = Math.min(dp[i][j], dp[i-1][j-1]); } } int ans = 86401-dp[n][k]; for (int i = k; i < n; i++) { ans = Math.max(ans, t[i+1]-dp[i][k]); } System.out.println(ans); } }
Java
["3 2\n30000 15000\n40000 15000\n50000 15000", "5 1\n1 20000\n10000 10000\n20000 20000\n25000 10000\n80000 60000"]
3 seconds
["49999", "39999"]
NoteIn the first sample the most convenient way is to ignore the first two calls.In the second sample it is best to ignore the third call. In this case Mr. Jackson will have been speaking: first call: from 1-st to 20000-th second, second call: from 20001-st to 30000-th second, fourth call: from 30001-st to 40000-th second (the third call is ignored), fifth call: from 80000-th to 139999-th second. Thus, the longest period of free time is from the 40001-th to the 79999-th second.
Java 6
standard input
[ "dp", "sortings", "*special" ]
936f883476039e9e5b698a1d45cbe61a
The first input line contains a pair of integers n, k (0 ≀ k ≀ n ≀ 4000) separated by a space. Following n lines contain the description of calls for today. The description of each call is located on the single line and consists of two space-separated integers ti and di, (1 ≀ ti, di ≀ 86400). All ti are distinct, the calls are given in the order of strict increasing ti. Scheduled times of calls [ti, ti + di - 1] can arbitrarily intersect.
1,900
Print a number from 0 to 86400, inclusive β€” the maximally possible number of seconds for Mr. Jackson to sleep today.
standard output
PASSED
cc01a460ce506977e0118ffd1b2463cd
train_002.jsonl
1330804800
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second t, and the call continues for d seconds, then Mr. Jackson is busy at seconds t, t + 1, ..., t + d - 1, and he can start a new call at second t + d. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most k calls. Note that a call which comes while he is busy talking can be ignored as well.What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URI; import java.util.Arrays; import java.util.StringTokenizer; public class Main implements Runnable { /** * @param args */ public static void main(String[] args) { (new Thread(new Main())).start(); } StringTokenizer st; BufferedReader in; PrintWriter out; public void run() { try { String task = ""; if (false && System.getProperty("LOCAL_RUN") != null) { // in = new BufferedReader(new InputStreamReader(System.in)); in = new BufferedReader(new FileReader("input")); out = new PrintWriter(System.out); } else { // in = new BufferedReader(new FileReader(task + ".in")); // out = new PrintWriter(task + ".out"); // in = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter("output.txt"); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } solve(); } catch (Exception e) { e.printStackTrace(); } finally { out.flush(); out.close(); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } void printArr(int[] a) { for (int i = 0; i < a.length; i++) out.print(a[i] + " "); out.println(); } int[] t, d; int dp[][] = new int[4400][4400]; int max_seconds = 86400; void solve() throws Exception { int n = nextInt(), k = nextInt(); if (n == 0) { out.println(max_seconds); return; } t = new int[n]; d = new int[n]; for (int i = 0; i < 4400; i++) Arrays.fill(dp[i], max_seconds+1); for (int i = 0; i < n; i++) { t[i] = nextInt(); d[i] = nextInt(); } // int res = t[0] - 1; for (int added = 0; added <= n; added++) { for (int skipped = 0; skipped <= k; skipped++) { int cur_time = added == 0 ? 1 : dp[added][skipped]; int xr = max_seconds + 1; if (added < n) { int ntime = Math.max(cur_time, t[added]) + d[added]; dp[added + 1][skipped] = Math.min(dp[added + 1][skipped], ntime); dp[added + 1][skipped + 1] = Math.min( dp[added + 1][skipped], cur_time); xr = t[added]; } res = Math.max(res, Math.min(max_seconds + 1, xr) - dp[added][skipped]); } } out.println(res); } }
Java
["3 2\n30000 15000\n40000 15000\n50000 15000", "5 1\n1 20000\n10000 10000\n20000 20000\n25000 10000\n80000 60000"]
3 seconds
["49999", "39999"]
NoteIn the first sample the most convenient way is to ignore the first two calls.In the second sample it is best to ignore the third call. In this case Mr. Jackson will have been speaking: first call: from 1-st to 20000-th second, second call: from 20001-st to 30000-th second, fourth call: from 30001-st to 40000-th second (the third call is ignored), fifth call: from 80000-th to 139999-th second. Thus, the longest period of free time is from the 40001-th to the 79999-th second.
Java 6
standard input
[ "dp", "sortings", "*special" ]
936f883476039e9e5b698a1d45cbe61a
The first input line contains a pair of integers n, k (0 ≀ k ≀ n ≀ 4000) separated by a space. Following n lines contain the description of calls for today. The description of each call is located on the single line and consists of two space-separated integers ti and di, (1 ≀ ti, di ≀ 86400). All ti are distinct, the calls are given in the order of strict increasing ti. Scheduled times of calls [ti, ti + di - 1] can arbitrarily intersect.
1,900
Print a number from 0 to 86400, inclusive β€” the maximally possible number of seconds for Mr. Jackson to sleep today.
standard output
PASSED
f7bc31c3b3be3fd84ed1c0171142deb4
train_002.jsonl
1330804800
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second t, and the call continues for d seconds, then Mr. Jackson is busy at seconds t, t + 1, ..., t + d - 1, and he can start a new call at second t + d. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most k calls. Note that a call which comes while he is busy talking can be ignored as well.What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.
256 megabytes
import java.io.*; /** * User: Igor Kirov * Date: 04.03.12 */ public class E { private StreamTokenizer in; private PrintWriter out; private void run() throws IOException { init(); int n = nextInt(); int k = nextInt(); int[] min = new int[k+10]; for (int i = 1; i<=k; i++) { min[i] = 100000; } int[] newMin = new int[k+10]; int res = 0; for (int i = 1; i<=n; i++) { int start = nextInt(); int length = nextInt(); if (min[0] < start) { res = Math.max(res, start - min[0] - 1); newMin[0] = start + length - 1; } else { newMin[0] = min[0] + length; } for (int j = 1; j <= Math.min(i, k); j++) { newMin[j] = min[j-1]; if (min[j] < start) { res = Math.max(res, start - min[j] - 1); newMin[j] = Math.min(newMin[j], start + length - 1); } else { newMin[j] = Math.min(newMin[j], min[j] + length); } } System.arraycopy(newMin, 0, min, 0, min.length); } if (min[k] < 86400) { res = Math.max(res, 86400 - min[k]); } out.println(res); done(); } private int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } private void init() throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("E.in"); Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("E.out"); in = new StreamTokenizer(new BufferedReader(reader)); out = new PrintWriter(writer); } private void done() { out.flush(); } public static void main(String[] args) throws IOException { new E().run(); } }
Java
["3 2\n30000 15000\n40000 15000\n50000 15000", "5 1\n1 20000\n10000 10000\n20000 20000\n25000 10000\n80000 60000"]
3 seconds
["49999", "39999"]
NoteIn the first sample the most convenient way is to ignore the first two calls.In the second sample it is best to ignore the third call. In this case Mr. Jackson will have been speaking: first call: from 1-st to 20000-th second, second call: from 20001-st to 30000-th second, fourth call: from 30001-st to 40000-th second (the third call is ignored), fifth call: from 80000-th to 139999-th second. Thus, the longest period of free time is from the 40001-th to the 79999-th second.
Java 6
standard input
[ "dp", "sortings", "*special" ]
936f883476039e9e5b698a1d45cbe61a
The first input line contains a pair of integers n, k (0 ≀ k ≀ n ≀ 4000) separated by a space. Following n lines contain the description of calls for today. The description of each call is located on the single line and consists of two space-separated integers ti and di, (1 ≀ ti, di ≀ 86400). All ti are distinct, the calls are given in the order of strict increasing ti. Scheduled times of calls [ti, ti + di - 1] can arbitrarily intersect.
1,900
Print a number from 0 to 86400, inclusive β€” the maximally possible number of seconds for Mr. Jackson to sleep today.
standard output
PASSED
a6e85ec01c926bd4f0111e84c5cea41b
train_002.jsonl
1330804800
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second t, and the call continues for d seconds, then Mr. Jackson is busy at seconds t, t + 1, ..., t + d - 1, and he can start a new call at second t + d. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most k calls. Note that a call which comes while he is busy talking can be ignored as well.What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Solution { static int[] t; static int[] d; static int n; static int k; static final int secAfterDayEnd = 86401; static int[][] M; public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // BufferedReader in = new BufferedReader(new FileReader("input.txt")); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(in.readLine()); n = Integer.parseInt(st.nextToken()); k = Integer.parseInt(st.nextToken()); t = new int[n]; d = new int[n]; M = new int[n + 1][k + 1]; for (int i = 0; i <= n; i++) Arrays.fill(M[i], -1); for (int i = 0; i < n; i++) { st = new StringTokenizer(in.readLine()); t[i] = Integer.parseInt(st.nextToken()); d[i] = Integer.parseInt(st.nextToken()); } int ans = Integer.MIN_VALUE; for (int i = 0; i <= n; i++) { int endTime = getEndTime(i, k); int nextTime = i == n ? secAfterDayEnd : t[i]; int locAns = endTime < nextTime ? nextTime - endTime : 0; ans = Math.max(ans, locAns); } out.println(ans); out.close(); } private static int getEndTime(int calls, int skips) { if (M[calls][skips] != -1) return M[calls][skips]; int ans = Integer.MAX_VALUE; if (calls == 0 || skips >= calls) ans = 1; else { // skip curr int ansSkip = Integer.MAX_VALUE; if (skips > 0) ansSkip = getEndTime(calls - 1, skips - 1); // do not skip int ansNoSkip = Math.max(getEndTime(calls - 1, skips), t[calls - 1]) + d[calls - 1]; ans = Math.min(ansSkip, ansNoSkip); } M[calls][skips] = ans; return ans; } }
Java
["3 2\n30000 15000\n40000 15000\n50000 15000", "5 1\n1 20000\n10000 10000\n20000 20000\n25000 10000\n80000 60000"]
3 seconds
["49999", "39999"]
NoteIn the first sample the most convenient way is to ignore the first two calls.In the second sample it is best to ignore the third call. In this case Mr. Jackson will have been speaking: first call: from 1-st to 20000-th second, second call: from 20001-st to 30000-th second, fourth call: from 30001-st to 40000-th second (the third call is ignored), fifth call: from 80000-th to 139999-th second. Thus, the longest period of free time is from the 40001-th to the 79999-th second.
Java 6
standard input
[ "dp", "sortings", "*special" ]
936f883476039e9e5b698a1d45cbe61a
The first input line contains a pair of integers n, k (0 ≀ k ≀ n ≀ 4000) separated by a space. Following n lines contain the description of calls for today. The description of each call is located on the single line and consists of two space-separated integers ti and di, (1 ≀ ti, di ≀ 86400). All ti are distinct, the calls are given in the order of strict increasing ti. Scheduled times of calls [ti, ti + di - 1] can arbitrarily intersect.
1,900
Print a number from 0 to 86400, inclusive β€” the maximally possible number of seconds for Mr. Jackson to sleep today.
standard output
PASSED
dc3916aeef4668fca70b8bf187a766ed
train_002.jsonl
1330804800
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second t, and the call continues for d seconds, then Mr. Jackson is busy at seconds t, t + 1, ..., t + d - 1, and he can start a new call at second t + d. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most k calls. Note that a call which comes while he is busy talking can be ignored as well.What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.
256 megabytes
import java.lang.*; import java.io.*; import java.util.*; import java.math.*; public class E implements Runnable{ public void run() { int n = nextInt(); int k = nextInt(); int[][] dp = new int[n+1][k+1]; int[] tt = new int[n]; int[] dd = new int[n]; for (int i = 0; i < n; ++i) { tt[i] = nextInt()-1; dd[i] = nextInt(); } for (int i = 1; i <= n; ++i) { Arrays.fill(dp[i], Integer.MAX_VALUE/3); } Arrays.fill(dp[0], -1); dp[0][0] = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j <= k; ++j) { if (dp[i][j] >= 0) { dp[i+1][j] = Math.min(dp[i+1][j], Math.max(dp[i][j], tt[i]) + dd[i]); } if (j < k) { dp[i+1][j+1] = Math.min(dp[i+1][j+1], dp[i][j]); } } } int ans = 0; for (int i = 1; i <= n; ++i) { ans = Math.max(tt[i-1] - dp[i-1][Math.min(k, i)], ans); } ans = Math.max(86400 - dp[n][k], ans); out.println(ans); out.flush(); } private static BufferedReader br = null; private static PrintWriter out = null; private static StringTokenizer stk = null; public static void main(String[] args) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); (new Thread(new E())).start(); } private void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } private String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } private Integer nextInt() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Integer.parseInt(stk.nextToken()); } private Long nextLong() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Long.parseLong(stk.nextToken()); } private String nextWord() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return (stk.nextToken()); } private Double nextDouble() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Double.parseDouble(stk.nextToken()); } }
Java
["3 2\n30000 15000\n40000 15000\n50000 15000", "5 1\n1 20000\n10000 10000\n20000 20000\n25000 10000\n80000 60000"]
3 seconds
["49999", "39999"]
NoteIn the first sample the most convenient way is to ignore the first two calls.In the second sample it is best to ignore the third call. In this case Mr. Jackson will have been speaking: first call: from 1-st to 20000-th second, second call: from 20001-st to 30000-th second, fourth call: from 30001-st to 40000-th second (the third call is ignored), fifth call: from 80000-th to 139999-th second. Thus, the longest period of free time is from the 40001-th to the 79999-th second.
Java 6
standard input
[ "dp", "sortings", "*special" ]
936f883476039e9e5b698a1d45cbe61a
The first input line contains a pair of integers n, k (0 ≀ k ≀ n ≀ 4000) separated by a space. Following n lines contain the description of calls for today. The description of each call is located on the single line and consists of two space-separated integers ti and di, (1 ≀ ti, di ≀ 86400). All ti are distinct, the calls are given in the order of strict increasing ti. Scheduled times of calls [ti, ti + di - 1] can arbitrarily intersect.
1,900
Print a number from 0 to 86400, inclusive β€” the maximally possible number of seconds for Mr. Jackson to sleep today.
standard output
PASSED
83e29d21474c93d8dd9033255193fb19
train_002.jsonl
1330804800
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second t, and the call continues for d seconds, then Mr. Jackson is busy at seconds t, t + 1, ..., t + d - 1, and he can start a new call at second t + d. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most k calls. Note that a call which comes while he is busy talking can be ignored as well.What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) {} long prevTime = System.currentTimeMillis(); new Main().run(); System.err.println("Total time: " + (System.currentTimeMillis() - prevTime) + " ms"); System.err.println("Memory status: " + memoryStatus()); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); in.close(); } /*************************************************************** * Solution **************************************************************/ final int INF = Integer.MAX_VALUE; final int MAXT = 86400; int[] start; int[] duration; int[] curDP; int[] nxtDP; void solve() throws IOException { int n = nextInt(); int k = nextInt(); start = new int [n + 2]; duration = new int [n + 2]; start[0] = 0; duration[0] = 1; for (int i = 1; i <= n; i++) { start[i] = nextInt(); duration[i] = nextInt(); } start[n + 1] = INF; duration[n + 1] = 0; int ans = 0; curDP = new int [k + 1]; nxtDP = new int [k + 1]; fill(curDP, INF); fill(nxtDP, INF); curDP[0] = 1; for (int i = 1; i <= n + 1; i++) { for (int j = 0; j <= k; j++) { int curVal = curDP[j]; if (curVal == INF) continue; { // curAns int l = min(MAXT + 1, curVal); int rest = k - j; int next = min(n + 1, i + rest); int r = min(MAXT + 1, start[next]); ans = max(ans, r - l); } if (i <= n) { // get current range nxtDP[j] = min(nxtDP[j], max(curVal, start[i]) + duration[i]); } if (i <= n && j < k) { // skip current range nxtDP[j + 1] = min(nxtDP[j + 1], curVal); } } { // swap rows int[] tmp = curDP; curDP = nxtDP; nxtDP = tmp; fill(nxtDP, INF); } } out.println(ans); } /*************************************************************** * Input **************************************************************/ BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } int[] nextIntArray(int size) throws IOException { int[] ret = new int [size]; for (int i = 0; i < size; i++) ret[i] = nextInt(); return ret; } long[] nextLongArray(int size) throws IOException { long[] ret = new long [size]; for (int i = 0; i < size; i++) ret[i] = nextLong(); return ret; } double[] nextDoubleArray(int size) throws IOException { double[] ret = new double [size]; for (int i = 0; i < size; i++) ret[i] = nextDouble(); return ret; } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } /*************************************************************** * Output **************************************************************/ void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { if (array == null || array.length == 0) return; boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings("rawtypes") void printCollection(Collection collection) { if (collection == null || collection.isEmpty()) return; boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } /*************************************************************** * Utility **************************************************************/ static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB"; } static void checkMemory() { System.err.println(memoryStatus()); } static long prevTimeStamp = Long.MIN_VALUE; static void updateTimer() { prevTimeStamp = System.currentTimeMillis(); } static long elapsedTime() { return (System.currentTimeMillis() - prevTimeStamp); } static void checkTimer() { System.err.println(elapsedTime() + " ms"); } }
Java
["3 2\n30000 15000\n40000 15000\n50000 15000", "5 1\n1 20000\n10000 10000\n20000 20000\n25000 10000\n80000 60000"]
3 seconds
["49999", "39999"]
NoteIn the first sample the most convenient way is to ignore the first two calls.In the second sample it is best to ignore the third call. In this case Mr. Jackson will have been speaking: first call: from 1-st to 20000-th second, second call: from 20001-st to 30000-th second, fourth call: from 30001-st to 40000-th second (the third call is ignored), fifth call: from 80000-th to 139999-th second. Thus, the longest period of free time is from the 40001-th to the 79999-th second.
Java 6
standard input
[ "dp", "sortings", "*special" ]
936f883476039e9e5b698a1d45cbe61a
The first input line contains a pair of integers n, k (0 ≀ k ≀ n ≀ 4000) separated by a space. Following n lines contain the description of calls for today. The description of each call is located on the single line and consists of two space-separated integers ti and di, (1 ≀ ti, di ≀ 86400). All ti are distinct, the calls are given in the order of strict increasing ti. Scheduled times of calls [ti, ti + di - 1] can arbitrarily intersect.
1,900
Print a number from 0 to 86400, inclusive β€” the maximally possible number of seconds for Mr. Jackson to sleep today.
standard output
PASSED
01c348fa4d9f942f2a05e2fb10278e28
train_002.jsonl
1330804800
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second t, and the call continues for d seconds, then Mr. Jackson is busy at seconds t, t + 1, ..., t + d - 1, and he can start a new call at second t + d. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most k calls. Note that a call which comes while he is busy talking can be ignored as well.What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.
256 megabytes
import java.util.Scanner; public class E { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int n = sc.nextInt(), k = sc.nextInt(); int[] t = new int[n + 1], d = new int[n + 1]; for (int i = 1; i <= n; ++i) { t[i] = sc.nextInt(); d[i] = sc.nextInt(); } int maxSleep = 0; int[][] Q = new int[n + 1][k + 1]; for (int i = 1; i <= n; ++i) { for (int j = 0; j <= k; ++j) { Q[i][j] = Integer.MAX_VALUE; // take it into account if (Q[i - 1][j] != Integer.MAX_VALUE) { if (Q[i - 1][j] >= t[i]) { Q[i][j] = Math.min(Q[i][j], Q[i - 1][j] + d[i]); } else { Q[i][j] = Math.min(Q[i][j], t[i] + d[i] - 1); maxSleep = Math.max(maxSleep, t[i] - Q[i - 1][j] - 1); } } // ignore it if (j > 0 && Q[i - 1][j - 1] != Integer.MAX_VALUE) { Q[i][j] = Math.min(Q[i][j], Q[i - 1][j - 1]); } } } for (int j = 0; j <= k; ++j) maxSleep = Math.max(maxSleep, 86400 - Q[n][j]); System.out.println(maxSleep); } }
Java
["3 2\n30000 15000\n40000 15000\n50000 15000", "5 1\n1 20000\n10000 10000\n20000 20000\n25000 10000\n80000 60000"]
3 seconds
["49999", "39999"]
NoteIn the first sample the most convenient way is to ignore the first two calls.In the second sample it is best to ignore the third call. In this case Mr. Jackson will have been speaking: first call: from 1-st to 20000-th second, second call: from 20001-st to 30000-th second, fourth call: from 30001-st to 40000-th second (the third call is ignored), fifth call: from 80000-th to 139999-th second. Thus, the longest period of free time is from the 40001-th to the 79999-th second.
Java 6
standard input
[ "dp", "sortings", "*special" ]
936f883476039e9e5b698a1d45cbe61a
The first input line contains a pair of integers n, k (0 ≀ k ≀ n ≀ 4000) separated by a space. Following n lines contain the description of calls for today. The description of each call is located on the single line and consists of two space-separated integers ti and di, (1 ≀ ti, di ≀ 86400). All ti are distinct, the calls are given in the order of strict increasing ti. Scheduled times of calls [ti, ti + di - 1] can arbitrarily intersect.
1,900
Print a number from 0 to 86400, inclusive β€” the maximally possible number of seconds for Mr. Jackson to sleep today.
standard output
PASSED
0614a8ec9ae66c579baf945b4e10636a
train_002.jsonl
1330804800
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second t, and the call continues for d seconds, then Mr. Jackson is busy at seconds t, t + 1, ..., t + d - 1, and he can start a new call at second t + d. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most k calls. Note that a call which comes while he is busy talking can be ignored as well.What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.
256 megabytes
import java.awt.Point; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.InputMismatchException; public class E_2012 { static p[] st; static int[][] DP; public static int call(int index, int k) { if (index == -1 && k == 0) return 1; if (index == -1 || k<0) return 1000000; if (DP[index][k] != -1) return DP[index][k]; return DP[index][k] = Math.min(call(index - 1, k - 1), Math.max(st[index].x, call(index - 1, k)) + st[index].y); } public static void main(String[] args) { InputReader in = new InputReader(System.in); int n = in.readInt(); int k = in.readInt(); st = new p[n]; for (int i = 0; i < n; i++) { st[i] = new p(in.readInt(), in.readInt()); } DP = new int[n + 1][k + 1]; for (int i = 0; i < DP.length; i++) { Arrays.fill(DP[i], -1); } int max = -1; for (int i = 0; i <= n; i++) { int right = 86401; if (i < n) right = st[i].x; int left = call(i - 1, k); int res = right - left; max = Math.max(max, res); } System.out.println(max); } static class p implements Comparable<p> { int x; int y; public p(int a, int b) { x = a; y = b; } public int compareTo(p o) { if (x < o.x) return -1; if (x > o.x) return 1; return y - o.y; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } }
Java
["3 2\n30000 15000\n40000 15000\n50000 15000", "5 1\n1 20000\n10000 10000\n20000 20000\n25000 10000\n80000 60000"]
3 seconds
["49999", "39999"]
NoteIn the first sample the most convenient way is to ignore the first two calls.In the second sample it is best to ignore the third call. In this case Mr. Jackson will have been speaking: first call: from 1-st to 20000-th second, second call: from 20001-st to 30000-th second, fourth call: from 30001-st to 40000-th second (the third call is ignored), fifth call: from 80000-th to 139999-th second. Thus, the longest period of free time is from the 40001-th to the 79999-th second.
Java 6
standard input
[ "dp", "sortings", "*special" ]
936f883476039e9e5b698a1d45cbe61a
The first input line contains a pair of integers n, k (0 ≀ k ≀ n ≀ 4000) separated by a space. Following n lines contain the description of calls for today. The description of each call is located on the single line and consists of two space-separated integers ti and di, (1 ≀ ti, di ≀ 86400). All ti are distinct, the calls are given in the order of strict increasing ti. Scheduled times of calls [ti, ti + di - 1] can arbitrarily intersect.
1,900
Print a number from 0 to 86400, inclusive β€” the maximally possible number of seconds for Mr. Jackson to sleep today.
standard output
PASSED
e841f9bed6c7bcd6965b7375b36395a4
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.*; import java.util.*; public class A1008 { public static void main(String [] args) throws Exception { InputStream inputReader = System.in; OutputStream outputReader = System.out; InputReader in = new InputReader(new FileInputStream(new File("input.txt")));//new InputReader(inputReader); PrintWriter out = new PrintWriter(new FileOutputStream(new File("output.txt"))); Algorithm solver = new Algorithm(); solver.solve(in, out); out.close(); } } class Algorithm { void solve(InputReader ir, PrintWriter pw) { int n =ir.nextInt(), k = ir.nextInt() - 1; int [] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ir.nextInt(); while(a[k] == 0) k = (k + 1) % n; pw.print(k + 1); } boolean isPolyndrom(String str) { StringBuilder newStr = new StringBuilder(); for (int i = str.length() - 1; i >= 0; i--) newStr.append(str.charAt(i)); return newStr.toString().equals(str); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine(){ String fullLine = null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } String [] toArray() { return nextLine().split(" "); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 8
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
a9121ddef2ea4cb2d139806ba901b0dc
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
//package com.company; import java.util.*; import java.io.*; import java.util.Scanner; public class A { public static void main(String[] args) throws Exception{ // write your code here Scanner sc = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter(new File("output.txt")); int n = sc.nextInt(); int k = sc.nextInt(); int[] sp = new int[n]; for (int i=0;i<n;i++){ sp[i]=sc.nextInt(); } int t = 0; int index = k-1; while(t<n){ if(sp[index]>0){ out.println(index+1); break; } else if (index+1>=n){ index=0; } else { index++; } t++; } out.close(); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 8
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
325c9879e6067ce9fef7277a5b60643d
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
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.FileReader; import java.io.FileWriter; //import java.lang.StringBuilder; import java.util.StringTokenizer; //import java.lang.Comparable; //import java.util.Arrays; //import java.util.HashMap; //import java.util.ArrayList; //import java.util.LinkedList; public class QuizzLeague { //static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //static PrintWriter out = new PrintWriter(System.out); //static StringBuilder sb = new StringBuilder(); public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("input.txt")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); boolean[] b = new boolean[n]; st = new StringTokenizer(in.readLine()); for(int i = 0; i < n; i++) { b[i] = (Integer.parseInt(st.nextToken()) == 0); } int i = k-1; while(b[i]) { i++; i %= n; } i++; out.print(i); out.close(); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 8
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
cf61e1ed4e552744163a4b668104831e
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Properties; import java.util.Scanner; import java.util.StringTokenizer; /** * Created by sanan on 4/12/15. */ public class Main { static int c; static String S; static String [] SS1; static int n,k; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); readFromFile("input.txt","output.txt"); out.flush(); } static String [] readFromFile(String input,String output) { String [] SS = new String[2]; try (BufferedReader reader = new BufferedReader(new FileReader(new File(input))); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(output)))) { String S = null; int num = 0; while ((S = reader.readLine()) != null) { num++; if (num == 1) { SS[0] = S.split("\\s")[0]; SS[1] = S.split("\\s")[1]; } else { SS1 = S.split("\\s"); } } int [] a = new int[Integer.parseInt(SS[0])]; for (int i = 0; i < a.length; i++) { a[i]=Integer.parseInt(SS1[i]); } boolean flag = false; for (int i = Integer.parseInt(SS[1])-1; i <a.length ; i++) { if (a[i] == 1) { writer.write(Integer.toString(i+1)); flag = true; break; } } if (!flag) { for (int i = 0; i < Integer.parseInt(SS[1])-1; i++) { if (a[i] == 1) { writer.write(Integer.toString(i+1)); break; } } } } catch (IOException e) { e.printStackTrace(); } return SS; } static void writeToFile(String pathName,String [] SS) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(pathName)))) { if (SS[0].equals("front")) { if (SS[1].equals("1")) { writer.write("L"); } else { writer.write("R"); } } else { if (SS[1].equals("1")) { writer.write("R"); } else { writer.write("L"); } } } catch (IOException e) { e.printStackTrace(); } } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 8
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
00700ba4372b6a402d35247675b0e44c
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.*; import java.util.*; public class kuchBhi{ public static void main(String[] args) throws Throwable{ // BufferedReader br = new BufferedReader(new FileReader("input.txt")); // String in = br.nextLine(); Scanner sc = new Scanner(new File("input.txt")); BufferedWriter br1 = new BufferedWriter(new FileWriter("output.txt")); int n = sc.nextInt(); int k = sc.nextInt(); int ar[] = new int[n+1]; for(int i=1;i<=n;i++) ar[i] = sc.nextInt(); while(true) { if(ar[k]==1) { br1.write(k+""); break; } k = (k+1)%n; if(k==0) k = n; } sc.close(); br1.close(); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 8
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
84642511f543d2233ea6da0fc0901398
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.*; import java.util.*; public final class code // public class Main // class code // public class Solution { static void solve()throws IOException { int n=nextInt(); int k=nextInt(); int a[]=new int[n+1]; for(int i=1;i<=n;i++) { a[i]=nextInt(); } while(a[k]==0) { if(k==n) k=1; else k++; } out.println(k); } /////////////////////////////////////////////////////////// static final long mod=(long)(1e9+7); static final int inf=(int)(1e9+1); static final int maxn=(int)(1e6); static final long lim=(long)(1e18); public static void main(String args[])throws IOException { br=new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); out=new PrintWriter(new FileOutputStream("output.txt")); solve(); // int t=nextInt(); // for(int i=1;i<=t;i++) // { // // out.print("Case #"+i+": "); // solve(); // } out.close(); } static int max(int ... a) { int ret=a[0]; for(int i=1;i<a.length;i++) ret=Math.max(ret,a[i]); return ret; } static int min(int ... a) { int ret=a[0]; for(int i=1;i<a.length;i++) ret=Math.min(ret,a[i]); return ret; } static void debug(Object ... a) { System.out.print("> "); for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } static void debug(int a[]){debuga(Arrays.stream(a).boxed().toArray());} static void debug(long a[]){debuga(Arrays.stream(a).boxed().toArray());} static void debuga(Object a[]) { System.out.print("> "); for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } static Random random; static BufferedReader br; static StringTokenizer st; static PrintWriter out; static String nextToken()throws IOException { while(st==null || !st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } static String nextLine()throws IOException { return br.readLine(); } static int nextInt()throws IOException { return Integer.parseInt(nextToken()); } static long nextLong()throws IOException { return Long.parseLong(nextToken()); } static double nextDouble()throws IOException { return Double.parseDouble(nextToken()); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 8
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
9f2deafa2d067f00e7cd4b798f40fb72
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.IOException; import java.util.InputMismatchException; import java.io.FileOutputStream; import java.io.FileInputStream; import java.util.NoSuchElementException; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream("input.txt"); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream("output.txt"); } catch (IOException e) { throw new RuntimeException(e); } InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out){ int n = in.ri(), k = in.ri() - 1; int[] a = IOUtils.readIntArray(in, n); for(int i = k; i < 3*a.length; i++) if (a[i%n] == 1){ out.print((i%n) + 1); return; } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int ri(){ return readInt(); } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void close() { writer.close(); } public void print(int i) { writer.print(i); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 8
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
18d02a9ac16b2a9658c5f216abbd4da3
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.*; import java.util.*; public class kuchBhi{ public static void main(String[] args) throws Throwable{ // BufferedReader br = new BufferedReader(new FileReader("input.txt")); // String in = br.nextLine(); Scanner sc = new Scanner(new File("input.txt")); BufferedWriter br1 = new BufferedWriter(new FileWriter("output.txt")); int n = sc.nextInt(); int k = sc.nextInt(); int ar[] = new int[n+1]; for(int i=1;i<=n;i++) ar[i] = sc.nextInt(); while(true) { if(ar[k]==1) { br1.write(k+""); break; } k = (k+1)%n; if(k==0) k = n; } sc.close(); br1.close(); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 8
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
8691b63a323a50c7cd0972826fe0bad1
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Closeable; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.StringTokenizer; public class A implements Closeable { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); A() throws IOException { reader = new BufferedReader(new FileReader("input.txt")); writer = new PrintWriter(new FileWriter("output.txt")); } StringTokenizer stringTokenizer; String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.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()); } private int MOD = 1000 * 1000 * 1000 + 7; int sum(int a, int b) { a += b; return a >= MOD ? a - MOD : a; } int product(int a, int b) { return (int) (1l * a * b % MOD); } int pow(int x, int k) { int result = 1; while (k > 0) { if (k % 2 == 1) { result = product(result, x); } x = product(x, x); k /= 2; } return result; } int inv(int x) { return pow(x, MOD - 2); } void solve() throws IOException { int n = nextInt(), k = nextInt() - 1; int[] a = new int[n]; for(int i = 0; i < n; i++) { a[i] = nextInt(); } while(a[k] == 0) { k = (k + 1) % n; } writer.println(k + 1); } public static void main(String[] args) throws IOException { try (A a = new A()) { a.solve(); } } @Override public void close() throws IOException { reader.close(); writer.close(); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 8
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
d21667d0dff2e1d1e92e7d524ddaafac
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class B120 { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter(new File("output.txt")); int N = in.nextInt(); int K = in.nextInt()-1; int[] A = new int[N]; for (int n=0; n<N; n++) { A[n] = in.nextInt(); } while (A[K] == 0) { K = (K+1)%N; } out.println(K+1); out.close(); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 8
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
69add6e7ce3db22e3d9ce8e90b91ff9b
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.*; import java.util.StringTokenizer; /** * 120B * ΞΈ(n) time * ΞΈ(n) space * * @author artyom */ public class _120B implements Runnable { private BufferedReader in; private StringTokenizer tok; private Object solve() throws IOException { int n = nextInt(), k = nextInt(); int[] a = readIntArray(n); for (int i = k - 1; i < n; i++) { if (a[i] == 1) { return i + 1; } } for (int i = 0; i < k - 1; i++) { if (a[i] == 1) { return i + 1; } } return -1; } //-------------------------------------------------------------- public static void main(String[] args) { new _120B().run(); } @Override public void run() { try { in = new BufferedReader(new FileReader("input.txt")); PrintWriter out = new PrintWriter(new FileWriter("output.txt")); tok = null; out.print(solve()); in.close(); out.close(); } catch (IOException e) { System.exit(0); } } private String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private int[] readIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 8
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
fe893854c0a0412f3b65bc65a17c15e5
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
//package que_a; import java.io.*; import java.util.*; import java.math.*; public class utkarsh { InputStream is; PrintWriter out; long mod = (long) (1e9 + 7), inf = (long) (3e18); void solve() { int n = ni(), k = ni()-1; int a[] = na(n); while(a[k] == 0) { k = (k + 1) % n; } out.println(k+1); } long mp(long b, long e) { long r = 1; while(e > 0) { if((e&1) == 1) r = (r * b) % mod; b = (b * b) % mod; e >>= 1; } return r; } //---------- I/O Template ---------- public static void main(String[] args) { new utkarsh().run(); } void run() { File fi = new File("input.txt"); File fo = new File("output.txt"); try{ is = new FileInputStream(fi); out = new PrintWriter(fo); } catch (FileNotFoundException e){ System.out.printf("Error %s\n",e); } solve(); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 8
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
3017c47f03ff574db7216f0d5605bcaa
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class B { private void Problem() throws IOException { int n = nextInt(), k = nextInt(), a[] = new int[n+1]; for (int i = 1; i < n + 1; i ++) a[i] = nextInt(); for (int i = k; i < n + 1; i ++) { if (a[i] == 1) { out.print(i); break; } if (i == n) i = 0; } } BufferedReader in; StringTokenizer tokenizer; PrintWriter out; public void Solution() throws IOException { in = new BufferedReader(new FileReader(new File("input.txt"))); out = new PrintWriter(new File("output.txt")); tokenizer = null; Problem(); in.close(); out.close(); } public static void main(String[] args) throws IOException { new B().Solution(); } int nextInt() throws IOException, NumberFormatException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException, NumberFormatException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException, NumberFormatException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 6
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
218e3881c8ceea25cd8f09d8b5981744
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.*; import java.util.*; public class CodeForces implements Runnable { void solve() throws IOException { int n = nextInt(); int p = nextInt(); int []a= new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); if(a[p-1]==1) writer.println(p); else { boolean find = false; int pos = 0; for(int i=p;i<n;i++) if(a[i]==1) { pos = i; find = true; break; } if(!find) { for(int i=0;i<p;i++) if(a[i]==1) { pos = i; break; } } writer.println(pos+1); } } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { //reader = new BufferedReader(new InputStreamReader(System.in)); //writer = new PrintWriter(System.out); reader = new BufferedReader(new FileReader("input.txt")); writer = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); tokenizer = null; solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) { new CodeForces().run(); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 6
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
49715cf2364e949f433e2d5a7b882462
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import com.sun.org.apache.bcel.internal.generic.ARRAYLENGTH; public class CodeForces { public void solve() throws IOException { int n=nextInt(); int k=nextInt()-1; int arr[]=new int[n]; for(int i=0;i<n;i++){ arr[i]=nextInt(); } while(true){ if(arr[k]==1) break; k++; if(k==n) k=0; } out.print(k+1); } public static void main(String[] args) { new CodeForces().run(); } int NOD(int a, int b) { while (a != 0 && b != 0) { if (a >= b) a = a % b; else b = b % a; } return a + b; } BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; public void run() { try { //reader = new BufferedReader(new InputStreamReader(System.in)); reader = new BufferedReader(new FileReader("input.txt")); tokenizer = null; //out = new PrintWriter(System.out); out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); // long t=new Date().getTime(); solve(); // writer.println(t-new Date().getTime()); reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 6
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
e3e6094eb74361561e1559d94612debe
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public BufferedReader input; public PrintWriter output; public StringTokenizer in = new StringTokenizer(""); public static void main(String[] args) throws IOException { new Main(); } Main() throws IOException{ input = new BufferedReader( new FileReader ("input.txt") ); output = new PrintWriter( new FileWriter("output.txt") ); int n = nextInt(); int k = nextInt()-1; int mas [] = new int [n]; for (int i=0; i<n; i++){ mas[i] = nextInt(); } while (mas[k]!=1){ k++; if (k>n-1) k=0; } output.print(k+1); input.close(); output.close(); } private int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextString()); } private String nextString() throws IOException { while (!in.hasMoreTokens()){ String st = input.readLine(); in = new StringTokenizer(st); } return in.nextToken(); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 6
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
fffe41584aa0dd6f1a22130f2a096b81
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("input.txt")); BufferedWriter out = new BufferedWriter(new FileWriter("output.txt")); int n = in.nextInt(); int k = in.nextInt(); boolean[] a = new boolean[n]; k--; for (int i = 0; i < n; i++) a[i] = (in.nextInt() == 0 ? true : false); int i; for (i = k; i <= n; i++) { i %= n; if (!a[i]) break; } String s = ""+(i+1); out.write(s); out.close(); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 6
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
023ae5ddce1be0f6e404cfa815a86f14
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.*; import java.util.*; public class TaskB { BufferedReader br; PrintWriter out; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return "-1"; } stok = new StringTokenizer(s); } return stok.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String nextLine() throws IOException { return br.readLine(); } void solve() throws IOException { int n = nextInt(), k = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } for (int i = k - 1; ; i++) { if (i >= n) { i -= n; } if (a[i] == 1) { out.print(i + 1); break; } } } void run() throws IOException { br = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); // br = new BufferedReader(new InputStreamReader(System.in)); // out = new PrintWriter(System.out); solve(); br.close(); out.close(); } public static void main(String[] args) throws IOException { // Locale.setDefault(Locale.US); new TaskB().run(); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 6
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt
PASSED
3906fe4dfa0442c1cbaa3cf8da6370df
train_002.jsonl
1318919400
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class solution { void solve() throws IOException { int n = nextInt(), k = nextInt() - 1; int[] z = new int[1010]; for (int i = 0; i < n; ++i) { z[i] = nextInt(); } while (true) { if (z[k] == 1) { out.println(k + 1); break; } else { k = (k + 1) % n; } } } BufferedReader br; StringTokenizer st; PrintWriter out; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return "-1"; } st = new StringTokenizer(s); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } void run() throws IOException { br = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); solve(); out.close(); br.close(); } public static void main(String[] args) throws IOException { new solution().run(); } }
Java
["5 5\n0 1 0 1 0", "2 1\n1 1"]
1 second
["2", "1"]
null
Java 6
input.txt
[ "implementation" ]
1378b4c9ba8029d310f07a1027a8c7a6
The first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
1,100
Print the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
output.txt