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
eaa8e695d95246b3f312eea00ac892c7
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x>=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class TheClosestPair { static int mod = 1000000007; static long L_INF = (1L << 60L); 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[500005]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { Reader in = new Reader(); int i, t, n, j, k; n = in.nextInt(); k = in.nextInt(); StringBuilder ans = new StringBuilder(); int limit = (n * (n - 1)) / 2; if (k >= limit) { System.out.println("no solution"); return; } ans.append("0 0\n"); for (i = 0; i < n - 1; i++) { ans.append("0 " + (i + 1) + "\n"); } System.out.println(ans); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
fb997123fc453862886bcb94d32c04f5
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.awt.Point; import java.util.Collections; import java.util.Comparator; import java.util.Scanner; public class Mainclass { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n,k; n=scan.nextInt(); k=scan.nextInt(); int[] arr=new int[n]; int tot=(n*(n-1))/2; if(tot>k) { for(int i=0;i<n;i++) { System.out.println(0+" "+i); } return; } System.out.println("no solution"); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
1ac200bf32dd45622038f7391ae0f956
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class A311 { public static long mod = 1000000007; public static long INF = (1L << 60); static FastScanner2 in = new FastScanner2(); static OutputWriter out = new OutputWriter(System.out); public static void main(String[] args) { int n=in.nextInt(); int k=in.nextInt(); if(k>=((n*(n-1))/2)) { System.out.println("no solution"); return; } else { for(int i=1;i<=n;i++) { out.println("2000 "+i); } } out.close(); } public static long pow(long x, long n) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p)) { if ((n & 1) != 0) { res = (res * p); } } return res; } public static long pow(long x, long n, long mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (res * p % mod); } } return res; } public static long gcd(long n1, long n2) { long r; while (n2 != 0) { r = n1 % n2; n1 = n2; n2 = r; } return n1; } public static long lcm(long n1, long n2) { long answer = (n1 * n2) / (gcd(n1, n2)); return answer; } static class FastScanner2 { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine() { String fullLine = null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public int nextInt() { return Integer.parseInt(next()); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
847b081c90b803ce2df5daac555a2776
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(), k = sc.nextInt(); if(k >= n * (n - 1) / 2) out.println("no solution"); else for(int i = 0; i < n; ++i) out.println(0 + " " + i); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
0fe4654478df78013bae804e2adbe5a1
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class SolutionA{ public static void main(String[] args){ new SolutionA().run(); } void solve(){ int n = in.nextInt(); int k = in.nextInt(); if( k >= n * (n - 1)/2) { out.println("no solution"); return; } int cnt = 10000; for(int i = 0; i<n; i++){ out.println("0 " + (i * cnt)); } } class Pair implements Comparable<Pair>{ int x, y; Pair(int x, int y){ this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if(o.x == x) return ((Integer) y).compareTo(o.y); return ((Integer) x).compareTo(o.x); } } FastScanner in; PrintWriter out; void run(){ in = new FastScanner(System.in); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.close(); } void runIO(){ try{ in = new FastScanner(new File("expr.in")); out = new PrintWriter(new FileWriter(new File("expr.out"))); solve(); out.close(); }catch(Exception ex){ ex.printStackTrace(); } } class FastScanner{ BufferedReader bf; StringTokenizer st; public FastScanner(File f){ try{ bf = new BufferedReader(new FileReader(f)); } catch(IOException ex){ ex.printStackTrace(); } } public FastScanner(InputStream is){ bf = new BufferedReader(new InputStreamReader(is)); } String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(bf.readLine()); } catch(IOException ex){ ex.printStackTrace(); } } return st.nextToken(); } char nextChar(){ return next().charAt(0); } int nextInt(){ return Integer.parseInt(next()); } double nextDouble(){ return Double.parseDouble(next()); } float nextFloat(){ return Float.parseFloat(next()); } String nextLine(){ try{ return bf.readLine(); } catch(Exception ex){ ex.printStackTrace(); } return ""; } long nextLong(){ return Long.parseLong(next()); } BigInteger nextBigInteger(){ return new BigInteger(next()); } BigDecimal nextBigDecimal(){ return new BigDecimal(next()); } int[] nextIntArray(int n){ int a[] = new int[n]; for(int i = 0; i < n; i++) a[i] = Integer.parseInt(next()); return a; } long[] nextLongArray(int n){ long a[] = new long[n]; for(int i = 0; i < n; i++) a[i] = Long.parseLong(next()); return a; } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
520d75ff8237bd064f4e3681de4a30a4
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
// package may2020; import java.util.*; import java.lang.*; import java.math.*; import java.io.*; public class C { public static void main(String[] args) throws IOException { FastReader scn = new FastReader(); OutputStream out = new BufferedOutputStream(System.out); int n = scn.nextInt(),k = scn.nextInt(); if(k>=(n*(n-1))/2) { out.write("no solution".getBytes()); out.close(); System.exit(0); } for(int i =0;i<n;i++) { out.write(("0 "+i+"\n").getBytes()); } out.close(); } // static int ub(long[] a, long val) { // int l=0, r=a.length; // // while(r>l) { // int x = (r+l)>>1; // if(val>=a[x]) { // l=x+1; // }else { // r=x; // } // } // return l; // } // static int lb(long[] a, long val) { // int l = 0; // int r = a.length; // while(r>l) { // int x = (l+r)>>1; // if(a[x]>=val) { // r=x; // }else { // l=x+1; // } // } // return l; // } 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
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
dc8fcb3ebd8ad63a200bc3a7dfb62746
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; public class Main { 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[100001]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { Reader s=new Reader();PrintWriter pw=new PrintWriter(System.out); int n=s.nextInt(),k=s.nextInt();int i; if((n*(n-1))/2<=k)pw.write("no solution"); else{ for(i=0;i<n;i++){ pw.write("0 "+String.valueOf(i)+"\n"); } } pw.flush();pw.close(); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
d50dd394500dac62238393c244b04509
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.*; import java.util.*; 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); Task solver = new Task(); solver.solve(in, out); out.close(); } static class Task { public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(), k = in.nextInt(); if (2 * k >= n * (n - 1)) { out.println("no solution"); return; } for (int i = 0; i < n; i++) { out.printf("0 %d\n", i); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
2d92ebc7bc0f7dac2b3cc4276e05e2b3
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.FileInputStream; import java.util.ArrayList; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); ATheClosestPair solver = new ATheClosestPair(); solver.solve(1, in, out); out.close(); } static class ATheClosestPair { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), k = in.nextInt(); if (n * (n - 1) / 2 <= k) { out.println("no solution"); out.flush(); return; } else { for (int i = 0; i < n; i++) { out.println("0 " + i); } } out.flush(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public InputReader(FileInputStream file) { this.stream = file; } 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 = (res << 3) + (res << 1) + c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static class OutputWriter { private final PrintWriter writer; private ArrayList<String> res = new ArrayList<>(); private StringBuilder sb = new StringBuilder(""); public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(Object... objects) { for (int i = 0; i < objects.length; i++) { sb.append(objects[i]); } res.add(sb.toString()); sb = new StringBuilder(""); } public void close() { writer.close(); } public void flush() { for (String str : res) writer.printf("%s\n", str); res.clear(); sb = new StringBuilder(""); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
6210882a7c7ffdd3ffba5065bd753186
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //(new FileReader("input.in")); StringBuilder out = new StringBuilder(); StringTokenizer tk; //PrintWriter pw = new PrintWriter("output.out", "UTF-8"); tk = new StringTokenizer(in.readLine()); int n = parseInt(tk.nextToken()),k = parseInt(tk.nextToken()); if(k >= n*(n-1)/2) { System.out.println("no solution"); return; } for(int i=0; i<n; i++) out.append("0 ").append(i).append("\n"); System.out.print(out); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
a613336f8b0418aa42081984fbf3b76f
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
/* [ ( ^ _ ^ ) ] */ import java.io.*; import java.util.*; public class test { int INF = (int)1e9; long MOD = 1000000007; void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); int k = in.nextInt(); int x = n * (n-1) / 2; if(k>=x) { out.println("no solution"); } else { for(int i=1; i<=n; i++) { out.println("0 "+i); } } } public static void main(String[] args) throws IOException { if(args.length>0 && args[0].equalsIgnoreCase("d")) { DEBUG_FLAG = true; } InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); int t = 1;//in.nextInt(); long start = System.nanoTime(); while(t-- >0) { new test().solve(in, out); } long end = System.nanoTime(); debug("\nTime: " + (end-start)/1e6 + " \n\n"); out.close(); } static boolean DEBUG_FLAG = false; static void debug(String s) { if(DEBUG_FLAG) System.out.print(s); } public static void show(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { static BufferedReader br; static StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
5e035c98206066c047bf804fc1987ff4
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Nhat M. Nguyen */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { InputReader in; OutputWriter out; public void solve(int testNumber, InputReader in_, OutputWriter out_) { in = in_; out = out_; int n = in.nextInt(); int k = in.nextInt(); if (k >= n * (n - 1) / 2) { out.println("no solution"); return; } for (int i = 0; i < n; i++) { out.println("0 ", i + 1); } } } static class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (Object object : objects) { writer.print(object); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private final int BUFFER_SIZE = 32768; private InputStream stream; private byte[] buffer = new byte[BUFFER_SIZE + 1]; private int pointer = 1; private int readLength = 0; private int lastWhiteSpace = '\n'; public InputReader(InputStream stream) { this.stream = stream; } private void fillBuffer() { try { readLength = stream.read(buffer, 1, BUFFER_SIZE); } catch (IOException e) { throw new RuntimeException(e); } } private byte get() { if (pointer > readLength) { pointer = 1; fillBuffer(); if (readLength <= 0) return -1; } return buffer[pointer++]; } public char nextChar() { int c = get(); while (isWhiteSpace(c)) { c = get(); } return (char) c; } public int nextInt() { int c = nextChar(); int sign = 1; if (c == '-') { sign = -1; c = get(); } int abs = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); abs *= 10; abs += c - '0'; c = get(); } while (!isWhiteSpace(c)); lastWhiteSpace = c; return abs * sign; } public boolean isWhiteSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
ced1773243d0a660c44b22bda09052d3
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
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.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); ClosestPair solver = new ClosestPair(); solver.solve(1, in, out); out.close(); } static class ClosestPair { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); int val = (n * (n - 1)) / 2; val--; if (k > val) { out.println("no solution"); return; } for (int i = 1; i <= n; i++) { out.println(0 + " " + 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 nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
1d632b5f8b7e76a45e07ac138c1b42ae
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.*; import java.util.*; public class R185qATheClosestPair { public static void main(String args[]) { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = in.nextInt(); int k = in.nextInt(); long x[] = new long[n]; long y[] = new long[n]; for(int i=0;i<n;i++) x[i] = i; long curr = 0,cnt = 0; for(int j=n-1;j>=0;j--){ y[j] = curr; cnt++; curr += cnt; } int total = 0; long d = Long.MAX_VALUE; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ total++; if( (x[j] - x[i]) * (x[j] - x[i]) >= d ) break; d = Math.min(d, (x[i] - x[j])*(x[i] - x[j]) + (y[i] - y[j])*(y[i] - y[j])); } } if(total > k){ for(int i=0;i<n;i++) w.println(x[i] + " " + y[i]); } else w.println("no solution"); w.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
d311afec306215143eef1f9076321941
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main extends PrintWriter { BufferedReader in; StringTokenizer stok; final Random rand = new Random(31); final int inf = (int) 1e9; final long linf = (long) 1e18; final static String IO = "_std"; void solve() throws IOException { int n = nextInt(); int k = nextInt(); if (k >= n * (n - 1) / 2) { println("no solution"); return; } for (int i = 0; i < n; i++) { print("0 "); println(i); } } Main() { super(System.out); in = new BufferedReader(new InputStreamReader(System.in)); } Main(String fileIn, String fileOut) throws IOException { super(fileOut); in = new BufferedReader(new FileReader(fileIn)); } public static void main(String[] args) throws IOException { Main main; if ("_std".equals(IO)) { main = new Main(); } else if ("_iotxt".equals(IO)) { main = new Main("input.txt", "output.txt"); } else { main = new Main(IO + ".in", IO + ".out"); } main.solve(); main.close(); } String next() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = in.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.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()); } int[] nextIntArray(int len) throws IOException { int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = nextInt(); } return a; } int[] nextIntArraySorted(int len) throws IOException { int[] a = nextIntArray(len); shuffle(a); Arrays.sort(a); return a; } void shuffle(int[] a) { for (int i = 1; i < a.length; i++) { int x = rand.nextInt(i + 1); int _ = a[i]; a[i] = a[x]; a[x] = _; } } void shuffleAndSort(int[] a) { shuffle(a); Arrays.sort(a); } boolean nextPermutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) { if (p[a] < p[a + 1]) for (int b = p.length - 1; ; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } } return false; } <T> List<T>[] createAdjacencyList(int n) { List<T>[] res = new List[n]; for (int i = 0; i < n; i++) { res[i] = new ArrayList<>(); } return res; } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
685c99ba13be239f69d77c3a7b7add57
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
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.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); if (k >= ((n - 1) * n) / 2) out.println("no solution"); else { for (int i = 1; i < n; i++) { out.println("1 " + (i * 2)); } out.println("1 " + (n * 2 - 1)); } } } static class InputReader { private StringTokenizer tokenizer; private BufferedReader reader; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private void fillTokenizer() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } } public String next() { fillTokenizer(); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
480824a2aa6da1911332cbe0e81d1492
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
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 ATailouloute */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; QuickScanner in = new QuickScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, QuickScanner in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); int mk = (n * (n - 1)) / 2; if (k >= mk) out.println("no solution"); else { for (int i = 0; i < n; i++) { out.println("0 " + i); } } } } static class QuickScanner { BufferedReader br; StringTokenizer st; InputStream is; public QuickScanner(InputStream stream) { is = stream; br = new BufferedReader(new InputStreamReader(stream), 32768); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
622c097fc8954695781e83fe48824b75
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.util.*; public class RookBishopKing { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k= sc.nextInt(); int tle = n*(n-1)/2; if (tle<=k){ System.out.println("no solution"); }else{ for (int i=0;i<n;++i){ System.out.println("0 " + i); } } sc.close(); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
c7996fee4efbbb50dcb7defc716234f7
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.StringTokenizer; import java.lang.*; import java.math.BigInteger; import java.util.Arrays; import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; public class Main { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; StringBuilder ans=new StringBuilder(""); st=new StringTokenizer(br.readLine()); long n=Long.parseLong(st.nextToken()); long k=Long.parseLong(st.nextToken()); long tot=(n*(n-1))/2; if(tot>k) for(int i=0;i<n;i++) System.out.println("0 "+i); else System.out.print("no solution"); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
3839ebe1c3dfc42d396c33ffc789f821
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.text.DecimalFormat; import java.lang.Math; import java.util.Iterator; public class C47{ static class Pair implements Comparable<Pair>{ int v; int i; public Pair(int v, int i) { this.v = v; this.i = i; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return this.v-o.v; } } public static boolean isPrime(long n){ if(n < 2){ return false; } if(n%2==0){ return n==2; } if(n%3==0){ return n==3; } long i = 5; long h = (long)Math.floor(Math.sqrt(n)+1); while(i <= h){ if(n%i==0){ return false; } if(n%(i+2)==0){ return false; } i += 6; } return true; } public static int gcd(int a, int b){ return b==0? a:gcd(b, a%b); } public static long bSearch(int n,ArrayList<Long> A){ int s = 0; int e = A.size()-1; while(s<=e){ int m = s+(e-s)/2; if(A.get(m)==(long)n){ return A.get(m); } else if(A.get(m)>(long)n){ e = m-1; } else{ s = m+1; } } return A.get(s); } static class Point implements Comparable<Point>{ int x; int y; public Point(int x, int y){ this.x = x; this.y = y; } @Override public int compareTo(Point o) { // TODO Auto-generated method stub if(this.x==o.x){ return this.y-o.y; } return this.x-o.x; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); if(k>=(n*(n-1))/2){ System.out.println("no solution"); return; } for(int i = 0; i < n; i++){ System.out.println(1+" "+i); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
46ef12b6330bbb11a4ac4ccc15a8c6e0
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.util.*; public class TheClosestPair { public static void main(String[] args) { Scanner cin = new Scanner(System.in); int n = cin.nextInt(); int k = cin.nextInt(); int a = n * (n - 1) / 2; if (a <= k) { System.out.println("no solution"); } else { for (int i = 0; i < n; i++) { System.out.println(0 + " " + i); } } cin.close(); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
f15c667291750a001cc60bf3f15783fd
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out){ int n = in.ri(), k = in.ri(); if ((n * (n - 1) / 2) > k){ for(int i = 0; i < n; i++) { out.printLine(0, i); } } else out.print("no solution"); } } 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 print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
d760a635771f5f3170ff62ea3a7bc3c8
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class TheClosestPair { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; static void solve() throws Exception { int n = nextInt(), k = nextInt(); if ((n - 1) * n / 2 <= k) out.println("no solution"); else for (int i = 0; i < n; i++) out.println(0 + " " + i); } public static void main(String args[]) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } static int nextInt() throws IOException { return Integer.parseInt(next()); } static int[] nextIntArray(int len, int start) throws IOException { int[] a = new int[len]; for (int i = start; i < len; i++) a[i] = nextInt(); return a; } static long nextLong() throws IOException { return Long.parseLong(next()); } static long[] nextLongArray(int len, int start) throws IOException { long[] a = new long[len]; for (int i = start; i < len; i++) a[i] = nextLong(); return a; } static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
d5da6ffc61cc632f7de0ca8c7c06a6f9
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
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.Comparator; import java.util.List; import java.util.InputMismatchException; public class Main { IIO io; Main(IIO io) { this.io = io; } public static void main(String[] args) throws IOException { ConsoleIO io = new ConsoleIO(); Main m = new Main(io); m.solve(); io.flush(); // Tester test = new Tester();test.run(); } public void solve() { int[] l = io.readIntArray(); int n = l[0]; int k = l[1]; int m = (n - 1) * n / 2; if (m <= k) { io.writeLine("no solution"); } else { for (int i = 0; i < n; i++) { io.writeLine("0 " + Integer.toString(i)); } } } } class ConsoleIO extends BaseIO { BufferedReader br; PrintWriter out; public ConsoleIO(){ br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } public void flush(){ 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 String readLine() { try { return br.readLine(); } catch (Exception ex){ return ""; } } public int read(){ try { return br.read(); } catch (Exception ex){ return -1; } } } abstract class BaseIO implements IIO { public long readLong() { return Long.parseLong(this.readLine()); } public int readInt() { return Integer.parseInt(this.readLine()); } public int[] readIntArray() { String line = this.readLine(); String[] nums = line.split(" "); int[] res = new int[nums.length]; for (int i = 0; i < nums.length; i++) { res[i] = Integer.parseInt(nums[i]); } return res; } public long[] readLongArray() { String line = this.readLine(); String[] nums = line.split(" "); long[] res = new long[nums.length]; for (int i = 0; i < nums.length; i++) { res[i] = Long.parseLong(nums[i]); } return res; } } interface IIO { void writeLine(String s); void writeInt(int a); void writeWord(String s); String readLine(); long readLong(); int readInt(); int read(); int[] readIntArray(); long[] readLongArray(); }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
92cbb803f03caf74de2c8824ccd96aa6
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author dipankar12 */ import java.io.*; import java.util.*; public class r185a { public static void main(String args[]) { fastio in=new fastio(System.in); PrintWriter pw=new PrintWriter(System.out); int n=in.nextInt(); int k=in.nextInt(); n--; if(k>=n*(n+1)/2) pw.println("no solution"); else { n++; for(int i=0;i<n;i++) pw.println(0+" "+i); } pw.close(); } static class fastio { private final InputStream stream; private final byte[] buf = new byte[8192]; private int cchar, snchar; private SpaceCharFilter filter; public fastio(InputStream stream) { this.stream = stream; } public int nxt() { if (snchar == -1) throw new InputMismatchException(); if (cchar >= snchar) { cchar = 0; try { snchar = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snchar <= 0) return -1; } return buf[cchar++]; } public int nextInt() { int c = nxt(); while (isSpaceChar(c)) { c = nxt(); } int sgn = 1; if (c == '-') { sgn = -1; c = nxt(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = nxt(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = nxt(); while (isSpaceChar(c)) { c = nxt(); } int sgn = 1; if (c == '-') { sgn = -1; c = nxt(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = nxt(); } 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 = nxt(); while (isSpaceChar(c)) { c = nxt(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nxt(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = nxt(); while (isSpaceChar(c)) c = nxt(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nxt(); } 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); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
bb396560b15df72cbe8c65c997d0f8ba
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; /** * Created by hama_du on 15/07/31. */ public class A { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int k = in.nextInt(); int pairs = n * (n - 1) / 2; if (k >= pairs) { out.println("no solution"); } else { for (int i = 0; i < n ; i++) { out.println(String.format("%d %d", 0, i)); } } out.flush(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int next() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public char nextChar() { int c = next(); while (isSpaceChar(c)) c = next(); if ('a' <= c && c <= 'z') { return (char) c; } if ('A' <= c && c <= 'Z') { return (char) c; } throw new InputMismatchException(); } public String nextToken() { int c = next(); while (isSpaceChar(c)) c = next(); StringBuilder res = new StringBuilder(); do { res.append((char) c); c = next(); } while (!isSpaceChar(c)); return res.toString(); } public int nextInt() { int c = next(); while (isSpaceChar(c)) c = next(); int sgn = 1; if (c == '-') { sgn = -1; c = next(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = next(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = next(); while (isSpaceChar(c)) c = next(); long sgn = 1; if (c == '-') { sgn = -1; c = next(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = next(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
761fd0b023ecbd99eb8183db0cf39804
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
/*package whatever //do not write package name here */ import java.io.*; import java.util.*; public class GFG { public static void main (String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); if(n*(n-1)/2 > k) { for(int i=0;i<n;i++) System.out.println(0+" "+i); } else System.out.println("no solution"); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
408c344e47f4e279b1ec342f3c4ebe2d
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt() , k = sc.nextInt(); long sum = 1l*n*(n-1)/2; if(sum<=k) { System.out.println("no solution"); return; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) sb.append("0 "+i+"\n"); System.out.print(sb); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException {br = new BufferedReader(new FileReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public String nextLine() throws IOException {return br.readLine();} public long nextLong() throws IOException {return Long.parseLong(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public char nextChar() throws IOException{return next().charAt(0);} public boolean ready() throws IOException {return br.ready();} public int[] nextIntArr() throws IOException{ st = new StringTokenizer(br.readLine()); int[] res = new int[st.countTokens()]; for (int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public char[] nextCharArr() throws IOException{ st = new StringTokenizer(br.readLine()); char[] res = new char[st.countTokens()]; for (int i = 0; i < res.length; i++) res[i] = nextChar(); return res; } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
ff9797fe3cc29609ef07e399ff863495
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { static long mod=((long)1e9)+7;//toString public static int gcd(int a,int b){if(b==0)return a;else return gcd(b,a%b);} public static long pow_mod(long x,long y){long res=1;x=x%mod;while(y > 0){if((y & 1)==1)res=(res * x)%mod;y=y>>1;x =(x * x)%mod;}return res;} public static int lower_bound(int[]arr,int val){int lo=0;int hi=arr.length-1;while(lo<hi){int mid=lo+((hi-lo+1)/2);if(arr[mid]==val){return mid;}else if(arr[mid]>val){hi=mid-1;}else lo=mid;}if(arr[lo]<=val)return lo;else return -1;} public static int upper_bound(int[]arr,int val){int lo=0;int hi=arr.length-1;while(lo<hi){int mid=lo+((hi-lo)/2);if(arr[mid]==val){return mid;}else if(arr[mid]>val){hi=mid;;}else lo=mid+1;}if(arr[lo]>=val)return lo;else return -1;} public static void main (String[] args) throws java.lang.Exception { Reader sn = new Reader(); Print p = new Print(); int n = sn.nextInt(); int k = sn.nextInt(); if(k >= ((n * (n - 1))/2)){ p.printLine("no solution"); } else{ for(int i = 0; i < n; ++i){ p.print("0 "+Integer.toString(i)); p.printLine(""); } } p.close(); } } class Pair implements Comparable<Pair> { int val; int in; Pair(int a, int b){ val=a; in=b; } @Override public int compareTo(Pair o) { if(val==o.val) return Integer.compare(in,o.in); else return Integer.compare(val,o.val); }} class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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 String readWord()throws IOException { 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 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(); } } class Print { private final BufferedWriter bw; public Print() { bw=new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(String str)throws IOException { bw.append(str); } public void printLine(String str)throws IOException { print(str); bw.append("\n"); } public void close()throws IOException { bw.close(); }}
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
a179b85b86e6941dc162f2b9a5a7186d
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.*; import java.util.*; public final class closest_pair { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static Random rnd=new Random(); public static void main(String args[]) throws Exception { int n=sc.nextInt(),cnt=0;long k=sc.nextInt(),curr=n;Pair[] a=new Pair[n]; for(int i=0;i<n;i++) { a[i]=new Pair(0,cnt++); } if((curr*(curr-1))/2>k) { for(Pair p:a) { out.println(p.x+" "+p.y); } } else { out.println("no solution"); } out.close(); } } class Pair { int x,y; public Pair(int x,int y) { this.x=x;this.y=y; } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
69d76ff573d0f40cfc5c2907d35c22ea
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; final long MOD = 1000L * 1000L * 1000L + 7; int[] dx = {0, -1, 0, 1}; int[] dy = {1, 0, -1, 0}; void solve() throws IOException { int n = nextInt(); int k = nextInt(); if (n * (n - 1) / 2 <= k) { out("no solution"); return; } int startx = 1; int starty = 1000 * 1000 * 100; for (int i = 0; i < n; i++) { outln(startx + " " + starty); startx++; starty -= 2001; } } void shuffle(long[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); long tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } public CFA() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFA(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
2f3fdd89027126664ff462646b596b8d
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.util.Scanner; public class TheclosetPair { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); int n = input.nextInt(); long k = input.nextLong(); long p = n*(n-1)/2; if(k>=p){ System.out.println("no solution"); } else{ for(int i=0; i<n;i++){ System.out.println("0 "+i); } } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
de117b95c05dc1c3d921691176c00f8d
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String 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 double d() throws IOException {return Double.parseDouble(s()) ;} 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; } } /////////////////////////////////////////////////////////////////////////////////////////// // RRRRRRRRR AAA HHH HHH IIIIIIIIIIIII LLL // // RR RRR AAAAA HHH HHH IIIIIIIIIII LLL // // RR RRR AAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHHHHHHHHHH III LLL // // RRRRRR AAA AAA HHHHHHHHHHH III LLL // // RR RRR AAAAAAAAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIII LLLLLLLLLLLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIIIII LLLLLLLLLLLL // /////////////////////////////////////////////////////////////////////////////////////////// static int n; static long store[]; public static void main(String[] args)throws IOException { PrintWriter out= new PrintWriter(System.out); Reader sc=new Reader(); int n=sc.i(); int k=sc.i(); if(k>=(n*(n-1))/2) out.println("no solution"); else { for(int i=0;i<n;i++) out.println("0 "+i); } out.flush(); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
a4ffdfb4ccf08303e2e5e44e7e23ed22
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.util.*; public class practice { public static void main(String[] args) { Scanner scn=new Scanner(System.in); int n=scn.nextInt(); int k=scn.nextInt(); if(k>=(n*(n-1)/2)){ System.out.println("no solution"); } else{ for(int i=0;i<n;i++){ System.out.println("0 "+i); } } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
621f994e4c51c1751f98967380ffd7ea
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
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 Nafiur Rahman Khadem Shafin */ public class Main { public static void main (String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader (inputStream); PrintWriter out = new PrintWriter (outputStream); TaskA solver = new TaskA (); solver.solve (1, in, out); out.close (); } static class TaskA { public void solve (int testNumber, InputReader in, PrintWriter out) { /* Problem is very interesting I must admit <3. Find a case to make a n^2 algo get tle. break the inner loop only when diffx * is >= minDistance till now ==> Assumption 1: I will keep all x same but increase y by only 1 ;) then tot is gooing to be * max I think maxTot=(((long)n)*(n-1))/2*/ int n = in.nextInt (), k = in.nextInt (); if ((((long) n)*(n-1))/2<=k) { out.println ("no solution"); } else { for (int i = 0; i<n; i++) { out.println (0+" "+i); } } } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader (InputStream stream) { reader = new BufferedReader (new InputStreamReader (stream)); tokenizer = null; } public String next () { while (tokenizer == null || !tokenizer.hasMoreTokens ()) { try { String str; if ((str = reader.readLine ()) != null) tokenizer = new StringTokenizer (str); else return null;//to detect eof } catch (IOException e) { throw new RuntimeException (e); } } return tokenizer.nextToken (); } public int nextInt () { return Integer.parseInt (next ()); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
6dc213e4af5b5e21d964f1812a1d2978
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.util.Scanner; public class TheClosestPath { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int tot = (n * (n-1))/2; int k = sc.nextInt(); StringBuilder sb = new StringBuilder(); if(k < tot) { for(int i = 0; i < n; i++) { sb.append(0 + " " + i); if(i < n-1)sb.append("\n"); } System.out.println(sb); } else { System.out.println("no solution"); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
32e0ba7d62f6852c2324a4d08cc51563
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.awt.Point; import java.util.*; import java.io.*; import static java.lang.Math.*; public class PracticeProblem { /* * This FastReader code is taken from GeeksForGeeks.com * https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/ * * The article was written by Rishabh Mahrsee */ public 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 FastReader in = new FastReader(); public static PrintWriter out = new PrintWriter(System.out); public static final int MOD = (int)1e9 + 7; public static void main(String[] args) { solve(); out.close(); } public static void solve() { long n = in.nextInt(), k = in.nextInt(); if ((n * (n - 1)) / 2 <= k) { out.println("no solution"); return; } for (int i = 0; i < n; i++) { out.println(0 + " " + i); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
ed5b45c3094f28a667731e61dd4d08b5
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
// package Practice.CF312; import java.util.Scanner; public class CF312C { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int k = s.nextInt(); if(k >= ((n-1)*n)/2){ System.out.println("no solution"); }else{ StringBuilder str = new StringBuilder(); for (int i = 0; i < n; i++) { str.append(0 + " " + i + "\n"); } System.out.println(str.toString()); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 8
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
050d6c7a8124a9441c16295285d3e995
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { InputReader in = new InputReader(); long n = in.nextInt(); long k = in.nextLong(); if ((n * (n - 1)) / 2 <= k) System.out.println("no solution"); else { for(int i = 0 ; i < n;i++) System.out.println(0 +" "+ i); } } static class InputReader { BufferedReader in; StringTokenizer st; public InputReader() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(in.readLine()); } public String next() throws IOException { while (!st.hasMoreElements()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
47bd6ee6b50a1c080722b2bf31368ce0
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.readInt(); int k = in.readInt(); int lim = (n * (n - 1)) / 2; if (k >= lim) { out.println("no solution"); return; } int d = 6000; int curX = 0; int curY = 0; for (int i = 0; i < n; ++i) { out.println(curX + " " + curY); curX++; curY += d; } } } 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() { // InputMismatchException -> UnknownError if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } else if (c == '+') { 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 static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
f1afd6fa849b3d4b6b3828f03a3ff56b
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main (String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] input = in.readLine().split(" "); int n = Integer.parseInt(input[0]); int k = Integer.parseInt(input[1]); int max = n*(n-1)/2; if(k>=max) System.out.println("no solution"); else { for (int i = 0; i < n; i++) { System.out.println("0 "+i); } } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
2a3712fc039bfc69383c7478ecc01daa
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main implements Runnable { private void solve() throws IOException { int n = nextInt(); int k = nextInt(); long[] x = new long[n]; long[] y = new long[n]; for (int i = 0; i < n; i++) { x[i] = i; y[i] = 44444 * i; } int tot = 0; double d = Double.MAX_VALUE; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) { ++tot; if (x[j] - x[i] >= d) break; d = Math.min(d, Math.sqrt((x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]))); } if (tot <= k) out.println("no solution"); else { for (int i = 0; i < n; ++i) out.println(x[i] + " " + y[i]); } } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) return null; eat(line); } return st.nextToken(); } public static void main(String[] args) { new Thread(null, new Main(), "Main", 1 << 28).start(); } private BufferedReader in; private PrintWriter out; private StringTokenizer st; @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); eat(""); solve(); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(566); } } private void eat(String s) { st = new StringTokenizer(s); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
8b2a53420166f50fa30fea8667d9de9f
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.util.*; import java.io.*; public class C312 { class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public InputReader() throws FileNotFoundException { reader = new BufferedReader(new FileReader("d:/input.txt")); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public long nextLong(){ return Long.parseLong(next()); } } public void run(){ InputReader reader = new InputReader(System.in); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = reader.nextInt(), k = reader.nextInt(); int max = (n-1)*n/2; if(k >= max){ out.println("no solution"); }else{ for(int i = 0 ; i < n ; i ++){ out.println(0+" "+i); } } out.flush(); } public static void main(String[] args) { new C312().run(); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
c5f6d3cb3850f87b2273c504a631adf8
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.util.*; public class cf311a { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int max = (n*n-n)/2; if(max <= k) System.out.println("no solution"); else for(int i=0; i<n; i++) System.out.println(0+" "+i); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
4f29c5e1dd6eca4477fc8c982ae50cb6
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class A implements Runnable { public void run() { long startTime = System.nanoTime(); int n = nextInt(); int k = nextInt(); if (n * (n - 1) / 2 > k) { for (int i = 0; i < n; i++) { println("0 " + i); } } else { println("no solution"); } if (fileIOMode) { System.out.println((System.nanoTime() - startTime) / 1e9); } out.close(); } //----------------------------------------------------------------------------------- private static boolean fileIOMode; private static String problemName = "a"; private static BufferedReader in; private static PrintWriter out; private static StringTokenizer tokenizer; public static void main(String[] args) throws Exception { fileIOMode = args.length > 0 && args[0].equals("!"); if (fileIOMode) { in = new BufferedReader(new FileReader(problemName + ".in")); out = new PrintWriter(problemName + ".out"); } else { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } tokenizer = new StringTokenizer(""); new Thread(new A()).start(); } private static String nextLine() { try { return in.readLine(); } catch (IOException e) { return null; } } private static String nextToken() { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(nextLine()); } return tokenizer.nextToken(); } private static int nextInt() { return Integer.parseInt(nextToken()); } private static long nextLong() { return Long.parseLong(nextToken()); } private static double nextDouble() { return Double.parseDouble(nextToken()); } private static BigInteger nextBigInteger() { return new BigInteger(nextToken()); } private static void print(Object o) { if (fileIOMode) { System.out.print(o); } out.print(o); } private static void println(Object o) { if (fileIOMode) { System.out.println(o); } out.println(o); } private static void printf(String s, Object... o) { if (fileIOMode) { System.out.printf(s, o); } out.printf(s, o); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
efb0d11aa72266f224eb6af138dc5513
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class ProblemA { public static void main(String[] args) { OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); Application solver = new Application(); solver.solve(System.in, out); out.close(); } } class Application { public void solve(InputStream in, PrintWriter out) { Scanner scanner = new Scanner(in); int n = scanner.nextInt(); int k = scanner.nextInt(); int m = (n*(n-1))/2; if (m <= k) { out.println("no solution"); } else { for (int i = 0; i < n; i++) { out.println("0 " + i); } } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
1af13c16405816b4913673e11bf29d43
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; /* br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); */ public class Main { private static BufferedReader br; private static StringTokenizer st; private static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //int qq = 1; int qq = Integer.MAX_VALUE; //int qq = readInt(); for(int casenum = 1; casenum <= qq; casenum++) { int n = readInt(); int k = readInt(); int max = n*(n-1)/2; if(max <= k) { pw.println("no solution"); } else { for(int i = 0; i < n; i++) { pw.println(0 + " " + i); } } } pw.close(); } static class State implements Comparable<State> { public String name; public int count; public State(String name, int count) { super(); this.name = name; this.count = count; } public int compareTo(State s) { return count - s.count; } } private static void exitImmediately() { pw.close(); System.exit(0); } private static long readLong() throws IOException { return Long.parseLong(nextToken()); } private static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } private static int readInt() throws IOException { return Integer.parseInt(nextToken()); } private static String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { if(!br.ready()) { exitImmediately(); } st = new StringTokenizer(br.readLine().trim()); } return st.nextToken(); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
34042a7802083daccd6a09de265e10df
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.util.*; import java.io.*; public class Contest185div1A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int p = n * (n - 1)/2; if(p <= k) { System.out.println("no solution"); return ; } for (int i = 1; i <= n; i++) { System.out.println(0 + " " + i); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
aaf06bdd1242f66830234898c4fdb0ce
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.*; import java.util.*; public class A { void solve() throws IOException { in("__std"); out("__std"); int n = readInt(); int k = readInt(); if (n * (n - 1) / 2 > k) { for (int y = 0; y < n; ++y) { println("0 " + y); } } else { println("no solution"); } exit(); } void in(String name) throws IOException { if (name.equals("__std")) { in = new BufferedReader(new InputStreamReader(System.in)); } else { in = new BufferedReader(new FileReader(name)); } } void out(String name) throws IOException { if (name.equals("__std")) { out = new PrintWriter(System.out); } else { out = new PrintWriter(name); } } void exit() { out.close(); System.exit(0); } char readChar() throws IOException { return (char) in.read(); } int readInt() throws IOException { return Integer.parseInt(readToken()); } long readLong() throws IOException { return Long.parseLong(readToken()); } double readDouble() throws IOException { return Double.parseDouble(readToken()); } String readLine() throws IOException { st = null; return in.readLine(); } String readToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } boolean eof() throws IOException { return !in.ready(); } void print(String format, Object ... args) { out.print(new Formatter(Locale.US).format(format, args)); } void println(String format, Object ... args) { out.println(new Formatter(Locale.US).format(format, args)); } void print(Object value) { out.print(value); } void println(Object value) { out.println(value); } void println() { out.println(); } StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) throws IOException { new A().solve(); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
f4a0f01ce2e713a1d248a5aa3d463fa1
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int max = n * (n - 1) / 2; if (max <= k) System.out.println("no solution"); else { for (int i = 0; i < n; i++) { System.out.println("0 " + i); } } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
871094de463158ebaac8b9ffe7d45a50
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.io.*; import java.util.*; public class Main { // static Scanner in; static PrintWriter out; static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;} // static BufferedReader in; public static void main(String[] args) throws Exception { // in = new Scanner(System.in); out = new PrintWriter(System.out); in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // in = new BufferedReader(new InputStreamReader(System.in)); int n = next(); int k = next(); int max = n*(n - 1)/2; if (max <= k) out.println("no solution"); else { for (int i = 0; i < n; i++) { out.println("0 " + i); } } out.close(); } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
bae948ad377a626552c8cadd2368a1bb
train_001.jsonl
1369582200
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x&gt;=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
256 megabytes
import java.util.*; import java.io.*; public class a { static long mod = 1000000007; public static void main(String[] args) throws IOException { //Scanner input = new Scanner(new File("input.txt")); //PrintWriter out = new PrintWriter(new File("output.txt")); input.init(System.in); PrintWriter out = new PrintWriter((System.out)); int n = input.nextInt(), k = input.nextInt(); if(k >= n*(n-1)/2) out.println("no solution"); else { int at = 0, diff = n; for(int i = 0; i<n; i++) { out.println(0+" "+at); at+=diff; diff--; } } out.close(); } static long pow(long base, long p) { if(p==0) return 1; if((p&1) == 0) { long sqrt = pow(base, p/2); return (sqrt*sqrt)%mod; } return (base*pow(base, p-1))%mod; } static long modinv(long x) { return pow(x, mod-2); } /* Sum Interval Tree - uses O(n) space Updates and queries over a range of values in log(n) time */ static class IT { int[] left,right, a, b; long[] val; IT(int n) { left = new int[4*n]; right = new int[4*n]; val = new long[4*n]; a = new int[4*n]; b = new int[4*n]; init(0,0, n); } int init(int at, int l, int r) { a[at] = l; b[at] = r; if(l==r) left[at] = right [at] = -1; else { int mid = (l+r)/2; left[at] = init(2*at+1,l,mid); right[at] = init(2*at+2,mid+1,r); } return at++; } //return the sum over [x,y] long get(int x, int y) { return go(x,y, 0); } long go(int x,int y, int at) { if(at==-1) return 0; if(x <= a[at] && y>= b[at]) return val[at]; if(y<a[at] || x>b[at]) return 0; return go(x, y, left[at]) + go(x, y, right[at]); } //add v to elements x through y void add(int x, int y, long v) { go3(x, y, v, 0); } void go3(int x, int y, long v, int at) { if(at==-1) return; if(y < a[at] || x > b[at]) return; val[at] += (Math.min(b[at], y) - Math.max(a[at], x) + 1)*v; go3(x, y, v, left[at]); go3(x, y, v, right[at]); } } static ArrayList<Integer>[] g; static boolean[] marked; static int[] id, low, stk; static int pre, count; static void scc() { id = new int[g.length]; low = new int[g.length]; stk = new int[g.length+1]; pre = count = 0; marked = new boolean[g.length]; for(int i =0; i<g.length; i++) if(!marked[i]) dfs(i); } static void dfs(int i) { marked[stk[++stk[0]]=i] = true; int min = low[i] = pre++; for(int j: g[i]) { if(!marked[j]) dfs(j); if(low[j] < min) min = low[j]; } if(min < low[i]) low[i] = min; else { while(stk[stk[0]] != i) { int j =stk[stk[0]--]; id[j] = count; low[j] = g.length; } id[stk[stk[0]--]] = count++; low[i] = g.length; } } static class input { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } static String nextLine() throws IOException { return reader.readLine(); } } }
Java
["4 3", "2 100"]
2 seconds
["0 0\n0 1\n1 0\n1 1", "no solution"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
a7846e4ae1f3fa5051fab9139a25539c
A single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).
1,300
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point. The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k.
standard output
PASSED
6628d208c32d411ee6eb1cc115e94c52
train_001.jsonl
1594996500
You are given a tree (connected graph without cycles) consisting of $$$n$$$ vertices. The tree is unrooted β€” it is just a connected undirected graph without cycles.In one move, you can choose exactly $$$k$$$ leaves (leaf is such a vertex that is connected to only one another vertex) connected to the same vertex and remove them with edges incident to them. I.e. you choose such leaves $$$u_1, u_2, \dots, u_k$$$ that there are edges $$$(u_1, v)$$$, $$$(u_2, v)$$$, $$$\dots$$$, $$$(u_k, v)$$$ and remove these leaves and these edges.Your task is to find the maximum number of moves you can perform if you remove leaves optimally.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<26).start(); } //User-defined functions goes here... ArrayList<TreeSet<Integer>> graph; ArrayList<TreeSet<Integer>> leaves; class set_comparator implements Comparator<Integer> { public int compare(Integer node1, Integer node2) { if(leaves.get(node2).size() == leaves.get(node1).size()) return node1 - node2; return leaves.get(node2).size() - leaves.get(node1).size(); } } public void run() { InputReader sc= new InputReader(System.in); PrintWriter w= new PrintWriter(System.out); //Your code goes here... int test = sc.nextInt(); for (int q0=0; q0<test; q0++) { int n = sc.nextInt(); int k = sc.nextInt(); graph = new ArrayList<>(); leaves = new ArrayList<>(); for (int i=0; i<n; i++) { graph.add(new TreeSet<>()); leaves.add(new TreeSet<>()); } for (int i=0; i<n-1; i++) { int u = sc.nextInt()-1; int v = sc.nextInt()-1; graph.get(u).add(v); graph.get(v).add(u); } for (int i=0; i<n; i++) { if(graph.get(i).size() == 1) leaves.get(graph.get(i).first()).add(i); } TreeSet<Integer> set = new TreeSet<>(new set_comparator()); for (int i=0; i<n; i++) { set.add(i); } int ans = 0; while(true){ int node = set.first(); if(leaves.get(node).size() < k) break; for (int i=0; i<k; i++) { int leaf = leaves.get(node).first(); graph.get(leaf).remove(node); graph.get(node).remove(leaf); set.remove(node); set.remove(leaf); leaves.get(node).remove(leaf); if(leaves.get(leaf).contains(node)) leaves.get(leaf).remove(node); if(graph.get(node).size() == 1){ int to = graph.get(node).iterator().next(); set.remove(to); leaves.get(to).add(node); set.add(to); } set.add(node); set.add(leaf); } ans++; } w.println(ans); } w.close(); } }
Java
["4\n8 3\n1 2\n1 5\n7 6\n6 8\n3 1\n6 4\n6 1\n10 3\n1 2\n1 10\n2 3\n1 5\n1 6\n2 4\n7 10\n10 9\n8 10\n7 2\n3 1\n4 5\n3 6\n7 4\n1 2\n1 4\n5 1\n1 2\n2 3\n4 3\n5 3"]
2 seconds
["2\n3\n3\n4"]
NoteThe picture corresponding to the first test case of the example:There you can remove vertices $$$2$$$, $$$5$$$ and $$$3$$$ during the first move and vertices $$$1$$$, $$$7$$$ and $$$4$$$ during the second move.The picture corresponding to the second test case of the example:There you can remove vertices $$$7$$$, $$$8$$$ and $$$9$$$ during the first move, then vertices $$$5$$$, $$$6$$$ and $$$10$$$ during the second move and vertices $$$1$$$, $$$3$$$ and $$$4$$$ during the third move.The picture corresponding to the third test case of the example:There you can remove vertices $$$5$$$ and $$$7$$$ during the first move, then vertices $$$2$$$ and $$$4$$$ during the second move and vertices $$$1$$$ and $$$6$$$ during the third move.
Java 8
standard input
[ "data structures", "implementation", "greedy", "trees" ]
3581b3a6bf7b122b49c481535491399d
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$1 \le k &lt; n$$$) β€” the number of vertices in the tree and the number of leaves you remove in one move, respectively. The next $$$n-1$$$ lines describe edges. The $$$i$$$-th edge is represented as two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$ and $$$y_i$$$ are vertices the $$$i$$$-th edge connects. It is guaranteed that the given set of edges forms a tree. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
2,300
For each test case, print the answer β€” the maximum number of moves you can perform if you remove leaves optimally.
standard output
PASSED
84fc814a7c2e3e6763cf59a4ac8372f5
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.awt.Point; public final class Solution { BufferedReader br; StringTokenizer st; { st = null; br = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) throws Exception { new Solution().run(); } void run() throws Exception { int n = ni(), k = ni(); Node[] g = new Node[n]; for(int i=0; i<n; i++) g[i] = new Node(); int[] deg = new int[n]; List<Point> edges = new ArrayList<>(); HashMap<Point, Integer> map = new HashMap<>(); for(int i=1; i<n; i++) { int a = ni()-1, b = ni()-1; deg[a]++; deg[b]++; g[a].adj.add(b); g[b].adj.add(a); edges.add(new Point(a, b)); map.put(new Point(a, b), 0); } int high = n, low = 1, mid; while(high - low > 4) { mid = (high + low) >> 1; if(valid(mid, k, deg)) { high = mid; } else { low = mid; } } int R = low; for(int i=low; i<=high; i++) { if(valid(i, k, deg)) { R = i; break; } } Queue<Integer> queue = new LinkedList<>(); HashSet<Integer> visited = new HashSet<>(); queue.add(0); int[] incoming = new int[deg.length]; Arrays.fill(incoming, -1); while(!queue.isEmpty()) { int cur = queue.remove(); if(visited.contains(cur)) continue; visited.add(cur); int color = 0; for(int adj : g[cur].adj) { if(visited.contains(adj)) continue; if(incoming[cur] == color) color++; color %= R; if(map.containsKey(new Point(adj, cur))) map.put(new Point(adj, cur), color); else map.put(new Point(cur, adj), color); incoming[adj] = color; color++; queue.add(adj); } } //pl(Arrays.toString(incoming)); StringBuilder res = new StringBuilder(""); res.append(R).append("\n"); for(Point edge : edges) { res.append(map.get(edge) + 1).append(" "); } p(res); } boolean valid(int r, int k, int[] deg) { int count = 0; for(int i=0; i<deg.length; i++) { if(deg[i] > r) {count++;} } return count <= k; } class Node { HashSet<Integer> adj; public Node() { adj = new HashSet<>(); } } // I/O String nt() throws Exception { if(st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine(), " "); } return st.nextToken(); } int ni() throws Exception { return Integer.parseInt(nt()); } long nl() throws Exception { return Long.parseLong(nt()); } void p(Object o) { System.out.print(o); } void pl(Object o) { System.out.println(o); } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
d6b5ab156a4476d20cc25287740e54ae
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
/* ID: tommatt1 LANG: JAVA TASK: */ import java.util.*; import java.io.*; public class cf1141g{ static ArrayList<pair>[] adj; static int min; static int[] col; public static void main(String[] args)throws IOException { BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //BufferedReader bf=new BufferedReader(new FileReader("cf1141g.in")); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("cf1141g.out"))); StringTokenizer st=new StringTokenizer(bf.readLine()); int n=Integer.parseInt(st.nextToken()); int k=Integer.parseInt(st.nextToken()); adj=new ArrayList[n]; int[] deg=new int[n]; int[] ndg=new int[n]; for(int i=0;i<n;i++) { adj[i]=new ArrayList<pair>(); } col=new int[n-1]; for(int i=0;i<n-1;i++) { st=new StringTokenizer(bf.readLine()); int a1=Integer.parseInt(st.nextToken())-1; int a2=Integer.parseInt(st.nextToken())-1; adj[a1].add(new pair(a2,i)); adj[a2].add(new pair(a1,i)); deg[a1]++; deg[a2]++; } for(int i=0;i<n;i++) { ndg[deg[i]]++; } int tmp=n; min=0; for(int i=1;i<n;i++) { if(tmp<=k) { break; } else { min++; tmp-=ndg[i]; } } if(min==0) min++; dfs(0,-1,-1); out.println(min); for(int i=0;i<n-1;i++) { out.print(col[i]+1); if(i<n-2) out.print(" "); } out.println(""); out.close(); } static void dfs(int v, int p, int c) { int color=0; for(pair i:adj[v]) { if(i.a!=p) { if(c==color) { color++; color%=min; } col[i.b]=color; dfs(i.a,v,color); color++; color%=min; } } } static class pair implements Comparable<pair>{ int a,b; public pair(int x,int y) { a=x;b=y; } public int compareTo(pair p) { return a-p.a; } } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
f272ea42992ee8368cee541ab9d55d0b
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.BufferedOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class Task { public static void solve() throws Exception { int n = nextInt(); int k = nextInt(); int[] tab = new int[n+1]; Map<Integer, List<Integer>> map = new HashMap<>(); Map<Integer, List<Integer>> mapInd = new HashMap<>(); for(int i=1;i<=n;i++) { map.put(i, new ArrayList<>()); mapInd.put(i, new ArrayList<>()); } for(int i=0;i<n-1;i++) { int a = nextInt(); int b = nextInt(); tab[a]++; tab[b]++; map.get(a).add(b); mapInd.get(a).add(i+1); map.get(b).add(a); mapInd.get(b).add(i+1); } sort(tab); int count = 0; int r = 1; for(int i=tab.length-1;i>=0;i--) { if(count == k) { r = tab[i]; break; } count++; } int[] company = new int[n+2]; List<Integer> stack = new ArrayList<>(); stack.add(1); Set<Integer> visited = new HashSet<Integer>(); while(!stack.isEmpty()) { Integer node = stack.remove(stack.size()-1); visited.add(node); List<Integer> edges = map.get(node); List<Integer> indicies = mapInd.get(node); int prevCompany = 0; for(int i=0;i<edges.size();i++) { Integer child = edges.get(i); if(visited.contains(child)) { int index = indicies.get(i); prevCompany = company[index]; break; } } for(int i=0;i<edges.size();i++) { Integer child = edges.get(i); if(!visited.contains(child)) { prevCompany++; if(prevCompany > r) { prevCompany = 1; } stack.add(child); int index = indicies.get(i); company[index] = prevCompany; } } } println(r); for(int i=1;i<=n-1;i++) { if(i > 1) print(" "); print(company[i]); } println(""); } public static void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int[n1]; int R[] = new int[n2]; for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void sort(int arr[]) { sort(arr, 0, arr.length - 1); } public static void sort(int arr[], int l, int r) { if (l < r) { int m = (l + r) / 2; sort(arr, l, m); sort(arr, m + 1, r); merge(arr, l, m, r); } } public static void main(String[] args) throws Exception { try { fastReader = new FastReader(System.in); systemOut = new BufferedOutputStream(System.out); solve(); } finally { systemOut.close(); } } private static FastReader fastReader = null; private static BufferedOutputStream systemOut = null; public static void print(Object obj) { print(obj.toString()); } public static void print(String str) { try { systemOut.write(str.getBytes("utf-8")); } catch (Exception ex) { throw new RuntimeException(ex); } } public static void println(Object obj) { println(obj.toString()); } public static void println(String str) { try { print(str); systemOut.write('\n'); } catch (Exception ex) { throw new RuntimeException(ex); } } public static String next() { return fastReader.readNextToken(false); } public static String nextLine() { return fastReader.readNextToken(true); } public static int nextInt() { return Integer.parseInt(fastReader.readNextToken(false)); } public static long nextLong() { return Long.parseLong(fastReader.readNextToken(false)); } public static double nextDouble() { return Double.parseDouble(fastReader.readNextToken(false)); } static class FastReader { private byte[] buf = new byte[65536]; private int ind = 0; private int maxInd = -1; private InputStream is = null; private boolean eof = false; private boolean lastCharRead = false; public FastReader(InputStream is) { this.is = is; } public String readNextToken(boolean endOfLine) { try { StringBuilder sb = new StringBuilder(); boolean found = false; while (true) { if (lastCharRead) { return null; } else if (ind > maxInd) { if (eof) { lastCharRead = true; } else { fillBuffer(); } } byte b = '\n'; if (!lastCharRead) { b = buf[ind++]; } if (b == '\r') { // ignore } else if ((b == '\n' && endOfLine) || (Character.isWhitespace(b) && !endOfLine)) { if (found) { break; } } else { sb.append((char) b); found = true; } } return sb.toString(); } catch (Exception ex) { throw new RuntimeException(ex); } } private void fillBuffer() { try { int read = is.read(buf, 0, buf.length); if (read < buf.length) { eof = true; } ind = 0; maxInd = read - 1; } catch (Exception ex) { throw new RuntimeException(ex); } } } public static class LST { public long[][] set; public int n; public LST(int n) { this.n = n; int d = 1; for (int m = n; m > 1; m >>>= 6, d++) ; set = new long[d][]; for (int i = 0, m = n >>> 6; i < d; i++, m >>>= 6) { set[i] = new long[m + 1]; } } // [0,r) public LST setRange(int r) { for (int i = 0; i < set.length; i++, r = r + 63 >>> 6) { for (int j = 0; j < r >>> 6; j++) { set[i][j] = -1L; } if ((r & 63) != 0) set[i][r >>> 6] |= (1L << r) - 1; } return this; } // [0,r) public LST unsetRange(int r) { if (r >= 0) { for (int i = 0; i < set.length; i++, r = r + 63 >>> 6) { for (int j = 0; j < r + 63 >>> 6; j++) { set[i][j] = 0; } if ((r & 63) != 0) set[i][r >>> 6] &= ~((1L << r) - 1); } } return this; } public LST set(int pos) { if (pos >= 0 && pos < n) { for (int i = 0; i < set.length; i++, pos >>>= 6) { set[i][pos >>> 6] |= 1L << pos; } } return this; } public LST unset(int pos) { if (pos >= 0 && pos < n) { for (int i = 0; i < set.length && (i == 0 || set[i - 1][pos] == 0L); i++, pos >>>= 6) { set[i][pos >>> 6] &= ~(1L << pos); } } return this; } public boolean get(int pos) { return pos >= 0 && pos < n && set[0][pos >>> 6] << ~pos < 0; } public LST toggle(int pos) { return get(pos) ? unset(pos) : set(pos); } public int prev(int pos) { for (int i = 0; i < set.length && pos >= 0; i++, pos >>>= 6, pos--) { int pre = prev(set[i][pos >>> 6], pos & 63); if (pre != -1) { pos = pos >>> 6 << 6 | pre; while (i > 0) pos = pos << 6 | 63 - Long.numberOfLeadingZeros(set[--i][pos]); return pos; } } return -1; } public int next(int pos) { for (int i = 0; i < set.length && pos >>> 6 < set[i].length; i++, pos >>>= 6, pos++) { int nex = next(set[i][pos >>> 6], pos & 63); if (nex != -1) { pos = pos >>> 6 << 6 | nex; while (i > 0) pos = pos << 6 | Long.numberOfTrailingZeros(set[--i][pos]); return pos; } } return -1; } private static int prev(long set, int n) { long h = set << ~n; if (h == 0L) return -1; return -Long.numberOfLeadingZeros(h) + n; } private static int next(long set, int n) { long h = set >>> n; if (h == 0L) return -1; return Long.numberOfTrailingZeros(h) + n; } @Override public String toString() { List<Integer> list = new ArrayList<Integer>(); for (int pos = next(0); pos != -1; pos = next(pos + 1)) { list.add(pos); } return list.toString(); } } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
f74931043f2c0d136ec50bb8da485ec4
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
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.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Washoum */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; inputClass in = new inputClass(inputStream); PrintWriter out = new PrintWriter(outputStream); GPrivatizationOfRoadsInTreeland solver = new GPrivatizationOfRoadsInTreeland(); solver.solve(1, in, out); out.close(); } static class GPrivatizationOfRoadsInTreeland { static GPrivatizationOfRoadsInTreeland.Node[] graph; static boolean[] visited; static int n; static int k; static int ans; static int[] rep; static void dfs(int a, int sauf, int par) { visited[a] = true; int which = 1; GPrivatizationOfRoadsInTreeland.Pair p; int i; for (i = 0; i < graph[a].edges.size() && which <= ans; i++) { p = graph[a].edges.get(i); if (p.x != par) { if (which == sauf) { which++; if (which > ans) { break; } } rep[p.pos] = which; which++; } } which = 1; if (graph[a].edges.size() > ans) { for (int j = i; j < graph[a].edges.size(); j++) { if (graph[a].edges.get(j).x != par) { rep[graph[a].edges.get(j).pos] = which; which++; if (which == ans + 1) { which = 1; } } } } for (GPrivatizationOfRoadsInTreeland.Pair o : graph[a].edges) { if (!visited[o.x]) { dfs(o.x, rep[o.pos], a); } } } public void solve(int testNumber, inputClass sc, PrintWriter out) { n = sc.nextInt(); k = sc.nextInt(); graph = new GPrivatizationOfRoadsInTreeland.Node[n]; visited = new boolean[n]; for (int i = 0; i < n; i++) { graph[i] = new GPrivatizationOfRoadsInTreeland.Node(); graph[i].edges = new ArrayList<>(); } int x, y; GPrivatizationOfRoadsInTreeland.Pair p; for (int i = 0; i < n - 1; i++) { x = sc.nextInt() - 1; y = sc.nextInt() - 1; p = new GPrivatizationOfRoadsInTreeland.Pair(); p.x = y; p.pos = i; graph[x].edges.add(p); p = new GPrivatizationOfRoadsInTreeland.Pair(); p.x = x; p.pos = i; graph[y].edges.add(p); } int l = 1; int r = n - 1; ans = n - 1; while (r - l >= 0) { int mid = (l + r) / 2; if (check(mid)) { ans = mid; r = mid - 1; } else { l = mid + 1; } } rep = new int[n - 1]; dfs(0, -1, -1); out.println(ans); for (int i = 0; i < n - 1; i++) { out.print(rep[i] + " "); } out.println(); } private boolean check(int mid) { int cmb = 0; for (int i = 0; i < n; i++) { if (graph[i].edges.size() > mid) { cmb++; } } if (cmb > k) { return false; } else { return true; } } static class Pair { int x; int pos; } static class Node { ArrayList<GPrivatizationOfRoadsInTreeland.Pair> edges; } } static class inputClass { BufferedReader br; StringTokenizer st; public inputClass(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
cb7f39bec44de6c34aa7f0a0173f87bd
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedInputStream; import java.util.HashMap; import java.util.HashSet; import java.io.FilterInputStream; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jenish */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); GPrivatizationOfRoadsInTreeland solver = new GPrivatizationOfRoadsInTreeland(); solver.solve(1, in, out); out.close(); } static class GPrivatizationOfRoadsInTreeland { int[] colo; int[][] g; int ans; HashMap<Long, Integer> gm; public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int k = in.scanInt(); int from[] = new int[n - 1]; int to[] = new int[n - 1]; gm = new HashMap<>(); for (int i = 0; i < n - 1; i++) { from[i] = in.scanInt(); to[i] = in.scanInt(); gm.put(CodeX.compute_hash(from[i], to[i]), i); gm.put(CodeX.compute_hash(to[i], from[i]), i); } g = CodeX.packGraph(from, to, n + 1); pair degree[] = new pair[n]; for (int i = 0; i < n; i++) degree[i] = new pair(i + 1, g[i + 1].length); Arrays.sort(degree, new Comparator<pair>() { public int compare(pair o1, pair o2) { return o2.de - o1.de; } }); if (n <= k) { out.println(1); for (int i = 0; i < n - 1; i++) { out.print(1 + " "); } } else { ans = degree[k].de; out.println(ans); colo = new int[n - 1]; Arrays.fill(colo, -1); dfs(1, -1, -1); for (int col : colo) { out.print((col + 1) + " "); } HashSet<Integer> node = new HashSet<>(); for (int i = 1; i <= n; i++) { HashSet<Integer> temp = new HashSet<>(); for (int tt : g[i]) { long hash = CodeX.compute_hash(i, tt); if (temp.contains(colo[gm.get(hash)])) { node.add(i); } else { temp.add(colo[gm.get(hash)]); } } } if (node.size() > k) throw new RuntimeException("WRONG ANS"); } } void dfs(int u, int p, int f) { int color = 0; for (int e : g[u]) if (p != e) { if (color == f) { color = (color + 1) % ans; // f = -1; } long hash = CodeX.compute_hash(u, e); colo[gm.get(hash)] = color; dfs(e, u, color); color = (color + 1) % ans; } } } static class pair { int id; int de; public pair(int id, int de) { this.id = id; this.de = de; } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int INDEX; private BufferedInputStream in; private int TOTAL; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (INDEX >= TOTAL) { INDEX = 0; try { TOTAL = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (TOTAL <= 0) return -1; } return buf[INDEX++]; } public int scanInt() { int I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } static class CodeX { public static long compute_hash(long a, long b) { return (((a * 1456973978l) % 8008808808808813l) + ((b * 234792734l) % 8008808808808813l)) % 8008808808808813l; } public static int[][] packGraph(int[] from, int[] to, int n) { int[][] g = new int[n + 1][]; int p[] = new int[n + 1]; for (int i : from) p[i]++; for (int i : to) p[i]++; for (int i = 0; i <= n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
389e8f1d2567acafb1ab87bad3cee04d
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.*; import java.util.*; public class MainClass { static int n = 0; static int k = 0; static ArrayList<Integer>[] adj; static ArrayList<Integer>[] indices; static boolean[] visited; static int ans = -1; static int[] mark; static StringBuilder stringBuilder = new StringBuilder(); public static void main(String[] args)throws IOException { Reader in = new Reader(); n = in.nextInt(); k = in.nextInt(); adj = new ArrayList[n]; indices = new ArrayList[n]; visited = new boolean[n]; mark = new int[n - 1]; for (int i=0;i<n;i++) { adj[i] = new ArrayList<>(); indices[i] = new ArrayList<>(); } for (int i=0;i<n - 1;i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; adj[x].add(y); adj[y].add(x); indices[x].add(i); indices[y].add(i); } int[] degrees = new int[n]; for (int i=0;i<n;i++) degrees[i] = adj[i].size(); new MergeSortInt().sort(degrees, 0, degrees.length - 1); int bigger = 0; ans = -1; int cc = 0; for (int i=n - 1;i>=0;i--) { if (i < n - 1 && degrees[i] != degrees[i + 1]) { bigger += cc; cc = 0; } if (bigger <= k) ans = degrees[i]; else break; cc++; } explore(0, 0); stringBuilder.append(ans).append("\n"); for (int i=0;i<n - 1;i++) stringBuilder.append(mark[i] + 1).append(" "); System.out.println(stringBuilder); } public static void explore(int v, int count) { visited[v] = true; int jj = 1; for (int i=0;i<adj[v].size();i++) { int to = adj[v].get(i); int index = indices[v].get(i); if (!visited[to]) { mark[index] = (count + jj) % ans; explore(to, (count + jj++) % ans); } } } } class Reader { final private int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public 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(); } }class MergeSortInt { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
5b38f4c03baab3cfaa8cb01ba6ab0008
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.regex.*; import java.util.stream.LongStream; public class Main{ static ArrayList a[]=new ArrayList[5000001]; static TreeSet<Integer>tr=new TreeSet<>(); static boolean visited[]=new boolean [300001]; static int ans[]=new int[300001]; static int upto[]=new int[300001]; static void dfs(int n,int c) { visited[n]=true; for(int i=0;i<a[n].size();i++) { pair id=(pair) a[n].get(i); if(!visited[id.x]) { if(tr.contains(n)) { ans[id.y]=1; } else { if((upto[n]+1)==c) { upto[n]++; } ans[id.y]=(++upto[n]); } dfs(id.x,ans[id.y]); } } } 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(); for(int i=0;i<=n;i++) { a[i]=new ArrayList<pair>(); } for(int i=0;i<n-1;i++) { int x=in.nextInt(); int y=in.nextInt(); a[x].add(new pair(y,i)); a[y].add(new pair(x,i)); } pair p[]=new pair[n]; for(int i=1;i<=n;i++) { p[i-1]=new pair(a[i].size(),i); } Arrays.sort(p,new Comparator<pair>() { public int compare(pair p1,pair p2) { if(p1.x>p2.x) return -1; if(p1.x<p2.x) return 1; return 0; } }); long c=0; for(int i=0;i<k;i++) { tr.add(p[i].y); } for(int i=k;i<n;i++) { c=Math.max(c, p[i].x); } dfs(1,-1); pw.println(c); for(int i=0;i<n-1;i++) pw.print(ans[i]+" "); pw.flush(); pw.close(); } private static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } 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; } static class tri implements Comparable<tri> { int p, c, l; tri(int p, int c, int l) { this.p = p; this.c = c; this.l = l; } public int compareTo(tri o) { return Integer.compare(l, o.l); } } 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 long mod = 1000000007; public static int d; public static int p; public static int q; 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 long primeFactorization(long n) { HashSet<Integer> a =new HashSet<Integer>(); long cnt=0; for(int i=2;i*i<=n;i++) { while(a%i==0) { a.add(i); a/=i; } } if(a!=1) cnt++; //a.add(n); return cnt; }*/ 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 void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } 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%M*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%M * x%M)%M; x=(x%M * x%M)%M; n=n/2; } return result; } public static long 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; } public static long[] shuffle(long[] a, Random gen){ for(int i = 0, n = a.length;i < n;i++){ int ind = gen.nextInt(n-i)+i; long d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } static class pair implements Comparable<pair>{ Integer x; Integer y; pair(int l,int id){ this.x=l; this.y=id; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString(){ return (x+" "+y); } } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
15f3831d376d45d51171fd9c43f109e4
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
/*Author: Satyajeet Singh, Delhi Technological University*/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; public class Main { /*********************************************Constants******************************************/ static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static long mod=(long)1e9+7; static long mod1=998244353; static boolean sieve[]; static ArrayList<Integer> primes; static ArrayList<Long> factorial; //static HashSet<Integer> graph[]; /****************************************Solutions Begins*****************************************/ static int n,k; static int col[]; static int D=0; static ArrayList<Integer> graph[],colo[]; static void dfs(int start,int par,int c){ int color=c; int idx=0; for(int u:graph[start]){ if(u!=par){ int id=colo[start].get(idx); // debug(start,u,c,id); color=(color+1)%D; col[id]=color; dfs(u,start,color); } idx++; } } public static void main (String[] args) throws Exception { String st[]=br.readLine().split(" "); n=Integer.parseInt(st[0]); k=Integer.parseInt(st[1]); Makegraph(n+1); for(int i=0;i<n-1;i++){ st=br.readLine().split(" "); int a=Integer.parseInt(st[0]); int b=Integer.parseInt(st[1]); addEdge(a,b,i); } TreeMap<Integer,Integer> map=new TreeMap<>(Collections.reverseOrder()); for(int i=1;i<=n;i++){ map.put(graph[i].size(),map.getOrDefault(graph[i].size(),0)+1); } int kk=0; int r=0; for(int u:map.keySet()){ if(kk<=k){ r=u; kk+=map.get(u); } else{ break; } } out.println(r); D=r; col=new int[n+1]; dfs(1,-1,0); // debug(graph); //debug(colo); for(int i=0;i<n-1;i++){ out.print(++col[i]+" "); } /****************************************Solutions Ends**************************************************/ out.flush(); out.close(); } /****************************************Template Begins************************************************/ /***************************************Precision Printing**********************************************/ static void printPrecision(double d){ DecimalFormat ft = new DecimalFormat("0.00000000000000000"); out.println(ft.format(d)); } /******************************************Graph*********************************************************/ static void Makegraph(int n){ graph=new ArrayList[n]; colo=new ArrayList[n]; for(int i=0;i<n;i++){ graph[i]=new ArrayList<>(); colo[i]=new ArrayList<>(); } } static void addEdge(int a,int b,int i){ graph[a].add(b); colo[a].add(i); graph[b].add(a); colo[b].add(i); } /*********************************************PAIR********************************************************/ static class PairComp implements Comparator<Pair>{ public int compare(Pair p1,Pair p2){ if(p1.u>p2.u){ return 1; } else if(p1.u<p2.u){ return -1; } else{ return p1.v-p2.v; } } } static class Pair implements Comparable<Pair> { int u; int v; int index=-1; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } static class PairCompL implements Comparator<Pairl>{ public int compare(Pairl p1,Pairl p2){ if(p1.v>p2.v){ return -1; } else if(p1.v<p2.v){ return 1; } else{ return 0; } } } static class Pairl implements Comparable<Pair> { long u; long v; int index=-1; public Pairl(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /*****************************************DEBUG***********************************************************/ public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } /************************************MODULAR EXPONENTIATION***********************************************/ static long modulo(long a,long b,long c) { long x=1; long y=a; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } /********************************************GCD**********************************************************/ static long gcd(long x, long y) { if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0) { r = a % b; a = b; b = r; } return r; } /******************************************SIEVE**********************************************************/ static void sieveMake(int n){ sieve=new boolean[n]; Arrays.fill(sieve,true); sieve[0]=false; sieve[1]=false; for(int i=2;i*i<n;i++){ if(sieve[i]){ for(int j=i*i;j<n;j+=i){ sieve[j]=false; } } } primes=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(sieve[i]){ primes.add(i); } } } /********************************************End***********************************************************/ }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
2b01270bf80210377d27f779c4dee5cc
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; //Solution Credits: Taranpreet Singh public class Main{ //SOLUTION BEGIN //Code not meant for understanding, proceed with caution void pre() throws Exception{} void solve(int TC) throws Exception{ int n = ni(), k = ni(); int[][] e = new int[n-1][]; int[] deg = new int[n]; for(int i = 0; i< n-1; i++){ e[i] = new int[]{ni()-1, ni()-1, i}; deg[e[i][0]]++; deg[e[i][1]]++; } int[][][] g = makeU(n,e); int[] cnt = new int[n]; for(int i = 0; i< n; i++)cnt[deg[i]]++; int ans = -1; int sum = 0; for(int i = n-1; i>= 0; i--){ sum+= cnt[i]; if(sum>k && ans==-1){ ans = i; } } pn(ans); int[] col = new int[n-1]; dfs(g,col,ans,0,-1,0); for(int i = 0; i< n-1; i++)p(col[i]+" ");pn(""); } void dfs(int[][][] g, int[] col, int ans, int u, int p,int a){ int cur = 1; for(int[] v:g[u]){ if(v[0]==p)continue; if(cur==a)cur++; while(cur>ans)cur-=ans; col[v[1]] = cur++; dfs(g, col, ans, v[0],u,col[v[1]]); } } int[][][] makeU(int n, int[][] edge){ int[][][] g = new int[n][][];int[] cnt = new int[n]; for(int i = 0; i< edge.length; i++){cnt[edge[i][0]]++;cnt[edge[i][1]]++;} for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][]; for(int i = 0; i< edge.length; i++){ g[edge[i][0]][--cnt[edge[i][0]]] = new int[]{edge[i][1], edge[i][2]}; g[edge[i][1]][--cnt[edge[i][1]]] = new int[]{edge[i][0], edge[i][2]}; } return g; } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} long mod = (long)1e9+7, IINF = (long)1e18; final int INF = (int)1e9, MX = (int)2e3+1; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.1415926535897932384626433832792884197169399375105820974944, eps = 1e-8; static boolean multipleTC = false, memory = false; FastReader in;PrintWriter out; void run() throws Exception{ in = new FastReader(); out = new PrintWriter(System.out); int T = (multipleTC)?ni():1; //Solution Credits: Taranpreet Singh pre();for(int t = 1; t<= T; t++)solve(t); out.flush(); out.close(); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str = ""; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
9a37ea24191fd7fb856bf24e9f8c78e6
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; /* spar5h */ public class cf2 implements Runnable { static class Edge { int u, v; Edge(int u, int v) { this.u = u; this.v = v; } int other(int x) { if(x == u) return v; return u; } } static class Pair { int i, w; Pair(int i, int w) { this.i = i; this.w = w; } } static class Comp implements Comparator<Pair> { public int compare(Pair x, Pair y) { if(x.w > y.w) return -1; if(x.w < y.w) return 1; return 0; } } public void run() { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = s.nextInt(), k = s.nextInt(); Edge[] edge = new Edge[n - 1]; int[] edgeCol = new int[n - 1]; ArrayList<Integer>[] adj = new ArrayList[n]; for(int i = 0; i < n; i++) adj[i] = new ArrayList<Integer>(); for(int i = 0; i < n - 1; i++) { Edge e = new Edge(s.nextInt() - 1, s.nextInt() - 1); edge[i] = e; adj[e.u].add(i); adj[e.v].add(i); } int[] dead = new int[n]; ArrayList<Pair> a = new ArrayList<Pair>(); for(int i = 0; i < n; i++) a.add(new Pair(i, adj[i].size())); Collections.sort(a, new Comp()); for(int i = 0; i < k; i++) dead[a.get(i).i] = 1; Queue<Integer> q = new LinkedList<Integer>(); int[] parentEdge = new int[n]; Arrays.fill(parentEdge, -1); int col = 0; for(int i : adj[0]) { if(dead[0] == 0) edgeCol[i] = ++col; else edgeCol[i] = 1; parentEdge[edge[i].other(0)] = i; q.add(edge[i].other(0)); } while(!q.isEmpty()) { int x = q.poll(); col = 0; for(int i : adj[x]) { if(i == parentEdge[x]) continue; if(dead[x] == 0) { if(col + 1 == edgeCol[parentEdge[x]]) col++; edgeCol[i] = ++col; } else edgeCol[i] = edgeCol[parentEdge[x]]; parentEdge[edge[i].other(x)] = i; q.add(edge[i].other(x)); } } col = 0; for(int i = 0; i < n - 1; i++) col = max(edgeCol[i], col); w.println(col); for(int i = 0; i < n - 1; i++) w.print(edgeCol[i] + " "); w.println(); w.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public 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); } } public static void main(String args[]) throws Exception { new Thread(null, new cf2(),"cf2",1<<26).start(); } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
a9882d62de69e903f83c9a3a2e02713b
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; 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.Queue; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class q5 { public static void main(String[] args) throws IOException { Reader.init(System.in); StringBuffer output=new StringBuffer(""); PrintWriter out=new PrintWriter(System.out); int n=Reader.nextInt(); int k=Reader.nextInt(); int[] deg=new int[n+1]; ArrayList<NoD>[] graph=new ArrayList[n+1]; for(int i=0;i<=n;i++) graph[i]=new ArrayList<NoD>(); for(int i=1;i<n;i++) { int a=Reader.nextInt(); int b=Reader.nextInt(); deg[a]++;deg[b]++; graph[a].add(new NoD(b,i)); graph[b].add(new NoD(a,i)); } int low=1; int high=n; int val=n; while(low<=high) { int mid=(low+high)/2; int count=0; for(int i=1;i<=n;i++) { if(deg[i]>mid) count++; } if(count<=k) { val=mid; high=mid-1; } else { low=mid+1; } } output.append(val);output.append("\n"); int nottoassign=-1; int[] colour=new int[n]; Queue<NoD> q=new LinkedList<NoD>(); int[] visited=new int[n+1]; visited[1]=1; q.add(new NoD(1,-1)); while(q.size()!=0) { NoD a=q.poll(); int v=a.val; nottoassign=a.index; int start=0; for(NoD b:graph[v]) { if(visited[b.val]==0) { if(start==nottoassign) {start++; start%=val;} colour[b.index]=start; visited[b.val]=1; q.add(new NoD(b.val,start)); start++; start%=val; } } } for(int i=1;i<n;i++) { output.append((colour[i]+1)+" "); } out.write(output.toString()); out.flush(); } } class NoD{ int val; int index; NoD(int v,int i){ val=v;index=i; } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String nextLine() throws IOException{ return reader.readLine(); } static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
a63b09bb4e42d6446fcc1ad7b85a13c1
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { new Main().go(); } PrintWriter out; Reader in; BufferedReader br; Main() throws IOException { try { //br = new BufferedReader( new FileReader("input.txt") ); //in = new Reader("input.txt"); in = new Reader("input.txt"); out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); } catch (Exception e) { //br = new BufferedReader( new InputStreamReader( System.in ) ); in = new Reader(); out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); } } void go() throws Exception { //int t = in.nextInt(); int t = 1; while (t > 0) { solve(); t--; } out.flush(); out.close(); } int inf = 2000000000; int mod = 1000000007; double eps = 0.000000001; int n; int m; ArrayList<Pair>[] g; int[] a; void solve() throws IOException { int n = in.nextInt(); int k = in.nextInt(); int[] deg = new int[n]; g = new ArrayList[n]; for (int i = 0; i < n; i++) g[i] = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; g[x].add(new Pair(y, i)); g[y].add(new Pair(x, i)); deg[x]++; deg[y]++; } int l = 1; int r = n; while (l < r) { int m = (l + r) >> 1; int cnt = 0; for (int i = 0; i < n; i++) if (deg[i] > m) cnt++; if (cnt > k) l = m + 1; else r = m; } dfs(0, -1, -1, r); out.println(r); for (int i = 0; i < n - 1; i++) out.print(ans[i] + " "); } int[] ans = new int[200000]; void dfs(int v, int p, int c, int r) { int cur = 0; boolean good = g[v].size() <= r; for (Pair u : g[v]) { if (u.a == p) continue; if (good) { cur++; if (cur == c) cur++; } else { cur = c; if (cur == -1) cur = 1; } ans[u.b] = cur; dfs(u.a, v, cur, r); } } class Pair implements Comparable<Pair>{ int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (a != p.a) return Integer.compare(a, p.a); else return Integer.compare(b, p.b); } } class Item { int a; int b; int c; Item(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } } static class InputReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public InputReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public InputReader(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 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
a80d3038f4aa269b68db6f58ecf7c03f
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static class node implements Comparable<node> { int u,id; node(){} node(int u,int id) { this.u=u; this.id=id; } @Override public int compareTo(node rhs) { return rhs.u-u; } } static ArrayList<node>[] G=new ArrayList[212345]; static int[] res=new int[212345]; static boolean[] vis=new boolean[212345]; static void dfs(int u,int fa,int col) { boolean[] used=new boolean[G[u].size()+1]; if (col<=G[u].size()) used[col]=true; int now=1; for (int i=0;i<G[u].size();++i) { int v=G[u].get(i).u; if (v==fa) continue; if (vis[u]) { res[G[u].get(i).id]=1; dfs(v,u,1); } else { while (used[now]) ++now; used[now]=true; res[G[u].get(i).id]=now; dfs(v,u,now); } } } public static void main(String[] args) throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); StringTokenizer sa=new StringTokenizer(in.readLine()); int n=Integer.parseInt(sa.nextToken()); int k=Integer.parseInt(sa.nextToken()); for (int i=1;i<=n;++i) G[i]=new ArrayList<node>(); for (int i=0;i<n-1;++i) { sa=new StringTokenizer(in.readLine()); int x=Integer.parseInt(sa.nextToken()); int y=Integer.parseInt(sa.nextToken()); G[x].add(new node(y,i)); G[y].add(new node(x,i)); } PriorityQueue<node> que=new PriorityQueue<node>(); for (int i=1;i<=n;++i) que.add(new node(G[i].size(),i)); for (int i=0;i<k;++i) { vis[que.peek().id]=true; que.poll(); } out.println(que.peek().u); dfs(1,0,0); for (int i=0;i<n-1;++i) out.printf("%d%c",res[i],i+2==n?'\n':' '); out.close(); } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
26cc9021e7717d6cf6f6b5ab27013d79
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Scanner; public class G { private static int n, k; private static Tree tree; private static int r; private static int[] c; public static void main(String[] args) throws IOException { in(); solution(); out(); } private static void in() { Scanner in = new Scanner(System.in); n = in.nextInt(); k = in.nextInt(); tree = new Tree(n); c = new int[n]; for (int i = 1; i < n; i++) { tree.addEdge(in.nextInt(), in.nextInt()); } } private static void solution() { long[] sum = new long[n + 1]; for (int i = 1; i <= n; i++) { sum[ tree.getAmountOfAdjacentVertices(i) ]++; } for (int i = n - 2; i > 0; i--) { sum[i] += sum[i + 1]; } r = n - 1; while (sum[r] <= k) { r--; } tree.paint(r); for (int i = 0; i < n - 1; i++) { c[i] = tree.getColorOfEdge(i); } } private static void out() throws IOException { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); bw.write(r + "\n"); for (int i = 0; i < n - 1; i++) { bw.write(c[i] + (i == n - 1 ? "\n" : " ")); } bw.close(); } } class Tree { private ArrayList<ArrayList<Pair<Integer, Integer>>> edges; private int amountOfEdges; private int[] edgesColors; Tree(int n) { edges = new ArrayList<>(); edgesColors = new int[n - 1]; amountOfEdges = 0; for (int i = 0; i < n; i++) { edges.add(new ArrayList<>()); } } void addEdge(int a, int b) { edges.get(a - 1).add( new Pair<>(b - 1, amountOfEdges) ); edges.get(b - 1).add( new Pair<>(a - 1, amountOfEdges) ); amountOfEdges++; } int getAmountOfAdjacentVertices(int a) { return edges.get(a - 1).size(); } void paint(int colors) { dfsPaintingEdges(0, colors,-1, -1); } private void dfsPaintingEdges(int vertex, int colors, int previousVertex, int lastColor) { int color = 0; for (int i = 0; i < edges.get(vertex).size(); i++) { if (previousVertex == edges.get(vertex).get(i).vertex) { continue; } if (color == lastColor) { lastColor = -1; color = (color + 1) % colors; } edgesColors[ edges.get(vertex).get(i).numberOfEdge ] = color + 1; dfsPaintingEdges( edges.get(vertex).get(i).vertex, colors, vertex, color); color = (color + 1) % colors; } } int getColorOfEdge(int i) { return edgesColors[i]; } } class Pair<T1, T2> { T1 vertex; T2 numberOfEdge; Pair(T1 vertex, T2 numberOfEdge) { this.vertex = vertex; this.numberOfEdge = numberOfEdge; } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
cbf2b0290fdef943654337d19f16045a
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.LinkedList; import java.util.Scanner; public class G { private static int n, k; private static Tree tree; private static int r; private static int[] c; public static void main(String[] args) throws IOException { in(); solution(); out(); } private static void in() { Scanner in = new Scanner(System.in); n = in.nextInt(); k = in.nextInt(); tree = new Tree(n); c = new int[n]; for (int i = 1; i < n; i++) { tree.addEdge(in.nextInt(), in.nextInt()); } } private static void solution() { long[] sum = new long[n + 1]; for (int i = 1; i <= n; i++) { sum[ tree.getAmountOfAdjacentVertices(i) ]++; } for (int i = n - 2; i > 0; i--) { sum[i] += sum[i + 1]; //System.out.println(i + ". " + sum[i]); } r = n - 1; while (sum[r] <= k && r >= 0) { //System.out.println("r=" + r + " " + "sum=" + sum[r]); r--; } tree.paint(r); for (int i = 0; i < n - 1; i++) { c[i] = tree.getColorOfEdge(i); } } private static void out() throws IOException { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); bw.write(r + "\n"); for (int i = 0; i < n - 1; i++) { bw.write(c[i] + (i == n - 1 ? "\n" : " ")); } bw.close(); } } class Tree { private ArrayList<ArrayList<Pair<Integer, Integer>>> edges; private int amountOfEdges; private int[] edgesColors; Tree(int n) { edges = new ArrayList<>(); edgesColors = new int[n - 1]; amountOfEdges = 0; for (int i = 0; i < n; i++) { edges.add(new ArrayList<>()); } } void addEdge(int a, int b) { edges.get(a - 1).add( new Pair<>(b - 1, amountOfEdges) ); edges.get(b - 1).add( new Pair<>(a - 1, amountOfEdges) ); amountOfEdges++; } int getAmountOfAdjacentVertices(int a) { return edges.get(a - 1).size(); } void paint(int colors) { dfsPaintingEdges(0, colors,-1, -1); } private void dfsPaintingEdges(int vertex, int colors, int previousVertex, int lastColor) { /* System.out.println("vertex: " + vertex); System.out.println("previousVertex: " + previousVertex); System.out.println("lastColor: " + lastColor); */ int color = 0; for (int i = 0; i < edges.get(vertex).size(); i++) { /* System.out.println(" for: " + vertex); System.out.println(" next: " + edges.get(vertex).get(i).vertex); System.out.println(" color: " + color); */ if (previousVertex == edges.get(vertex).get(i).vertex) { //System.out.println(" skip edge"); continue; } if (color == lastColor) { lastColor = -1; color = (color + 1) % colors; //System.out.printf(" skip color to %d\n", color); } edgesColors[ edges.get(vertex).get(i).numberOfEdge ] = color + 1; //System.out.printf(" %d was set to %d\n", edges.get(vertex).get(i).numberOfEdge, color); dfsPaintingEdges( edges.get(vertex).get(i).vertex, colors, vertex, color); color = (color + 1) % colors; } } int getColorOfEdge(int i) { return edgesColors[i]; } } class Pair<T1, T2> { T1 vertex; T2 numberOfEdge; Pair(T1 vertex, T2 numberOfEdge) { this.vertex = vertex; this.numberOfEdge = numberOfEdge; } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
cf3c993fc03fe4c85bec2421f3955562
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { PrintWriter out = new PrintWriter(System.out); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(""); String next() throws IOException { if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } long nl() throws IOException { return Long.parseLong(next()); } ArrayList<Integer>[]A; ArrayList<Integer>[]B; int[]D; int m; void solve() throws IOException { int n=ni(); int k=ni(); A=new ArrayList[n+1]; B=new ArrayList[n+1]; for (int x=1;x<=n;x++) { A[x]=new ArrayList(); B[x]=new ArrayList(); } for (int x=1;x<n;x++) { int u=ni(),v=ni(); A[u].add(v); A[v].add(u); B[u].add(x); B[v].add(x); } int[]C=new int[n+1]; for (int x=1;x<=n;x++) { C[x]=A[x].size(); } Arrays.sort(C); m=C[n-k]; D=new int[n]; dfs(1,0,0); out.println(m); for (int x=1;x<n;x++) out.print(D[x]+" "); out.println(); out.flush(); } void dfs(int v, int p, int c) { if (A[v].size()>m) { for (int x=0;x<A[v].size();x++) { int u=A[v].get(x); if (u==p) continue; D[B[v].get(x)]=1; dfs(u,v,1); } } else { int d=1; if (c==1) d++; for (int x=0;x<A[v].size();x++) { int u=A[v].get(x); if (u==p) continue; D[B[v].get(x)]=d; dfs(u,v,d); d++; if (d==c) d++; } } } public static void main(String[] args) throws IOException { new Main().solve(); } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
e45288e1ab300e9b8c4e402842bf77fa
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static final long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "Yes"; private static final String no = "No"; int n; int k; class Edge { int other; int idx; public Edge(int other, int idx) { this.other = other; this.idx = idx; } @Override public String toString() { return other + " " + idx; } } List<List<Edge>> graph = new ArrayList<>(); boolean[] isGood; int[] res; int r; void solve() throws IOException { n = nextInt(); k = nextInt(); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } for (int i = 0; i < n - 1; i++) { int x = nextInt() - 1; int y = nextInt() - 1; graph.get(x).add(new Edge(y, i)); graph.get(y).add(new Edge(x, i)); } int l = 0; int h = (int) MOD; while (l < h) { int mid = (l + h) / 2; if (check(mid)) { h = mid; } else { l = mid + 1; } } isGood = new boolean[n]; r = l; for (int i = 0; i < n; i++) { List<Edge> ls = graph.get(i); if (ls.size() <= r) { isGood[i] = true; } } res = new int[n - 1]; dfs(-1, 0, -1); outln(r); for (int i = 0; i < n - 1; i++) { out((1 + res[i]) + " "); } } void dfs(int parent, int cur, int label) { List<Edge> ls = graph.get(cur); int j = 0; for (Edge e : ls) { if (e.other == parent) { continue; } int nxt = (label + j + 1) % r; res[e.idx] = nxt; dfs(cur, e.other, nxt); j++; } } boolean check(int num) { int cnt = 0; for (List<Edge> ls : graph) { if (ls.size() > num) { cnt++; } } return cnt <= k; } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } private void formatPrint(double val) { outln(String.format("%.9f%n", val)); } public CFA() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFA(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
ddc373565b8daf0e39c27cab58e2bcfc
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class G { String filename = null; final int INF = 1_000_000_000; int last; List<Edge>[] g; int[] vertexes, colors, startColors; boolean[] used; void dfs(int v){ used[v] = true; int notColor = startColors[v]; int curColor = 1; for(Edge edge : g[v]){ if(!used[edge.to]){ if(curColor == notColor) curColor++; if(curColor > last) curColor = 1; startColors[edge.to] = curColor; colors[edge.num] = curColor; dfs(edge.to); curColor++; } } } class Edge{ int to, num; Edge(int t, int n){ to = t; num = n; } } void solve(){ int n = readInt(); int k = readInt(); int[] degrees = new int[n]; g = new List[n]; for(int i = 0;i<n;i++){ g[i] = new ArrayList<>(); } int max = 0; for(int i = 0;i<n-1;i++){ int from = readInt() - 1; int to = readInt() - 1; degrees[from]++; degrees[to]++; max = Math.max(max, Math.max(degrees[from], degrees[to])); g[from].add(new Edge(to, i)); g[to].add(new Edge(from, i)); } vertexes = new int[max + 1]; for(int i = 0;i<n;i++){ vertexes[degrees[i]]++; } int d = 0; last = 0; for(int i = max;i>=0;i--){ if(d + vertexes[i] > k){ last = i; break; } d += vertexes[i]; } colors = new int[n - 1]; startColors = new int[n]; used = new boolean[n]; dfs(0); out.println(last); for(int i = 0;i<n - 1;i++){ out.print(colors[i] + " "); } } public static void main(String[] args) { new G().run(); } private void run() { try { init(); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } private BufferedReader in; private StringTokenizer tok = new StringTokenizer(""); private PrintWriter out; private void init() { if (filename == null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); return; } try { in = new BufferedReader(new FileReader(new File(filename))); out = new PrintWriter(new File(filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } } private String readLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } private String readString() { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (nextLine == null) return null; tok = new StringTokenizer(nextLine); } return tok.nextToken(); } private int readInt() { return Integer.parseInt(readString()); } private long readLong() { return Long.parseLong(readString()); } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
2e113c61b084b14b408c364fd3591d56
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.LinkedList; public class CF1141G { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] split = br.readLine().split(" "); int n = Integer.parseInt(split[0]); int k = Integer.parseInt(split[1]); ArrayList<Edge> el = new ArrayList<>(); ArrayList<Edge>[] e = new ArrayList[n]; BitSet[] compsPerCity = new BitSet[n]; for(int i=0; i<n; i++) { e[i] = new ArrayList<>(); compsPerCity[i] = new BitSet(); } for(int i=0; i<n-1; i++) { split = br.readLine().split(" "); int a = Integer.parseInt(split[0])-1; int b = Integer.parseInt(split[1])-1; Edge cur = new Edge(a, b); e[a].add(cur); e[b].add(cur); el.add(cur); } ArrayList<Pair> degs = new ArrayList<>(); for(int i=0; i<n; i++) { degs.add(new Pair(i, e[i].size())); } Collections.sort(degs); int r = degs.get(0).d; int ptr = 0; while(ptr<degs.size() && r>1) { int test = r-1; while(ptr<degs.size() && degs.get(ptr).d>test) ptr++; if(ptr<=k) r = test; else break; } // for(int i=0; i<n; i++) { // int curIndex = degs.get(i).i; // int compIndex = 0; // for(Edge cur: e[curIndex]) { // if(cur.c==-1) { // if(compsPerCity[i].cardinality()==r) { // compIndex = (compIndex+1)%r; // cur.c = compIndex; // } else { // while(compsPerCity[i].get(compIndex)) compIndex = (compIndex+1)%r; // cur.c = compIndex; // compsPerCity[i].set(compIndex); // } // } // } // } BitSet visited = new BitSet(); LinkedList<Pair> q = new LinkedList<>(); visited.set(degs.get(0).i); int c = 0; for(Edge next : e[degs.get(0).i]) { if(next.a==degs.get(0).i) { visited.set(next.b); q.add(new Pair(next.b, c)); } else { visited.set(next.a); q.add(new Pair(next.a, c)); } next.c = c; c = (c+1)%r; } while(!q.isEmpty()) { Pair cur = q.poll(); c = (cur.d+1)%r; for(Edge next : e[cur.i]) { if(next.c==-1) { if(next.a==cur.i && !visited.get(next.b)) { visited.set(next.b); q.add(new Pair(next.b, c)); } else if(next.b==cur.i && !visited.get(next.a)) { visited.set(next.a); q.add(new Pair(next.a, c)); } next.c = c; c = (c+1)%r; } } } StringBuilder sb = new StringBuilder(); sb.append(r).append("\n"); for(Edge cur: el) sb.append(cur.c+1).append(" "); System.out.print(sb.toString().trim()); } static class Pair implements Comparable<Pair>{ int i, d; Pair(int a, int b){ i = a; d = b; } @Override public int compareTo(Pair o) { return o.d-d; } } static class Edge{ int a, b, c; Edge(int x, int y){ a = x; b = y; c = -1; } } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
ec4758d63e9cb0325d318c10848331da
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.*; import java.util.*; public class ProblemG { public static InputStream inputStream = System.in; public static OutputStream outputStream = System.out; public static void main(String[] args) { MyScanner scanner = new MyScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); int n = scanner.nextInt(); int k = scanner.nextInt(); Tree tree = new Tree(n); for (int i = 0; i < n - 1; i++) { int x = scanner.nextInt(); int y = scanner.nextInt(); tree.addEdge(i, x, y); } List<Node> nodes = new ArrayList<>(tree.nodes.values()); Collections.sort(nodes, Comparator.comparingInt(a -> a.adjacents.size())); Collections.reverse(nodes); Set<Integer> set = new HashSet<>(); for (int i = 0; i < k; i++) { set.add(nodes.get(i).label); } int max = nodes.get(k).adjacents.size(); int[] ans = new int[n + 1]; Node root = tree.nodes.get(1); LinkedList<Node> toVisit = new LinkedList<>(); toVisit.add(root); while (!toVisit.isEmpty()) { Node node = toVisit.poll(); int color = node.color + 1; if (color > max) { color = 1; } for (Pair<Integer, Node> pair : node.adjacents) { if (ans[pair.first] == 0) { if (pair.second.label != node.label) { if (set.contains(node.label)) { ans[pair.first] = 1; pair.second.color = 1; } else { ans[pair.first] = color; pair.second.color = color; color++; if (color > max) { color = 1; } } toVisit.add(pair.second); } } } } out.println(max); for (int i = 0; i < n - 1; i++) { out.print(ans[i] + " "); } out.flush(); } private static class Tree { private Map<Integer, Node> nodes = new HashMap<>(); private Tree(int n) { for (int i = 1; i <= n; i++) { nodes.put(i, new Node(i)); } } private void addEdge(int index, int x, int y) { nodes.get(x).adjacents.add(new Pair<>(index, nodes.get(y))); nodes.get(y).adjacents.add(new Pair<>(index, nodes.get(x))); } } private static class Node { private int label; private int color; private List<Pair<Integer, Node>> adjacents = new ArrayList<>(); private Node(int label) { this.label = label; } } private static class MyScanner { private BufferedReader bufferedReader; private StringTokenizer stringTokenizer; private MyScanner(InputStream inputStream) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); } private String next() { while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) { try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return stringTokenizer.nextToken(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } private String nextLine() { String str = ""; try { str = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } private static class Pair<F, S> { private F first; private S second; public Pair() {} public Pair(F first, S second) { this.first = first; this.second = second; } } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
24947d14ad072d4075a76c2528f5a5b9
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.*; import java.util.*; import java.awt.Point; public class CF_1141G { static ArrayList<ArrayList<Integer>> adj; public static void main(String args[]) throws Exception { BufferedScanner in = new BufferedScanner(System.in); BufferedPrinter out = new BufferedPrinter(System.out); int n = in.nextInt(), k = in.nextInt(); adj = get2D(n); int[] cnts = new int[n]; Point[] es = new Point[n - 1]; for (int i = 0; i < n - 1; i++) { int u = in.nextInt() - 1, v = in.nextInt() - 1; adj.get(u).add(v); adj.get(v).add(u); es[i] = new Point(u, v); cnts[u]++; cnts[v]++; } int[] cntsLp = new int[n]; for (int i = 0; i < n; i++) { cntsLp[cnts[i]]++; } int ans = n - 1; while (ans >= 0 && k >= 0) { k -= cntsLp[ans]; ans--; } ans++; calcEdges(0, -1, ans, -1); out.println(ans); for (int i = 0; i < n - 1; i++) out.print((lp.get(es[i]) + 1) + " "); out.close(); in.close(); } static HashMap<Point, Integer> lp = new HashMap<>(); static void calcEdges(int curr, int p, int lim, int c) { lp.put(new Point(curr, p), c); lp.put(new Point(p, curr), c); boolean evil = adj.get(curr).size() > lim; int currC = 0; for (Integer v : adj.get(curr)) { if (v != p) { if (!evil && currC == c) currC++; force(lim == 0 || currC < lim); calcEdges(v, curr, lim, currC); if (!evil) currC++; } } } /** * My template below. FastIO and utility functions. * Minimized with https://codebeautify.org/javaviewer. */ // @formatter:off static<T>ArrayList<ArrayList<T>>get2D(int n){ArrayList<ArrayList<T>>ret=new ArrayList<>();for(int i=0;i<n;i++)ret.add(new ArrayList<>());return ret;} static void force(boolean condition){if(!condition)throw new IllegalStateException();} static class BufferedPrinter{PrintWriter out;BufferedPrinter(OutputStream out){this(new OutputStreamWriter(out));} BufferedPrinter(Writer out){this.out=new PrintWriter(new BufferedWriter(out));} void print(Object...os){for(int i=0;i<os.length;i++){if(i!=0)out.print(' ');out.print(os[i]);}} void println(Object...os){print(os);out.println();} void close(){out.close();} void flush(){out.flush();}} static class BufferedScanner{private final InputStream in;private final byte[]buf=new byte[1<<13];int pos,count;BufferedScanner(InputStream in)throws IOException{this.in=in;} long nextLong()throws IOException{return Long.parseLong(next());} int[]nextN(int n)throws IOException{int[]ret=new int[n];for(int i=0;i<n;i++)ret[i]=this.nextInt();return ret;} long[]nextNL(int n)throws IOException{long[]ret=new long[n];for(int i=0;i<n;i++)ret[i]=this.nextLong();return ret;} private int read(){if(count==-1)err();try{if(pos>=count){pos=0;count=in.read(buf);if(count<=0)return-1;}}catch(IOException e){err();} return buf[pos++];} private static boolean isSpace(int c){return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;} private int readSkipSpace(){int ret;do{ret=read();}while(isSpace(ret));return ret;} int nextInt(){int sign=1;int c=readSkipSpace();if(c=='-'){sign=-1;c=read();} int ret=0;do{if(c<'0'||c>'9')err();ret=ret*10+c-'0';c=read();}while(!isSpace(c));return sign*ret;} String next(){StringBuilder sb=new StringBuilder();int c=readSkipSpace();do{sb.append((char)c);c=read();}while(!isSpace(c));return sb.toString();} private void err(){throw new InputMismatchException();} void close()throws IOException{in.close();}} // @formatter:on }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
0fae8b848ba43c1739aa5b59db45462c
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.*; import java.util.*; import java.awt.Point; public class CF_1141G { static ArrayList<ArrayList<Integer>> adj; public static void main(String args[]) throws Exception { BufferedScanner in = new BufferedScanner(System.in); BufferedPrinter out = new BufferedPrinter(System.out); int n = in.nextInt(), k = in.nextInt(); adj = get2D(n); int[] cnts = new int[n]; Point[] es = new Point[n - 1]; for (int i = 0; i < n - 1; i++) { int u = in.nextInt() - 1, v = in.nextInt() - 1; adj.get(u).add(v); adj.get(v).add(u); es[i] = new Point(u, v); cnts[u]++; cnts[v]++; } int[] cntsLp = new int[n]; for(int i = 0; i < n; i++){ cntsLp[cnts[i]]++; } int ans = n - 1; while(ans >= 0 && k >= 0){ k -= cntsLp[ans]; ans--; } ans++; out.println(ans); addLp = true; kLeft = k; possib(0, -1, ans, -1); for (int i = 0; i < n - 1; i++) out.print((lp.get(es[i]) + 1) + " "); out.close(); in.close(); } static int kLeft; static HashMap<Point, Integer> lp = new HashMap<>(); static boolean addLp = false; static void possib(int curr, int p, int lim, int c) { if(addLp){ lp.put(new Point(curr, p), c); lp.put(new Point(p, curr), c); } boolean evil = adj.get(curr).size() > lim; if (evil) kLeft--; int currC = 0; for (Integer v : adj.get(curr)) { if (v != p) { if (!evil && currC == c) currC++; force(lim == 0 || currC < lim); possib(v, curr, lim, currC); if (!evil) currC++; } } } /** * My template below. FastIO and utility functions. * Minimized with https://codebeautify.org/javaviewer. */ // @formatter:off static<T>ArrayList<ArrayList<T>>get2D(int n){ArrayList<ArrayList<T>>ret=new ArrayList<>();for(int i=0;i<n;i++)ret.add(new ArrayList<>());return ret;} static void force(boolean condition){if(!condition)throw new IllegalStateException();} static class BufferedPrinter{PrintWriter out;BufferedPrinter(OutputStream out){this(new OutputStreamWriter(out));} BufferedPrinter(Writer out){this.out=new PrintWriter(new BufferedWriter(out));} void print(Object...os){for(int i=0;i<os.length;i++){if(i!=0)out.print(' ');out.print(os[i]);}} void println(Object...os){print(os);out.println();} void close(){out.close();} void flush(){out.flush();}} static class BufferedScanner{private final InputStream in;private final byte[]buf=new byte[1<<13];int pos,count;BufferedScanner(InputStream in)throws IOException{this.in=in;} long nextLong()throws IOException{return Long.parseLong(next());} int[]nextN(int n)throws IOException{int[]ret=new int[n];for(int i=0;i<n;i++)ret[i]=this.nextInt();return ret;} long[]nextNL(int n)throws IOException{long[]ret=new long[n];for(int i=0;i<n;i++)ret[i]=this.nextLong();return ret;} private int read(){if(count==-1)err();try{if(pos>=count){pos=0;count=in.read(buf);if(count<=0)return-1;}}catch(IOException e){err();} return buf[pos++];} private static boolean isSpace(int c){return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;} private int readSkipSpace(){int ret;do{ret=read();}while(isSpace(ret));return ret;} int nextInt(){int sign=1;int c=readSkipSpace();if(c=='-'){sign=-1;c=read();} int ret=0;do{if(c<'0'||c>'9')err();ret=ret*10+c-'0';c=read();}while(!isSpace(c));return sign*ret;} String next(){StringBuilder sb=new StringBuilder();int c=readSkipSpace();do{sb.append((char)c);c=read();}while(!isSpace(c));return sb.toString();} private void err(){throw new InputMismatchException();} void close()throws IOException{in.close();}} // @formatter:on }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
17ab9aab45967b272354ef94f31621f7
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.InputMismatchException; import java.util.List; public class Q7 { public static void main(String[] args) { InputReader s = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t = 1; // t = s.nextInt(); nexttest: while (t-- > 0) { int n = s.nextInt(); int k = s.nextInt(); ArrayList<Edge>[] g = new ArrayList[n]; Degree[] degrees = new Degree[n]; for (int i = 0; i < n; i++) { g[i] = new ArrayList<>(); degrees[i] = new Degree(0, i); } for (int i = 0; i < n - 1; i++) { int l = s.nextInt() - 1; int r = s.nextInt() - 1; g[l].add(new Edge(r, i)); g[r].add(new Edge(l, i)); degrees[l].degree++; degrees[r].degree++; } Arrays.sort(degrees); // System.out.println(Arrays.toString(degrees)); int color[] = new int[n - 1]; boolean[] bad = new boolean[n]; for (int i = n - k; i < n ; i++) bad[degrees[i].id] = true; dfs(0, bad, color, g, -1); for (int i = n - k - 1; i >= 0; i--) { int node = degrees[i].id; HashSet<Integer> taken = new HashSet<>(); for (Edge edge : g[node]) { if (color[edge.id] != 0) { if (taken.contains(color[edge.id])) throw new RuntimeException("Errrorooro"); taken.add(color[edge.id]); } } int curr = 1; for (Edge edge : g[node]) { if (color[edge.id] == 0) { while (taken.contains(curr)) { curr++; } color[edge.id] = curr; taken.add(curr); } } } int max = 0; for (int i = 0; i < n - 1; i++) { if (color[i] == 0) { color[i] = 1; } max = Math.max(max, color[i]); } out.println(max); for (int i = 0; i < n - 1; i++) { out.print(color[i] + " "); } } out.close(); } static void dfs(int node, boolean[] bad, int[] color, ArrayList<Edge>[] g, int parentEdgeColor) { if(bad[node]) { for (Edge edge : g[node]) { if (color[edge.id] == 0) { color[edge.id] = 1; dfs(edge.next, bad, color, g, 1); } } } int curr = 1; for (Edge edge : g[node]) { if (color[edge.id] == 0) { if (curr == parentEdgeColor) curr++; color[edge.id] = curr; dfs(edge.next, bad, color, g, curr); curr++; } } } static class Degree implements Comparable<Degree> { int degree; int id; public Degree(final int degree, final int id) { this.degree = degree; this.id = id; } @Override public int compareTo(final Degree o) { return this.degree - o.degree; } @Override public String toString() { return "Degree{" + "degree=" + degree + ", id=" + id + '}'; } } static class Edge { int next; int id; public Edge(final int next, final int id) { this.next = next; this.id = id; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private InputReader.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); } } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
d4a9a93a9d3b473716c9c7d07bf778e6
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.lang.*; import java.math.*; import java.util.*; import java.io.*; public class Main{ class Node { int id; int x; public Node(int id,int x){ this.id=id; this.x=x; } } void solve() { n=ni(); k=ni(); g=new ArrayList[n+1]; for(int i=1;i<=n;i++) g[i]=new ArrayList<>(); deg=new int[n+1]; deg2=new int[n+1]; for(int i=1;i<n;i++){ int u=ni(),v=ni(); g[u].add(new Node(i,v)); g[v].add(new Node(i,u)); deg[u]++; deg[v]++; deg2[u]++; deg2[v]++; } Arrays.sort(deg2,1,n+1); int l=1,r=n; while(l<=r){ int mid=(l+r)>>1; if(check(mid)){ R=mid; r=mid-1; }else l=mid+1; } ans=new int[n]; c=new int[R+1]; dfs(1,-1,-1); pw.println(R); for(int i=1;i<n;i++) pw.print((ans[i]+1)+" "); pw.println(""); } int deg[]; int deg2[]; int n,k; ArrayList<Node> g[]; int R=-1; int ans[]; int c[]; void dfs(int v,int pr,int id){ if(id!=-1) c[ans[id]]=1; // if(v==4) { // for(int i=0;i<2;i++) pw.print(c[i]+" "); // pw.println(""); // } // pw.println(v+" "+deg[v]); int j=0; if(deg[v]<=R) { for (Node p : g[v]) { if (p.x == pr) continue; while (c[j] == 1) { j++; } // if(v==4) pw.println(j+" "+p.x); ans[p.id] = j; j++; } }else { for(Node p : g[v]){ if(p.x==pr) continue; ans[p.id]=0; } } if(id!=-1) c[ans[id]]=0; for(Node p : g[v]){ if(p.x==pr) continue; c[ans[p.id]]=0; } for(Node p : g[v]){ if(p.x!=pr) dfs(p.x,v,p.id); } } boolean check(int mid){ int cc=0; for(int i=1;i<=n;i++) if(deg2[i]>mid) cc++; return cc<=k; } long M = (long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o)); } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
8cf8399f549287e359e4d828c48eeb93
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.util.*; import java.io.*; public class Mainfre { public static class node implements Comparable<node> { int u,id; node(){} node(int u,int id) { this.u=u; this.id=id; } @Override public int compareTo(node rhs) { return rhs.u-u; } } static ArrayList<node>[] G=new ArrayList[212345]; static int[] res=new int[212345]; static boolean[] vis=new boolean[212345]; static void dfs(int u,int fa,int col) { boolean[] used=new boolean[G[u].size()+1]; if (col<=G[u].size()) used[col]=true; int now=1; for (int i=0;i<G[u].size();++i) { int v=G[u].get(i).u; // v is the index of dealing node if (v==fa) continue;// if v is equal to father continue if (vis[u]) {//if node is already visited res[G[u].get(i).id]=1;// coloring all the paths that belong to current node to 1 as this is visited dfs(v,u,1);// making dfs } else { while (used[now]) ++now;// taking the appropriate value of now used[now]=true;// making it equal to true res[G[u].get(i).id]=now;// coloring that path to 1 dfs(v,u,now); // running recursive dfs } } } public static void main(String[] args) throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); StringTokenizer sa=new StringTokenizer(in.readLine()); int n=Integer.parseInt(sa.nextToken()); int k=Integer.parseInt(sa.nextToken()); for (int i=1;i<=n;++i) G[i]=new ArrayList<node>(); for (int i=0;i<n-1;++i) { sa=new StringTokenizer(in.readLine()); int x=Integer.parseInt(sa.nextToken()); int y=Integer.parseInt(sa.nextToken()); G[x].add(new node(y,i)); G[y].add(new node(x,i)); } PriorityQueue<node> que=new PriorityQueue<node>(); for (int i=1;i<=n;++i) que.add(new node(G[i].size(),i)); for (int i=0;i<k;++i) { vis[que.peek().id]=true; que.poll(); } out.println(que.peek().u); dfs(1,0,0); for (int i=0;i<n-1;++i) out.printf("%d%c",res[i],i+2==n?'\n':' ');//printing the colors out.close(); } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
6566ece25aca38472106e973c720f88c
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class TaskG { private static Map<Integer, List<Integer>> adjacent = new HashMap<>(); private static Map<Integer, List<Integer>> roadIndex = new HashMap<>(); private static int colorCount; private static int[] color; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer nkt = new StringTokenizer(in.readLine()); int n = Integer.parseInt(nkt.nextToken()); int k = Integer.parseInt(nkt.nextToken()); int[] u = new int[n - 1]; int[] v = new int[n - 1]; for (int i = 0; i < n - 1; i++) { StringTokenizer uvt = new StringTokenizer(in.readLine()); u[i] = Integer.parseInt(uvt.nextToken()); v[i] = Integer.parseInt(uvt.nextToken()); } int[] e = new int[n + 1]; for (int i = 0; i < n - 1; i++) { e[u[i]] += 1; e[v[i]] += 1; adjacent.computeIfAbsent(u[i], $ -> new ArrayList<>()).add(v[i]); roadIndex.computeIfAbsent(u[i], $ -> new ArrayList<>()).add(i); adjacent.computeIfAbsent(v[i], $ -> new ArrayList<>()).add(u[i]); roadIndex.computeIfAbsent(v[i], $ -> new ArrayList<>()).add(i); } Arrays.sort(e); int L = 1; int R = n - 1; while (L < R) { int M = (L + R) / 2; int countBad = countGreater(e, M); if (countBad > k) { L = M + 1; } else { R = M; } } colorCount = L; color = new int[n - 1]; colorDfs(1, -1, -1); StringBuilder output = new StringBuilder(); output.append(colorCount).append("\n"); for (int i = 0; i < n - 1; i++) { output.append(color[i]).append(" "); } System.out.println(output.toString()); in.close(); } private static void colorDfs(int v, int parent, int parentColor) { List<Integer> adj = adjacent.get(v); List<Integer> road = roadIndex.get(v); boolean skipParentColor = true; if (parent == -1) { skipParentColor = false; } else if (adj.size() - 1 >= colorCount) { skipParentColor = false; } int colorIndex = 1; if (skipParentColor && colorIndex == parentColor) { if (colorIndex < colorCount) { colorIndex += 1; } } for (int i = 0; i < adj.size(); i++) { int u = adj.get(i); if (u == parent) continue; int r = road.get(i); color[r] = colorIndex; if (colorIndex < colorCount) { colorIndex++; if (skipParentColor && colorIndex == parentColor) { if (colorIndex < colorCount) { colorIndex += 1; } } } colorDfs(u, v, color[r]); } } /** * @param values sorted naturally (1, 2, 3, .. ) * @param key key * @return count of values: value > key */ private static int countGreater(int[] values, int key) { int L = 0; int R = values.length - 1; while (L < R) { int M = (L + R) / 2; if (values[M] <= key) { L = M + 1; } else { R = M; } } // values[L] is first bigger or last-of-array if (values[L] <= key) { assert L == values.length - 1; L = values.length; } return values.length - L; } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
94333b093243dca4208b1970b7c69643
train_001.jsonl
1553006100
Treeland consists of $$$n$$$ cities and $$$n-1$$$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right β€” the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $$$k$$$ and the number of companies taking part in the privatization is minimal.Choose the number of companies $$$r$$$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $$$k$$$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $$$r$$$ that there is such assignment to companies from $$$1$$$ to $$$r$$$ that the number of cities which are not good doesn't exceed $$$k$$$. The picture illustrates the first example ($$$n=6, k=2$$$). The answer contains $$$r=2$$$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $$$3$$$) is not good. The number of such vertices (just one) doesn't exceed $$$k=2$$$. It is impossible to have at most $$$k=2$$$ not good cities in case of one company.
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.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Washoum */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; inputClass in = new inputClass(inputStream); PrintWriter out = new PrintWriter(outputStream); GPrivatizationOfRoadsInTreeland solver = new GPrivatizationOfRoadsInTreeland(); solver.solve(1, in, out); out.close(); } static class GPrivatizationOfRoadsInTreeland { static GPrivatizationOfRoadsInTreeland.Node[] graph; static boolean[] visited; static int n; static int k; static int ans; static int[] rep; static void dfs(int a, int sauf, int par) { visited[a] = true; int which = 1; GPrivatizationOfRoadsInTreeland.Pair p; int i; for (i = 0; i < graph[a].edges.size() && which <= ans; i++) { p = graph[a].edges.get(i); if (p.x != par) { if (which == sauf) { which++; if (which > ans) { break; } } rep[p.pos] = which; which++; } } which = 1; if (graph[a].edges.size() > ans) { for (int j = i; j < graph[a].edges.size(); j++) { if (graph[a].edges.get(j).x != par) { rep[graph[a].edges.get(j).pos] = which; which++; if (which == ans + 1) { which = 1; } } } } for (GPrivatizationOfRoadsInTreeland.Pair o : graph[a].edges) { if (!visited[o.x]) { dfs(o.x, rep[o.pos], a); } } } public void solve(int testNumber, inputClass sc, PrintWriter out) { n = sc.nextInt(); k = sc.nextInt(); graph = new GPrivatizationOfRoadsInTreeland.Node[n]; visited = new boolean[n]; for (int i = 0; i < n; i++) { graph[i] = new GPrivatizationOfRoadsInTreeland.Node(); graph[i].edges = new ArrayList<>(); } int x, y; GPrivatizationOfRoadsInTreeland.Pair p; for (int i = 0; i < n - 1; i++) { x = sc.nextInt() - 1; y = sc.nextInt() - 1; p = new GPrivatizationOfRoadsInTreeland.Pair(); p.x = y; p.pos = i; graph[x].edges.add(p); p = new GPrivatizationOfRoadsInTreeland.Pair(); p.x = x; p.pos = i; graph[y].edges.add(p); } int l = 1; int r = n - 1; ans = n - 1; while (r - l >= 0) { int mid = (l + r) / 2; if (check(mid)) { ans = mid; r = mid - 1; } else { l = mid + 1; } } rep = new int[n - 1]; dfs(0, -1, -1); out.println(ans); for (int i = 0; i < n - 1; i++) { out.print(rep[i] + " "); } out.println(); } private boolean check(int mid) { int cmb = 0; for (int i = 0; i < n; i++) { if (graph[i].edges.size() > mid) { cmb++; } } if (cmb > k) { return false; } else { return true; } } static class Pair { int x; int pos; } static class Node { ArrayList<GPrivatizationOfRoadsInTreeland.Pair> edges; } } static class inputClass { BufferedReader br; StringTokenizer st; public inputClass(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6 2\n1 4\n4 3\n3 5\n3 6\n5 2", "4 2\n3 1\n1 4\n1 2", "10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9"]
2 seconds
["2\n1 2 1 1 2", "1\n1 1 1", "3\n1 1 2 3 2 3 1 3 1"]
null
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "binary search", "dfs and similar", "trees" ]
0cc73612bcfcd3be142064e2da9e92e3
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200000, 0 \le k \le n - 1$$$) β€” the number of cities and the maximal number of cities which can have two or more roads belonging to one company. The following $$$n-1$$$ lines contain roads, one road per line. Each line contains a pair of integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$), where $$$x_i$$$, $$$y_i$$$ are cities connected with the $$$i$$$-th road.
1,900
In the first line print the required $$$r$$$ ($$$1 \le r \le n - 1$$$). In the second line print $$$n-1$$$ numbers $$$c_1, c_2, \dots, c_{n-1}$$$ ($$$1 \le c_i \le r$$$), where $$$c_i$$$ is the company to own the $$$i$$$-th road. If there are multiple answers, print any of them.
standard output
PASSED
cdaec304d7da4e6a5a2bfe2481ac2f8e
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.io.*; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } String readString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine(), " :"); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() { return Integer.parseInt(readString()); } int[] readIntArray(int size) { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long readLong() { return Long.parseLong(readString()); } double readDouble() { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } class SegmentTree { long[] cnt; long[] push; int n; int size; SegmentTree(int n) { this.n = n; size = 4 * n; cnt = new long[size]; push = new long[size]; } void push(int v) { if (push[v] == 0) return; cnt[v] += push[v]; if (v * 2 < size) { push[v * 2] += push[v]; } if (v * 2 + 1 < size) { push[v * 2 + 1] += push[v]; } push[v] = 0; } void add(int v, int tl, int tr, int left, int right, long val) { push(v); if (tl == left && tr == right) { push[v] += val; push(v); return; } int mid = (tl + tr) / 2; if (right <= mid) { add(v * 2, tl, mid, left, right, val); } else if (left > mid) { add(v * 2 + 1, mid + 1, tr, left, right, val); } else { add(v * 2, tl, mid, left, mid, val); add(v * 2 + 1, mid + 1, tr, mid + 1, right, val); } } long get(int v, int tl, int tr, int index) { push(v); if (tl == tr) { return cnt[v]; } int mid = (tl + tr) / 2; return index <= mid ? get(v * 2, tl, mid, index) : get(v * 2 + 1, mid + 1, tr, index); } void add(int x, int y, long val) { add(1, 1, n, x, y, val); } long get(int x) { return get(1, 1, n, index.get(x)); } } SegmentTree sum; SegmentTree count; int[] left; int[] right; int[] key; int[] mostLeft; int[] mostRight; int get(int i) { return index.get(i); } void dfsX(int index) { if (left[index] == -1) { mostLeft[index] = index; mostRight[index] = index; return; } dfsX(left[index]); dfsX(right[index]); mostLeft[index] = mostLeft[left[index]]; mostRight[index] = mostRight[right[index]]; } void dfs(int x, int l, int r) { if (left[x] == -1) return; int k = key[x]; add(index.higherEntry(l - 1).getValue(), index.lowerEntry(k).getValue(), key[mostLeft[right[x]]]); add(index.higherEntry(k).getValue(), index.lowerEntry(r + 1).getValue(), key[mostRight[left[x]]]); dfs(left[x], l, k - 1); dfs(right[x], k + 1, r); } void add(int l, int r, long val) { sum.add(l, r, val); count.add(l, r, 1); } TreeMap<Integer, Integer> index; private void solve() { int n = readInt(); left = new int[n]; right = new int[n]; Arrays.fill(left, -1); Arrays.fill(right, -1); key = new int[n]; mostRight = new int[n]; mostLeft = new int[n]; TreeSet<Integer> set = new TreeSet<>(); int[] p = new int[n]; int rootIndex = 0; for (int i = 0; i < n; i++) { p[i] = readInt(); key[i] = readInt(); set.add(key[i]); if (p[i] == -1) { rootIndex = i; } } for (int i = 0; i < n; i++) { if (p[i] == -1) continue; p[i]--; if (key[p[i]] < key[i]) { right[p[i]] = i; } else { left[p[i]] = i; } } int k = readInt(); int[] q = new int[k]; for (int i = 0; i < k; i++) { q[i] = readInt(); set.add(q[i]); } index = new TreeMap<>(); for (int x : set) { index.put(x, index.size() + 1); } sum = new SegmentTree(index.size()); count = new SegmentTree(index.size()); int lower = set.first(); int upper = set.last(); dfsX(rootIndex); dfs(rootIndex, lower, upper); for (int r : q) { long x = sum.get(r); long y = count.get(r); out.println(1d * x / y); } } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 8
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
b9599174c5f7b432674889dcf0b6c5ff
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class Main { final static boolean debug = false; final static String fileName = ""; final static boolean useFiles = false; public static void main(String[] args) throws FileNotFoundException { PrintWriter writer = new PrintWriter(System.out); new Task(new InputReader(System.in), writer).solve(); writer.close(); } } 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 double nextDouble() { return Double.parseDouble(next()); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public byte nextByte() { return Byte.parseByte(next()); } } class Interval implements Comparable<Interval> { Interval(int l, int r, double p, int id) { Left = l; Right = r; Probability = p; Id = id; } double Probability; int Left, Right, Id; ArrayList<Interval> Dependents = new ArrayList<>(); @Override public int compareTo(Interval o) { int x = Left - o.Left; if (x != 0) return x; x = o.Right - Right; if (x != 0) return x; return Id - o.Id; } } class Node{ Node Left, Right; int Key; long Sum; int Index, Depth; boolean isLeaf(){ return Left == null && Right == null; } } class Query { Query(int key, int id) { Key = key; Index = id; } int Key; double Answer; int Index; } class Task { void dfs(Node[] nodes, Node v){ if (v.isLeaf()) return; v.Left.Sum = v.Sum + nodes[v.Index + 1].Key; v.Right.Sum = v.Sum + nodes[v.Index - 1].Key; v.Left.Depth = v.Right.Depth = v.Depth + 1; dfs(nodes, v.Left); dfs(nodes, v.Right); } void print(Node v, PrintWriter out){ if (v.isLeaf()) out.print(v.Key + " "); else { print(v.Left, out); out.print(v.Key + " "); print(v.Right, out); } } public void solve() { int n = in.nextInt(); Node[] nodes = new Node[n]; for (int i = 0; i < n; i++) nodes[i] = new Node(); Node root = null; for (int i = 0; i < n; i++) { int parent = in.nextInt() - 1; nodes[i].Key = in.nextInt(); if (parent == -2) root = nodes[i]; else { if (nodes[parent].Left == null) nodes[parent].Left = nodes[i]; else nodes[parent].Right = nodes[i]; } } for (int i = 0; i < n; i++) { if (nodes[i].isLeaf()) continue; if (nodes[i].Left.Key > nodes[i].Right.Key) { Node t = nodes[i].Left; nodes[i].Left = nodes[i].Right; nodes[i].Right = t; } } Arrays.sort(nodes, (o1, o2) -> o1.Key - o2.Key); for (int i = 0; i < n; i++) nodes[i].Index = i; dfs(nodes, root); // print(root, out); // out.println(); int k = in.nextInt(); Query[] queries = new Query[k]; for (int i = 0; i < k; i++) { queries[i] = new Query(in.nextInt(), i); } Arrays.sort(queries, (o1, o2) -> o1.Key - o2.Key); for (int i = 0, j = 0; i < k; i++) { for (; j < n && nodes[j].Key < queries[i].Key; j++) ; if (0 <= j - 1 && nodes[j - 1].isLeaf()) queries[i].Answer = nodes[j - 1].Sum / (double) nodes[j - 1].Depth; else queries[i].Answer = nodes[j].Sum / (double) nodes[j].Depth; } Arrays.sort(queries, (o1, o2) -> o1.Index - o2.Index); for (int i = 0; i < k; i++) out.println(queries[i].Answer + " "); // int n = in.nextInt(); // int[] a = new int[n]; // for (int i = 0; i < n; i++) // a[i] = in.nextInt(); // int q = in.nextInt(); // Interval[] intervals = new Interval[q]; // for (int i = 0; i < q; i++) { // intervals[i] = new Interval(in.nextInt() - 1, in.nextInt() - 1, in.nextDouble(), i); // } // Arrays.sort(intervals); // Interval root = new Interval(0, n - 1, 0, q); // Stack<Interval> stack = new Stack<>(); // stack.add(root); // for (Interval interval : intervals) { // while (stack.peek().Right < interval.Left) // stack.pop(); // stack.peek().Dependents.add(interval); // } } private InputReader in; private PrintWriter out; Task(InputReader in, PrintWriter out) { this.in = in; this.out = out; } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 8
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
c72c312f454e9704e6348d123ad54197
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.util.*; import java.io.*; public class TaskC { class Summarizer { int n; long[] keys; long[] sum; void updateSum(int pos, long value) { while (pos <= n) { sum[pos] += value; pos = (pos | (pos - 1)) + 1; } } void update(long min, long max, long value) { if (min > keys[n-1]) return; if (max < keys[0]) return; int l = -1, r = n-1; while (r - l > 1) { int c = (l + r) / 2; if (keys[c] >= min) r = c; else l = c; } int left = r; l = 0; r = n; while (r - l > 1) { int c = (l + r) / 2; if (keys[c] <= max) l = c; else r = c; } int right = l; if (left > right) return; left++; right++; updateSum(left, value); updateSum(right+1, -value); } long getSum(int pos) { long res = 0; while (pos > 0) { res += sum[pos]; pos &= pos - 1; } return res; } public long getValueAt(int pos) { pos++; return getSum(pos); } public Summarizer(long[] keys) { this.n = keys.length; this.keys = keys; this.sum = new long[n + 1]; } } class Key implements Comparable<Key> { int id; long value; double ans; public Key(int id, long value) { this.id = id; this.value = value; } public int compareTo(Key other) { return this.value < other.value ? -1 : 1; } } public void doMain() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] parent = new int[n]; long[] key = new long[n]; boolean[] isLeaf = new boolean[n]; Arrays.fill(isLeaf, true); int root = -1; int[][] edg = new int[n][2]; int[] edgCnt = new int[n]; for (int i=0; i < n; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); parent[i] = Integer.parseInt(st.nextToken()); if (parent[i] != -1) { parent[i]--; isLeaf[parent[i]] = false; } else root = i; key[i] = Integer.parseInt(st.nextToken()); if (parent[i] != -1) { edg[parent[i]][edgCnt[parent[i]]++] = i; } } int k = Integer.parseInt(br.readLine()); Key[] keys = new Key[k]; for (int i=0; i < k; i++) { keys[i] = new Key(i, Integer.parseInt(br.readLine())); } br.close(); long[] treeKeys = new long[n]; for (int i=0; i < n; i++) treeKeys[i] = key[i]; Arrays.sort(treeKeys); Arrays.sort(keys); long[] searchKeys = new long[k]; for (int i=0; i < k; i++) searchKeys[i] = keys[i].value; Arrays.sort(searchKeys); Summarizer counts = new Summarizer(searchKeys); Summarizer sums = new Summarizer(searchKeys); final int INF = 1100000000; int[] Q = new int[n]; long[] QL = new long[n]; long[] QR = new long[n]; int qBeg = 0, qEnd = 0; Q[qBeg] = root; QL[qBeg] = -INF; QR[qBeg++] = INF; while (qEnd < qBeg) { int curV = Q[qEnd]; long curL = QL[qEnd]; long curR = QR[qEnd++]; if (!isLeaf[curV]) { int pos = Arrays.binarySearch(treeKeys, key[curV]); counts.update(key[curV] + 1, curR, 1); sums.update(key[curV] + 1, curR, treeKeys[pos-1]); counts.update(curL, key[curV] - 1, 1); sums.update(curL, key[curV] - 1, treeKeys[pos+1]); } for (int i=0; i < edgCnt[curV]; i++) { if (key[edg[curV][i]] < key[curV]) { Q[qBeg] = edg[curV][i]; QL[qBeg] = curL; QR[qBeg++] = key[curV] - 1; } else { Q[qBeg] = edg[curV][i]; QL[qBeg] = key[curV] + 1; QR[qBeg++] = curR; } } } double[] answer = new double[k]; for (int i=0; i < k; i++) { int pos = Arrays.binarySearch(searchKeys, keys[i].value); long sum = sums.getValueAt(pos); long cnt = counts.getValueAt(pos); answer[keys[i].id] = sum / (double)cnt; } for (int i=0; i < k; i++) System.out.println(answer[i]); } public static void main(String[] args) throws Exception { (new TaskC()).doMain(); } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 6
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
df401f3481f0a82bf24ff97092276164
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { private BufferedReader in; private PrintWriter out; private StringTokenizer st; private void eat(String line) { st = new StringTokenizer(line); } private String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) return null; eat(line); } return st.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); eat(""); go(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } public static void main(String[] args) { new Thread(new Main()).start(); } private class Node { public Node left, right, parent; public int value, min, max, size, height; public long errorSum; public Node(int value) { left = right = parent = null; this.value = this.min = this.max = value; size = 1; errorSum = 0L; height = 0; } public boolean isLeaf() { return left == null && right == null; } public void update() { if (isLeaf()) { min = max = value; size = 1; } else { left.update(); min = left.min; right.update(); max = right.max; size = left.size + right.size + 1; } } public void updateHeight() { if (parent == null) height = 0; else height = parent.height + 1; if (!isLeaf()) { left.updateHeight(); right.updateHeight(); } } public void updateErrorSum() { if (parent == null) errorSum = 0; else { errorSum = parent.errorSum; if (this == parent.left) errorSum += parent.right.min; else errorSum += parent.left.max; } if (!isLeaf()) { left.updateErrorSum(); right.updateErrorSum(); } } } private Node makeTree(int n, int[] p, int[] v) { Node[] node = new Node[n]; for (int i = 0; i < n; ++i) node[i] = new Node(v[i]); Node root = null; for (int i = 0; i < n; ++i) { int parent = p[i] - 1; if (parent >= 0) { if (v[i] < v[parent]) node[parent].left = node[i]; else node[parent].right = node[i]; node[i].parent = node[parent]; } else { root = node[i]; root.parent = null; } } root.update(); root.updateHeight(); root.updateErrorSum(); return root; } private void getPlainRepresentation(Node root, int offset, Node[] node, int[] value, boolean[] isLeaf) { if (root.isLeaf()) { value[offset] = root.value; isLeaf[offset] = true; node[offset] = root; } else { getPlainRepresentation(root.left, offset, node, value, isLeaf); offset += root.left.size; value[offset] = root.value; isLeaf[offset] = false; node[offset] = root; offset += 1; getPlainRepresentation(root.right, offset, node, value, isLeaf); } } public void go() throws IOException { int n = nextInt(); int[] p = new int[n], v = new int[n]; for (int i = 0; i < n; ++i) { p[i] = nextInt(); v[i] = nextInt(); } Node root = makeTree(n, p, v); Node[] node = new Node[n]; int[] value = new int[n]; boolean[] isLeaf = new boolean[n]; getPlainRepresentation(root, 0, node, value, isLeaf); int k = nextInt(); while (k-- != 0) { int key = nextInt(); int index = -Arrays.binarySearch(value, key) - 1; index = Math.min(index, n - 1); if (!isLeaf[index]) --index; double expectation = (double) node[index].errorSum / (double) node[index].height; out.printf("%.9f\n", expectation); } } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 6
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
c6d333c7759ee91327efd3689a8b33ec
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class C { int[][] children; int[] keys; Integer[] sorted; int[] toSorted; double[] expected; private int n; public void run() { n = nextInt(); children = new int[n][2]; keys = new int[n]; sorted = new Integer[n]; toSorted = new int[n]; expected = new double[n]; for (int i = 0; i < n; ++i) { children[i][0] = -1; children[i][1] = -1; } int root = -1; for (int i = 0; i < n; ++i) { int p = nextInt() - 1; int k = nextInt(); if (p >= 0) { if (children[p][0] == -1) { children[p][0] = i; } else { children[p][1] = i; } } else { root = i; } keys[i] = k; sorted[i] = i; } Arrays.sort(sorted, new Comparator<Integer>() { public int compare(Integer a, Integer b) { return keys[a] - keys[b]; } }); for (int i = 0; i < n; ++i) { toSorted[sorted[i]] = i; } dfs(root, 0, 0); int k = nextInt(); for (int i = 0; i < k; ++i) { int x = nextInt(); int v = findLeaf(x); if (children[v][0] != -1) { v = sorted[toSorted[v] + 1]; } System.out.println(expected[v]); } } void dfs(int v, long error, int depth) { if (children[v][0] == -1) { expected[v] = (double)error / depth; } else { if (keys[children[v][0]] > keys[children[v][1]]) { int t = children[v][0]; children[v][0] = children[v][1]; children[v][1] = t; } dfs(children[v][0], error + keys[sorted[toSorted[v]+1]], depth + 1); dfs(children[v][1], error + keys[sorted[toSorted[v]-1]], depth + 1); } } int findLeaf(int k) { int left = 0; int right = n; while (left + 1 < right) { int mid = (left + right) / 2; if (k < keys[sorted[mid]]) { right = mid; } else { left = mid; } } return sorted[left]; } public static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public static StringTokenizer tokenizer; public static void main(String[] args) throws IOException { new C().run(); } public static String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new Error(e); } } return tokenizer.nextToken(); } public static int nextInt() { return Integer.parseInt(nextToken()); } public static long nextLong() { return Long.parseLong(nextToken()); } public static double nextDouble() { return Double.parseDouble(nextToken()); } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 6
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
eb6d8ce8b9cb6d0102f3096bed7fcbbf
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.io.*; import java.util.*; public class Solution implements Runnable { BufferedReader input; StringTokenizer tokenizer; PrintWriter output; int n; int[] p; int[] val; int[] left; int[] right; int[] depth; int[] minleft; int[] maxright; int[] minlefti; int[] maxrighti; long[] sum; int root; private void solve() throws Exception { n = nextInt(); p = new int[n]; left = new int[n]; right = new int[n]; depth = new int[n]; minleft = new int[n]; minlefti = new int[n]; maxright = new int[n]; maxrighti = new int[n]; val = new int[n]; sum = new long[n]; Arrays.fill(left, -1); Arrays.fill(right, -1); Arrays.fill(depth, -1); for (int i = 0; i < n; i++) { int u = nextInt() - 1; int k = nextInt(); p[i] = u; val[i] = k; minleft[i] = maxright[i] = k; minlefti[i] = maxrighti[i] = i; if (u == -2) { root = i; } else { if (left[u] == -1) { left[u] = i; } else { right[u] = i; if (val[left[u]] > val[right[u]]) { right[u] = left[u]; left[u] = i; } } } } int[] q = new int[n]; q[0] = root; depth[root] = 0; int qh = 0; int qt = 1; for (; qh < qt; qh++) { int u = q[qh]; int d = depth[u]; if (left[u] != -1) { int v = left[u]; depth[v] = d + 1; q[qt++] = v; v = right[u]; depth[v] = d + 1; q[qt++] = v; } } int numleaves = 0; for (int i = qt - 1; i >= 0; i--) { int u = q[i]; if (left[u] == -1) { numleaves++; continue; } minleft[u] = minleft[left[u]]; minlefti[u] = minlefti[left[u]]; maxright[u] = maxright[right[u]]; maxrighti[u] = maxrighti[right[u]]; } for (int i = 1; i < qt; i++) { int u = q[i]; int v = p[u]; sum[u] = sum[v]; if (left[v] == u) { sum[u] += minleft[right[v]]; } else { sum[u] += maxright[left[v]]; } } long[] sortkeys = new long[n]; for (int i = 0; i < n; i++) { sortkeys[i] = ((long)val[i]) * n + i; } Arrays.sort(sortkeys); int[] sortedval = new int[n]; int[] sortedi = new int[n]; for (int i = 0; i < n; i++) { sortedval[i] = (int)(sortkeys[i] / n); sortedi[i] = (int)(sortkeys[i] % n); } int m = nextInt(); for (int i = 0; i < m; i++) { int x = nextInt(); // int u = root; // while (left[u] != -1) // { // u = x < val[u] ? left[u] : right[u]; // } int su = binSearch(sortedval, x); int u = su == -1 ? minlefti[root] : sortedi[su]; if (right[u] != -1 && su < n - 1) { u = sortedi[su + 1]; } output.println(1.0 * sum[u] / depth[u]); } } int binSearch(int[] a, int x) { int l = -1; int r = n; while (l + 1 < r) { int m = (l + r) / 2; if (a[m] < x) { l = m; } else { r = m; } } return l; } private int nextInt() throws Exception { return Integer.parseInt(next()); } private String next() throws Exception { if (tokenizer == null || !tokenizer.hasMoreTokens()) { String s = ""; while (s.equals("")) { s = input.readLine(); } tokenizer = new StringTokenizer(s); } return tokenizer.nextToken(); } private void out(String s) { output.println(s); } public void run() { try { solve(); } catch (Exception ex) { throw new RuntimeException(ex); } finally { output.close(); } } public Solution() throws IOException { input = new BufferedReader(new InputStreamReader(System.in)); output = new PrintWriter(System.out); } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Thread(new Solution()).start(); } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 6
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
e995f8dc2b1f4f4b6dc63fa5b3683972
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.util.*; import static java.lang.Math.*; import java.io.*; public class C implements Runnable{ static int N, K; static Node[] T; static int root, numleaves; static int[] max; static double[] avg; static int[] Q; public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); N = Integer.valueOf(in.readLine().trim()); T = new Node[N]; root = -1; for(int i = 0; i < N;i++){ StringTokenizer stok = new StringTokenizer(in.readLine()); int p = Integer.valueOf(stok.nextToken()); T[i] = new Node(); T[i].parent = p-1; T[i].key = Integer.valueOf(stok.nextToken()); T[i].id = i; if(p == -1){ root = i; } } for(int i = 0; i < N;i++){ if(T[i].parent >= 0){ int p = T[i].parent; if(T[i].key < T[p].key) T[p].left = i; else T[p].right = i; } } numleaves = 0; for(Node n:T) if(n.left == -1) numleaves++; K = Integer.valueOf(in.readLine().trim()); Q = new int[K]; for(int i = 0; i < K;i++){ StringTokenizer stok = new StringTokenizer(in.readLine()); Q[i] = Integer.valueOf(stok.nextToken()); } max = new int[numleaves]; avg = new double[numleaves]; new Thread(null, new Runnable() { public void run() { new C().run(); } }, "1", 1 << 24).start(); } public void run() { update(T[root]); computeavg(T[root]); at = 0; updatefinal(T[root], Integer.MAX_VALUE); StringBuilder output = new StringBuilder(); for(int i = 0; i < K;i++){ int q = Q[i]; int index = Arrays.binarySearch(max, q); index = -(1+index); double ans = avg[index]; output.append(String.format("%.015f\n", ans)); } System.out.print(output); } static int at; private void updatefinal(Node n, int m) { if(n.left != -1){ updatefinal(T[n.left], n.key); updatefinal(T[n.right], m); }else{ avg[at] = n.avg/n.numavg; max[at] = m; at++; } } void computeavg(Node n) { if(n.parent >=0){ n.avg = T[n.parent].avg; n.numavg = T[n.parent].numavg; if(T[n.parent].left == n.id){ n.avg += T[T[n.parent].right].min; }else{ n.avg += T[T[n.parent].left].max; } n.numavg++; } if(n.left != -1){ computeavg(T[n.left]); computeavg(T[n.right]); } } int update(Node n) { n.min = n.key; n.max = n.key; if(n.left != -1){ update(T[n.left]); n.min = min(n.min, T[n.left].min); n.max = max(n.max, T[n.left].max); update(T[n.right]); n.min = min(n.min, T[n.right].min); n.max = max(n.max, T[n.right].max); } return n.min; } static class Node{ int id; int left, right, parent; int key; int min, max; double avg; int numavg; public Node(){ left = -1; right = -1; avg = 0; numavg = 0; } } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 6
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
a48147a9c174111420c702edd03141fe
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.util.InputMismatchException; import java.util.Comparator; import java.io.*; import java.util.Locale; import java.util.SortedSet; import java.util.Arrays; /** * Generated by Contest helper plug-in * Actual solution is at the bottom */ public class Main { public static void main(String[] args) { InputReader in = new StreamInputReader(System.in); PrintWriter out = new PrintWriter(System.out); run(in, out); } public static void run(InputReader in, PrintWriter out) { Solver solver = new taskC(); solver.solve(1, in, out); Exit.exit(in, out); } } abstract class InputReader { private boolean finished = false; public abstract int read(); public int nextInt() { return Integer.parseInt(nextToken()); } public String readString() { return readLine(); } public String readLine() { StringBuffer res = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') res.appendCodePoint(c); c = read(); } return res.toString(); } public String nextToken() { 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; } public void setFinished(boolean finished) { this.finished = finished; } public abstract void close(); } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public StreamInputReader(InputStream stream) { this.stream = stream; curChar = 0; } 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++]; } @Override public void close() { try { stream.close(); } catch (IOException ignored) { } } } class Exit { private Exit() { } public static void exit(InputReader in, PrintWriter out) { in.setFinished(true); in.close(); out.close(); } } interface Solver { public void solve(int testNumber, InputReader in, PrintWriter out); } class taskC implements Solver { int left[]; int right[]; int val[]; int par[]; boolean leaf[]; int funcLeft[]; int funcRight[]; int depth[]; long funcExpected[]; void dfs(int cur, int dep) { depth[cur] = dep; if (leaf[cur]) { funcLeft[cur] = funcRight[cur ] = val[cur]; } else { dfs(left[cur], dep + 1); dfs(right[cur], dep + 1); funcLeft[cur] = funcLeft[left[cur]]; funcRight[cur] = funcRight[right[cur]]; } } void calcFunc(int cur, long sum) { if (leaf[cur]) { funcExpected[cur] = sum; } else { int t = funcRight[left[cur]]; calcFunc(right[cur], sum + t); t = funcLeft[right[cur]]; calcFunc(left[cur], sum + t); } } int up[]; int down[]; void calcLeafs(int cur, int U, int D) { if (leaf[cur]) { up[cur] = U; down[cur] = D; } else { calcLeafs(left[cur], U, val[cur] - 1); calcLeafs(right[cur], val[cur] + 1, D); } } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); left = new int[n]; right = new int[n]; val = new int[n]; par = new int[n]; leaf = new boolean[n]; Arrays.fill(leaf, true); Arrays.fill(left, -1); int root = -1; for (int i = 0; i < n; ++i) { int a = in.nextInt(); int b = in.nextInt(); par[i] = a - 1; val[i] = b; if (a != -1) { if (left[a - 1] == -1) { leaf[a - 1] = false; left[a - 1] = i; } else right[a - 1] = i; } else root = i; } for (int i =0; i < n; ++i) { if (!leaf[i]) { if (val[left[i]] > val[right[i]]) { int tmp = left[i]; left[i] = right[i]; right[i] = tmp; } } } funcLeft = new int[n]; funcRight = new int[n]; depth = new int[n]; dfs(root, 0); funcExpected = new long[n]; down = new int[n]; up = new int[n]; calcLeafs(root, 0, 1000000001); calcFunc(root, 0); int k = in.nextInt(); int cnt = 0; for (int i = 0; i < n; ++i) { if (leaf[i]) ++ cnt; } Pair [] ar = new Pair[cnt]; cnt = 0; for (int i = 0; i < n ;++i) { if (leaf[i]) { ar[cnt ++] = new Pair(up[i], down[i], i); } } Arrays.sort(ar, new Comparator<Pair>() { public int compare(Pair o1, Pair o2) { return o1.L - o2.L; } }); for (int i = 0; i < k; ++i) { int x = in.nextInt(); int t = Arrays.binarySearch(ar, new Pair(x, x, 0), new Comparator<Pair>() { public int compare(Pair o1, Pair o2) { if (o1.L <= o2.L && o2.L <= o1.R) return 0; return o1.L - o2.L; } }); t = ar[t].vertex; double res = funcExpected[t] / (double ) depth[t]; out.printf(Locale.US, "%.10f\n",res ); } } class Pair { int L, R; int vertex; Pair(int l, int r, int vertex) { L = l; R = r; this.vertex = vertex; } Pair(int l, int r) { L = l; R = r; } } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 6
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
32d4fd1a30b7f24d6413ad65954d6720
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.util.InputMismatchException; import java.util.Comparator; import java.io.*; import java.util.Locale; import java.util.SortedSet; import java.util.Arrays; /** * Generated by Contest helper plug-in * Actual solution is at the bottom */ public class Main { public static void main(String[] args) { InputReader in = new StreamInputReader(System.in); PrintWriter out = new PrintWriter(System.out); run(in, out); } public static void run(InputReader in, PrintWriter out) { Solver solver = new taskC(); solver.solve(1, in, out); Exit.exit(in, out); } } abstract class InputReader { private boolean finished = false; public abstract int read(); public int nextInt() { return Integer.parseInt(nextToken()); } public String readString() { return readLine(); } public String readLine() { StringBuffer res = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') res.appendCodePoint(c); c = read(); } return res.toString(); } public String nextToken() { 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; } public void setFinished(boolean finished) { this.finished = finished; } public abstract void close(); } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public StreamInputReader(InputStream stream) { this.stream = stream; curChar = 0; } 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++]; } @Override public void close() { try { stream.close(); } catch (IOException ignored) { } } } class Exit { private Exit() { } public static void exit(InputReader in, PrintWriter out) { in.setFinished(true); in.close(); out.close(); } } interface Solver { public void solve(int testNumber, InputReader in, PrintWriter out); } class taskC implements Solver { int left[]; int right[]; int val[]; int par[]; boolean leaf[]; int funcLeft[]; int funcRight[]; int depth[]; long funcExpected[]; void dfs(int cur, int dep) { depth[cur] = dep; if (leaf[cur]) { funcLeft[cur] = funcRight[cur ] = val[cur]; } else { dfs(left[cur], dep + 1); dfs(right[cur], dep + 1); funcLeft[cur] = funcLeft[left[cur]]; funcRight[cur] = funcRight[right[cur]]; } } void calcFunc(int cur, long sum) { if (leaf[cur]) { funcExpected[cur] = sum; } else { int t = funcRight[left[cur]]; calcFunc(right[cur], sum + t); t = funcLeft[right[cur]]; calcFunc(left[cur], sum + t); } } int up[]; int down[]; void calcLeafs(int cur, int U, int D) { if (leaf[cur]) { up[cur] = U; down[cur] = D; } else { calcLeafs(left[cur], U, val[cur] - 1); calcLeafs(right[cur], val[cur] + 1, D); } } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); left = new int[n]; right = new int[n]; val = new int[n]; par = new int[n]; leaf = new boolean[n]; Arrays.fill(leaf, true); Arrays.fill(left, -1); int root = -1; for (int i = 0; i < n; ++i) { int a = in.nextInt(); int b = in.nextInt(); par[i] = a - 1; val[i] = b; if (a != -1) { if (left[a - 1] == -1) { leaf[a - 1] = false; left[a - 1] = i; } else right[a - 1] = i; } else root = i; } for (int i =0; i < n; ++i) { if (!leaf[i]) { if (val[left[i]] > val[right[i]]) { int tmp = left[i]; left[i] = right[i]; right[i] = tmp; } } } funcLeft = new int[n]; funcRight = new int[n]; depth = new int[n]; dfs(root, 0); funcExpected = new long[n]; down = new int[n]; up = new int[n]; calcLeafs(root, 0, 1000000001); calcFunc(root, 0); int k = in.nextInt(); int cnt = 0; for (int i = 0; i < n; ++i) { if (leaf[i]) ++ cnt; } Pair [] ar = new Pair[cnt]; cnt = 0; for (int i = 0; i < n ;++i) { if (leaf[i]) { ar[cnt ++] = new Pair(up[i], down[i], i); } } Arrays.sort(ar, new Comparator<Pair>() { public int compare(Pair o1, Pair o2) { return o1.L - o2.L; } }); for (int i = 0; i < k; ++i) { int x = in.nextInt(); if (leaf[root]) { out.printf(Locale.US, "%.10f\n",val[root]); } else { //int t = getLeaf(root, x); int t = ar[getIndex(x, ar)].vertex; double res = funcExpected[t] / (double ) depth[t]; out.printf(Locale.US, "%.10f\n",res ); } } } int getIndex(int value, Pair[] a) { int l = 0, r = a.length; while (l <= r) { int m = (l + r) / 2; if (a[m].L <= value && a[m].R >= value) return m; if (a[m].R < value) l = m + 1; else r = m - 1; } throw new RuntimeException(); } class Pair { int L, R; int vertex; Pair(int l, int r, int vertex) { L = l; R = r; this.vertex = vertex; } Pair(int l, int r) { L = l; R = r; } } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 6
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
1cc9c533450b776349ab301dc9a0802d
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.util.*; import java.io.*; public class C_as { FastScanner in; PrintWriter out; int[] l; int[] r; long[] v; long[] sumv; int[] vl; long[] max; long[] min; int root; int[] lcp; int[] li; long[] lv; int ln; int[] depth; void dfs(int u) { if (l[u] == -1) { li[ln] = u; vl[u] = ln; lv[ln] = v[u]; ln++; } else { dfs(l[u]); lcp[ln - 1] = u; dfs(r[u]); } } long dfsMax(int u) { if (l[u] == -1) { return max[u] = v[u]; } else { dfsMax(l[u]); return max[u] = dfsMax(r[u]); } } long dfsMin(int u) { if (l[u] == -1) { return min[u] = v[u]; } else { dfsMin(r[u]); return min[u] = dfsMin(l[u]); } } void dfsSum(int u, long sum, int d) { if (l[u] == -1) { sumv[vl[u]] = sum; depth[vl[u]] = d; } else { dfsSum(l[u], sum + min[r[u]], d + 1); dfsSum(r[u], sum + max[l[u]], d + 1); } } public void solve() throws IOException { int n = in.nextInt(); int[] p = new int[n]; l = new int[n]; r = new int[n]; v = new long[n]; for (int i = 0; i < n; i++) { p[i] = in.nextInt(); v[i] = in.nextInt(); if (p[i] == -1) { root = i; } else { p[i]--; } } Arrays.fill(l, -1); Arrays.fill(r, -1); for (int i = 0; i < n; i++) { if (p[i] != -1) { if (v[i] < v[p[i]]) { l[p[i]] = i; } else { r[p[i]] = i; } } } lcp = new int[n]; li = new int[n]; lv = new long[n]; vl = new int[n]; dfs(root); min = new long[n]; max = new long[n]; dfsMin(root); dfsMax(root); sumv = new long[n]; depth = new int[n]; dfsSum(root, 0, 0); int k = in.nextInt(); for (int i = 0; i < k; i++) { long key = in.nextLong(); int z = Arrays.binarySearch(lv, 0, ln, key); z = -(z + 1); double ans; if (z == 0) { ans = 1.0 * sumv[0] / depth[0]; } else if (z == ln) { ans = 1.0 * sumv[ln - 1] / depth[ln - 1]; } else { long tv = v[lcp[z - 1]]; if (tv > key) { z = z - 1; } ans = 1.0 * sumv[z] / depth[z]; } out.println(ans); } } public void run() { try { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] arg) { new C_as().run(); } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { System.err.println(e); return ""; } } return st.nextToken(); } void close() { try { br.close(); } catch (IOException e) { } } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 6
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
f587196c4ac6e5a7b9c88107f3908ac3
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.util.*; public class C { private static Scanner in; int n; int[] key; int[] parent; int[] left; int[] right; int[] from; int[] to; int[] size; int root; public void run() { n = in.nextInt(); key = new int[n]; parent = new int[n]; left = new int[n]; right = new int[n]; from = new int[n]; to = new int[n]; size = new int[n]; Arrays.fill(parent, -1); Arrays.fill(left, -1); Arrays.fill(right, -1); for (int i = 0; i < n; i++) { int p = parent[i] = in.nextInt() - 1; key[i] = in.nextInt(); if (p < 0) { root = i; } else { if (left[p] == -1) { left[p] = i; } else { if (key[i] < key[left[p]]) { right[p] = left[p]; left[p] = i; } else { right[p] = i; } } } } dfs1(root); int m = in.nextInt(); int[] a = new int[m]; for (int i = 0; i < m; i++) { a[i] = in.nextInt(); } int[] aa = a.clone(); Arrays.sort(a); amount = new int[m + 1]; sum = new long[m + 1]; dfs2(root, a, 0, m); int am = 0; long s = 0; HashMap<Integer, Double> answer = new HashMap<Integer, Double>(); for (int i = 0; i < m; i++) { am += amount[i]; s += sum[i]; answer.put(a[i], s * 1d / am); } for (int x : aa) { System.out.println(answer.get(x)); } } private void dfs2(int v, int[] a, int x, int z) { if (left[v] == -1) { return; } int y = - 1 - Arrays.binarySearch(a, /*x, z,*/ key[v]); y = Math.max(x, y); y = Math.min(z, y); add(x, y, from[right[v]]); add(y, z, to[left[v]]); dfs2(left[v], a, x, y); dfs2(right[v], a, y, z); } int[] amount; long[] sum; private void add(int x, int y, int value) { amount[x]++; sum[x] += value; amount[y]--; sum[y] -= value; } private void dfs1(int v) { if (left[v] == -1) { from[v] = to[v] = key[v]; size[v] = 1; return; } dfs1(left[v]); dfs1(right[v]); from[v] = from[left[v]]; to[v] = to[right[v]]; size[v] = 1 + size[left[v]] + size[right[v]]; } public static void main(String[] args) { Locale.setDefault(Locale.US); in = new Scanner(System.in); new C().run(); in.close(); } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 6
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
64ae2d929c46b5e56b83ea230d119556
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Locale; import java.util.StringTokenizer; public class C implements Runnable { int[] left; int[] right; int[] leftmost; int[] rightmost; int[] height; long[] sum; int[] val; int[] par; int[] x; void dfs(int u, int h, int[] l, int[] r) { height[u] = h; leftmost[u] = val[u]; rightmost[u] = val[u]; if (left[u] != -1 && right[u] != -1) { dfs(left[u], h + 1, l, r); leftmost[u] = l[0]; dfs(right[u], h + 1, l, r); rightmost[u] = r[0]; } l[0] = leftmost[u]; r[0] = rightmost[u]; } void dfs2(int u, long add) { sum[u] = add; if (left[u] != -1 && right[u] != -1) { dfs2(left[u], add + leftmost[right[u]]); dfs2(right[u], add + rightmost[left[u]]); } } HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); private int[] data; private void solve() throws IOException { int n = nextInt(); left = new int[n]; right = new int[n]; par = new int[n]; Arrays.fill(left, -1); Arrays.fill(right, -1); val = new int[n]; data = new int[n]; leftmost = new int[n]; rightmost = new int[n]; height = new int[n]; sum = new long[n]; Arrays.fill(sum, 0); int x, y; int root = -1; for (int i = 0; i < n; ++i) { x = nextInt(); y = nextInt(); par[i] = x - 1; data[i] = val[i] = y; map.put(val[i], i); } for (int i = 0; i < n; ++i) { if (par[i] != -2) { if (val[par[i]] > val[i]) { left[par[i]] = i; } else { right[par[i]] = i; } } else { root = i; } } dfs(root, 0, new int[1], new int[1]); dfs2(root, 0); Arrays.sort(data); int k = nextInt(); int sch, pos; for (int i = 0; i < k; ++i) { sch = nextInt(); pos = findLower(data, sch); if (left[map.get(data[pos])] != -1) { ++pos; } pos = map.get(data[pos]); out.println((double)sum[pos] / height[pos]); } } private int findLower(int[] data2, int sch) { int down = 0; int up = data2.length; int mid= 0; while (up > down + 1) { mid = (up + down) / 2; if (data2[mid] < sch) { down = mid; } else { up = mid; } } return down; } /** * @param args */ public static void main(String[] args) { new Thread(new C()).start(); } private BufferedReader br; private StringTokenizer st; private PrintWriter out; @Override public void run() { try { Locale.setDefault(Locale.US); //br = new BufferedReader(new FileReader("input.txt")); br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); out = new PrintWriter(System.out); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } String next() throws IOException { while (!st.hasMoreTokens()) { String temp = br.readLine(); if (temp == null) { return null; } st = new StringTokenizer(temp); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 6
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
c59fdbf59e95806a4b195fdfb00ffbf9
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.lang.*; import java.math.BigInteger; import java.io.*; import java.util.*; public class Solution implements Runnable{ public static BufferedReader br; public static PrintWriter out; public static StringTokenizer stk; public static boolean isStream = true; public static void main(String[] args) throws IOException { if (isStream) { br = new BufferedReader(new InputStreamReader(System.in)); } else { br = new BufferedReader(new FileReader("in.txt")); } out = new PrintWriter(System.out); new Thread(new Solution()).start(); } public void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } public String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return ""; } } public String nextWord() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return stk.nextToken(); } public Integer nextInt() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Integer.valueOf(stk.nextToken()); } public Long nextLong() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Long.valueOf(stk.nextToken()); } public Double nextDouble() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Double.valueOf(stk.nextToken()); } public Float nextFloat() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Float.valueOf(stk.nextToken()); } ArrayList<Integer>[] map; int n; int[] key, skey; double[] dp; HashMap<Integer, Integer> isLeaf; void dfs(int pos, double M, double depth) { if (map[pos].size() == 0) { dp[pos] = M / depth; return; } int k = Arrays.binarySearch(skey, key[pos]); if (key[map[pos].get(0)] < key[map[pos].get(1)]) { // To left dfs(map[pos].get(0), M + skey[k+1], depth+1); // To right dfs(map[pos].get(1), M + skey[k-1], depth+1); } else { // To left dfs(map[pos].get(1), M + skey[k+1], depth+1); // To right dfs(map[pos].get(0), M + skey[k-1], depth+1); } } public void run() { n = nextInt(); map = new ArrayList[n]; for (int i = 0; i < n; i++) { map[i] = new ArrayList<Integer>(); } skey = new int[n]; key = new int[n]; isLeaf = new HashMap<Integer, Integer>(); int root = 0; for (int i = 0; i < n; i++) { int prev = nextInt()-1; if (prev != -2) { map[prev].add(i); } else { root = i; } key[i] = nextInt(); skey[i] = key[i]; } Arrays.sort(skey); for (int i = 0; i < n; i++) { isLeaf.put(key[i], i); } dp = new double[n]; dfs(root, 0, 0); int m = nextInt(); for (int i = 0; i < m; i++) { int nkey = nextInt(); int k = -(Arrays.binarySearch(skey, nkey)+1); if (k-1 >= 0) { if (map[isLeaf.get(skey[k-1])].size() == 0) { out.println(dp[isLeaf.get(skey[k-1])]); } } if (k < n) { if (map[isLeaf.get(skey[k])].size() == 0) { out.println(dp[isLeaf.get(skey[k])]); } } } out.flush(); } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 6
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
f0cb3006d6b0817502d8e337e6a71661
train_001.jsonl
1305903600
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; 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.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Locale; import java.util.Queue; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Solution implements Runnable { public static void main(String[] args) { (new Thread(new Solution())).start(); } BufferedReader in; PrintWriter out; StringTokenizer st; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String r = in.readLine(); if (r == null) return null; st = new StringTokenizer(r); } 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()); } class Node { int k; Node l, r; int lk, rk; Node() { l = r = null; lk = rk = k = 0; } } void dfs(Node q) { if (q.l == null) { q.lk = q.rk = q.k; } else { dfs(q.l); dfs(q.r); q.lk = q.l.lk; q.rk = q.r.rk; } } Q[] ck; long sum; int cnt; int j; Node lastleft; class Q { int n, k; double ans; Q(int q, int w) { n = q; k = w; ans = 0; } } void dfsans(Node q) { if (q.l == null) { while (j < ck.length && (lastleft == null || ck[j].k < lastleft.k)) { ck[j++].ans = (double)sum / cnt; } } else { cnt++; sum += q.r.lk; Node tm = lastleft; lastleft = q; dfsans(q.l); lastleft = tm; sum += q.l.rk - q.r.lk; dfsans(q.r); sum -= q.l.rk; cnt--; } } void solve() throws Exception { int n = nextInt(); Node[] a = new Node[n + 1]; int[] p = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = new Node(); p[i] = nextInt(); a[i].k = nextInt(); } Node root = null; for (int i = 1; i <= n; i++) { if (p[i] == -1) root = a[i]; else { if (a[p[i]].k < a[i].k) a[p[i]].r = a[i]; else a[p[i]].l = a[i]; } } int k = nextInt(); ck = new Q[k]; for (int i = 0; i < k; i++) ck[i] = new Q(i, nextInt()); Arrays.sort(ck, new Comparator<Q>() { public int compare(Q a, Q b) { return a.k - b.k; } }); dfs(root); sum = 0; cnt = 0; lastleft = null; dfsans(root); Arrays.sort(ck, new Comparator<Q>() { public int compare(Q a, Q b) { return a.n - b.n; } }); for (int i = 0; i < k; i++) { out.printf("%.10f\n", ck[i].ans); } } public void run() { Locale.setDefault(Locale.UK); try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // in = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter("output.txt"); solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { out.flush(); } } }
Java
["7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9"]
3 seconds
["8.0000000000", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000"]
NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
Java 6
standard input
[ "probabilities", "sortings", "binary search", "dfs and similar", "trees" ]
afe77e7b2dd6d7940520d9844ab30cfd
The first line contains an odd integer n (3 ≀ n &lt; 105), which represents the number of tree nodes. Next n lines contain node descriptions. The (i + 1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1 ≀ k ≀ 105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All n + k keys are distinct. All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
2,200
Print k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10 - 9.
standard output
PASSED
82bee039a3337c6178673e9d98691aab
train_001.jsonl
1450888500
Genos needs your help. He was asked to solve the following programming problem by Saitama:The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static long sx = 0, sy = 0, mod = (long) (1e9 + 7); static ArrayList<Integer>[] a; static int[][] dp; static int[] size; static long[] farr; public static PrintWriter out; static ArrayList<pair> p = new ArrayList<>(); static long[] fact = new long[(int) 1e6]; static boolean b = false; static StringBuilder sb = new StringBuilder(); static boolean cycle = false; static long m = 998244353; static long[] no, col; static String s; static int ans = 0; static int[] dis; static HashMap<Integer, Integer> hm; public static void main(String[] args) throws IOException { Scanner scn = new Scanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); // Reader scn = new Reader(); String s = scn.next(), p = scn.next(); long[] dp = new long[p.length()]; dp[0] = p.charAt(0) - '0'; for (int i = 1; i < p.length(); i++) dp[i] = dp[i - 1] + p.charAt(i) - '0'; long ans = 0; for (int i = 0; i < s.length(); i++) { int si = i, e = p.length() - s.length() + i; int cnt = (e - si + 1) * (s.charAt(i) - '0'); long sub = dp[e] - (si - 1 >= 0 ? dp[si - 1] : 0); ans += Math.abs(cnt - sub); } System.out.println(ans); } // _________________________TEMPLATE_____________________________________________________________ // public static long lcm(long x, long y) { // // return (x * y) / gcd(x, y); // } // // private static long gcd(long x, long y) { // if (x == 0) // return y; // // return gcd(y % x, x); // } // static class comp implements Comparator<Integer> { // // @Override // public int compare(Integer o1, Integer o2) { // return depth[o2] - depth[o1]; // } // // } // public static long pow(long a, long b) { // // if (b < 0) // return 0; // if (b == 0 || b == 1) // return (long) Math.pow(a, b); // // if (b % 2 == 0) { // // long ret = pow(a, b / 2); // ret = (ret % mod * ret % mod) % mod; // return ret; // } // // else { // return ((pow(a, b - 1) % mod) * a % mod) % mod; // } // } private static class pair implements Comparable<pair> { int pos, pow; pair(int a, int b) { pos = a; pow = b; } @Override public int compareTo(pair o) { return o.pos - this.pos; } } private static String reverse(String s) { return new StringBuilder(s).reverse().toString(); } public 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[1000000 + 1]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public int[][] nextInt2DArray(int m, int n) throws IOException { int[][] arr = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) arr[i][j] = nextInt(); } return arr; } public long[][] nextInt2DArrayL(int m, int n) throws IOException { long[][] arr = new long[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) arr[i][j] = nextInt(); } return arr; } // kickstart - Solution // atcoder - Main } }
Java
["01\n00111", "0011\n0110"]
2 seconds
["3", "2"]
NoteFor the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.The second sample case is described in the statement.
Java 11
standard input
[ "combinatorics", "strings" ]
ed75bd272f6d3050426548435423ca92
The first line of the input contains binary string a (1 ≀ |a| ≀ 200 000). The second line of the input contains binary string b (|a| ≀ |b| ≀ 200 000). Both strings are guaranteed to consist of characters '0' and '1' only.
1,500
Print a single integerΒ β€” the sum of Hamming distances between a and all contiguous substrings of b of length |a|.
standard output
PASSED
440d0cb6076c1dc9b35188817aa3edbb
train_001.jsonl
1450888500
Genos needs your help. He was asked to solve the following programming problem by Saitama:The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.
256 megabytes
/** * @author egaeus * @mail sebegaeusprogram@gmail.com * @veredict Not sended * @url <https://codeforces.com/problemset/problem/608/B> * @category two pointers * @date 6/06/2020 **/ import java.io.*; import java.util.*; import static java.lang.Integer.*; import static java.lang.Math.*; public class CF608B { public static void main(String args[]) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (String ln; (ln = in.readLine()) != null && !ln.equals(""); ) { char[] A = ln.toCharArray(); char[] B = in.readLine().toCharArray(); long[] ones = new long[B.length]; long[] zeros = new long[B.length]; for (int i = 0; i < B.length; i++) { ones[i] = i > 0 ? ones[i - 1] : 0; zeros[i] = i > 0 ? zeros[i - 1] : 0; if (B[i] == '0') zeros[i]++; else ones[i]++; } long s = 0; for (int i = 0; i < A.length; i++) { int from = i, to = B.length - A.length + i; if (A[i] == '0') s += ones[to] - (from > 0 ? ones[from - 1] : 0); else s += zeros[to] - (from > 0 ? zeros[from - 1] : 0); } System.out.println(s); } } }
Java
["01\n00111", "0011\n0110"]
2 seconds
["3", "2"]
NoteFor the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.The second sample case is described in the statement.
Java 11
standard input
[ "combinatorics", "strings" ]
ed75bd272f6d3050426548435423ca92
The first line of the input contains binary string a (1 ≀ |a| ≀ 200 000). The second line of the input contains binary string b (|a| ≀ |b| ≀ 200 000). Both strings are guaranteed to consist of characters '0' and '1' only.
1,500
Print a single integerΒ β€” the sum of Hamming distances between a and all contiguous substrings of b of length |a|.
standard output
PASSED
376919e09a2a5a6eabe231282e513e45
train_001.jsonl
1450888500
Genos needs your help. He was asked to solve the following programming problem by Saitama:The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.
256 megabytes
import java.util.Scanner; public final class HamingDistanceSum { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String a=sc.next(); String b=sc.next(); int n=a.length(); int m=b.length(); int prefix[][]=new int[2][m]; if(b.charAt(0)=='0') prefix[0][0]++; else prefix[1][0]++; for(int i=1;i<m;i++){ prefix[0][i]=prefix[0][i-1]; prefix[1][i]=prefix[1][i-1]; if(b.charAt(i)=='0') prefix[0][i]++; else prefix[1][i]++; } long ans=0; for(int i=0;i<n;i++){ int curr=(a.charAt(i)=='0')?0:1; int right=m-(n-i); ans+=prefix[1-curr][right]; if(i>0){ ans-=prefix[1-curr][i-1]; } } System.out.println(ans); } }
Java
["01\n00111", "0011\n0110"]
2 seconds
["3", "2"]
NoteFor the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.The second sample case is described in the statement.
Java 11
standard input
[ "combinatorics", "strings" ]
ed75bd272f6d3050426548435423ca92
The first line of the input contains binary string a (1 ≀ |a| ≀ 200 000). The second line of the input contains binary string b (|a| ≀ |b| ≀ 200 000). Both strings are guaranteed to consist of characters '0' and '1' only.
1,500
Print a single integerΒ β€” the sum of Hamming distances between a and all contiguous substrings of b of length |a|.
standard output
PASSED
b8db8d05b3907ed396c1c67eb9cf49e7
train_001.jsonl
1450888500
Genos needs your help. He was asked to solve the following programming problem by Saitama:The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main (String[] args) { new A(); } public A() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println(""); char[] a = fs.next().toCharArray(); char[] b = fs.next().toCharArray(); int[] freq = new int[2]; int ptr = b.length; for(int i = 0; i < b.length; i++) { if(i + a.length - 1 < b.length) { freq[b[i]-'0']++; } else { ptr = i; break; } } long res = 0; int ptr1 = 0; for(int i = 0; i < a.length; i++) { res += freq[(a[i]-'0')^1]; freq[b[ptr1]-'0']--; if(ptr < b.length) freq[b[ptr]-'0']++; ptr1++; ptr++; } out.println(res); out.close(); } class FastScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
Java
["01\n00111", "0011\n0110"]
2 seconds
["3", "2"]
NoteFor the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.The second sample case is described in the statement.
Java 11
standard input
[ "combinatorics", "strings" ]
ed75bd272f6d3050426548435423ca92
The first line of the input contains binary string a (1 ≀ |a| ≀ 200 000). The second line of the input contains binary string b (|a| ≀ |b| ≀ 200 000). Both strings are guaranteed to consist of characters '0' and '1' only.
1,500
Print a single integerΒ β€” the sum of Hamming distances between a and all contiguous substrings of b of length |a|.
standard output
PASSED
4b914e8c0ae391ca7debcb31898f0ca9
train_001.jsonl
1450888500
Genos needs your help. He was asked to solve the following programming problem by Saitama:The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.
256 megabytes
// https://codeforces.com/contest/182/submission/70317507 import java.math.*; import java.util.*; import java.io.*; public class B { static BufferedReader in; static String file = "../in"; static int test = 10; // 0 for local testing, 1 for std input static String[] split() throws Exception { return in.readLine().split(" "); } static int readInt() throws Exception { return Integer.valueOf(in.readLine()); } public static void main(String[] args) throws Exception { int _k = Integer.valueOf("1"); if(test > 0) in = new BufferedReader(new InputStreamReader(System.in)); else in = new BufferedReader(new FileReader(file)); if(test < 0) {String[] str = in.readLine().split(" ");} /****************************************************/ /****************************************************/ /****************************************************/ /****************************************************/ String s1 = in.readLine(), s2 = in.readLine(); Map<String, Integer> map = new HashMap<>(); int m = s1.length(); int n = s2.length(); long re = 0; int[] f = new int[n + 1]; for(int i = 0; i < n; i++) { f[i + 1] = f[i] + (s2.charAt(i) == '1' ? 1 : 0); } for(int i = 0; i < m; i++) { int a = s1.charAt(i) == '1' ? 1 : 0; int count = f[n - m + i + 1] - f[i]; if(a == 0) re += count; else re += n - m + 1 - count; // System.out.println(re); } System.out.println(re); } }
Java
["01\n00111", "0011\n0110"]
2 seconds
["3", "2"]
NoteFor the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.The second sample case is described in the statement.
Java 11
standard input
[ "combinatorics", "strings" ]
ed75bd272f6d3050426548435423ca92
The first line of the input contains binary string a (1 ≀ |a| ≀ 200 000). The second line of the input contains binary string b (|a| ≀ |b| ≀ 200 000). Both strings are guaranteed to consist of characters '0' and '1' only.
1,500
Print a single integerΒ β€” the sum of Hamming distances between a and all contiguous substrings of b of length |a|.
standard output
PASSED
4127ef921837722a04fec8c3c8ac706d
train_001.jsonl
1450888500
Genos needs your help. He was asked to solve the following programming problem by Saitama:The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Random; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeSet; import javax.swing.event.TreeExpansionEvent; public class Contest { private static PrintWriter out = new PrintWriter(System.out); private static int n, m, k, tc, x, N; private static int[] a; private static int[][] grid; public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); char[] a = sc.next().toCharArray(); n = a.length; char[] b = sc.next().toCharArray(); m = b.length; //System.out.println(n + " " + m); long[] pref = new long[m + 1]; for(int i = 1;i <= m;i++) { pref[i] = pref[i - 1] + (b[i - 1] == '1'?1:0); } long res = 0; for(int i = 0;i < n;i++) { int st = i; int en = st+1 + m - n; if(a[i] == '0') { res += (pref[en] - pref[st]); }else { res = res + ((long)en - st - (pref[en] - pref[st])); } } out.println(res); out.flush(); } private static void sort(int[] a, int n) { ArrayList<Integer> b = new ArrayList<Integer>(); for (int i = 0; i < n; i++) b.add(a[i]); Collections.sort(b); for (int i = 0; i < n; i++) a[i] = b.get(i); } static final Random random = new Random(); static void ruffleSort(int[] a) { int n = a.length;// shuffle, then sort for (int i = 0; i < n; i++) { int oi = random.nextInt(n), temp = a[oi]; a[oi] = a[i]; a[i] = temp; } java.util.Arrays.sort(a); } // private static class Scanner { // public BufferedReader reader; // public StringTokenizer st; // // public Scanner(InputStream stream) { // reader = new BufferedReader(new InputStreamReader(stream)); // st = null; // } // // public String next() { // while (st == null || !st.hasMoreTokens()) { // try { // String line = reader.readLine(); // if (line == null) // return null; // st = new StringTokenizer(line); // } catch (Exception e) { // throw (new RuntimeException()); // } // } // return st.nextToken(); // } // // public int nextInt() { // return Integer.parseInt(next()); // } // // public long nextLong() { // return Long.parseLong(next()); // } // // public double nextDouble() { // return Double.parseDouble(next()); // } // } }
Java
["01\n00111", "0011\n0110"]
2 seconds
["3", "2"]
NoteFor the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.The second sample case is described in the statement.
Java 11
standard input
[ "combinatorics", "strings" ]
ed75bd272f6d3050426548435423ca92
The first line of the input contains binary string a (1 ≀ |a| ≀ 200 000). The second line of the input contains binary string b (|a| ≀ |b| ≀ 200 000). Both strings are guaranteed to consist of characters '0' and '1' only.
1,500
Print a single integerΒ β€” the sum of Hamming distances between a and all contiguous substrings of b of length |a|.
standard output