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
b130aef72827857669b16d3943cfabcf
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
//package com.company; import java.io.*; import java.util.*; public class Main { static long TIME_START, TIME_END; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileInputStream("Test.in")); PrintWriter pw = new PrintWriter(System.out); // PrintWriter pw = new PrintWriter(new FileOutputStream("Test.in")); TIME_START = System.currentTimeMillis(); Task t = new Task(); t.solve(sc, pw); TIME_END = System.currentTimeMillis(); // pw.println("Time used: " + (TIME_END - TIME_START) + "."); pw.close(); } public static class Task { int MOD = 1000000007; List<Integer>[] child; int[] color; long[][] dp; public void solve(Scanner sc, PrintWriter pw) throws IOException { int n = sc.nextInt(); color = new int[n]; child = new List[n]; for (int i = 0; i < n; i++) { child[i] = new ArrayList<>(); } dp = new long[n][2]; for (int i = 0; i < n - 1; i++) { int p = sc.nextInt(); child[p].add(i + 1); } for (int i = 0; i < n; i++) { color[i] = sc.nextInt(); } dfs(0); pw.println(dp[0][1]); } public void dfs(int u) { if (child[u].size() == 0) { dp[u][color[u]] = 1; dp[u][0] = 1; return; } if (color[u] == 1) { long t = 1; for (int v : child[u]) { dfs(v); t *= dp[v][0]; t %= MOD; } dp[u][0] = t; dp[u][1] = t; } else { long t = 1; for (int v : child[u]) { dfs(v); t *= dp[v][0]; t %= MOD; } for (int v : child[u]) { dp[u][1] += dp[v][1] * t % MOD * powmod(dp[v][0], MOD - 2) % MOD; if (dp[u][1] >= MOD) { dp[u][1] -= MOD; } } dp[u][0] = t + dp[u][1]; } } public int powmod(long a, int b) { if (b == 0) return 1; if (b % 2 == 0) return powmod(a * a % MOD, b >> 1); return (int) (a * powmod(a * a % MOD, b >> 1) % MOD); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader s) throws FileNotFoundException {br = new BufferedReader(s);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
d89be83c522cfc66cdf2a27d334b79dc
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; import java.util.Arrays; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top */ public class MainC { 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 dfs(long[][] dp, ArrayList<Integer>[] tree, int[] colors, int v, int MOD) { if (colors[v] == 1) { dp[v][0] = 0; dp[v][1] = 1; } else { dp[v][0] = 1; dp[v][1] = 0; } if (tree[v] == null) return; for (int u : tree[v]) { dfs(dp, tree, colors, u, MOD); if (colors[v] == 1) { dp[v][1] *= (dp[u][0] + dp[u][1]) % MOD; dp[v][1] = dp[v][1] % MOD; } else { // Assume that dp[v][1] stores the num solutions if there // is a single black node in the children from 1-(u-1). // First suppose the black node does not come from u. // Then it must be between 1-(u-1). // So multiply dp[v][1], which stores that, by dp[u][0], // which is the number of ways to arrange arrange the whites in u. // Now suppose that the black node does come from u. // How many ways are there to get the black node? This is just dp[u][1] but we must also // multiply it by the number of ways to ensure all children from 1 - (u-1) are white. // This value is stored for us in dp[v][0]. dp[v][1] *= (dp[u][0] + dp[u][1]) % MOD; dp[v][1] = dp[v][1] % MOD; dp[v][1] += (dp[v][0] * dp[u][1]) % MOD; dp[v][1] = dp[v][1] % MOD; // Assume that dp[v][0] stores the num solutions if there is are // no black nodes in children from 1-(u-1). // Then for the next child, there continue to be no children. // If u is connected to v, there are dp[u][0] ways. // If u is not connected to v, there are dp[u][1] ways. // You add these together (the total number of ways) // and multiply by the already-existing combinations. dp[v][0] *= (dp[u][0] + dp[u][1]) % MOD; dp[v][0] = dp[v][0] % MOD; } } } public void solve(int testNumber, InputReader in, PrintWriter out) { int MOD = (int) 1e9 + 7; int n = in.nextInt(); ArrayList<Integer>[] tree = (ArrayList<Integer>[]) new ArrayList[n]; int[] colors = new int[n]; for (int i = 0; i < n - 1; i++) { int parent = in.nextInt(); if (tree[parent] == null) { tree[parent] = new ArrayList<Integer>(); } tree[parent].add(i + 1); } for (int i = 0; i < colors.length; i++) { colors[i] = in.nextInt(); } long[][] dp = new long[n][2]; dfs(dp, tree, colors, 0, MOD); out.write((dp[0][1] % MOD) + "\n"); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
412282476608336d7349b8285084b139
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class Main { //SOLUTION BEGIN //Into the Hardware Mode long MOD = (long)1e9+7; void pre() throws Exception{} void solve(int TC) throws Exception { int N = ni(); int[] from = new int[N-1], to = new int[N-1]; for(int i = 0; i< N-1; i++){ from[i] = ni(); to[i] = i+1; } int[][] G = make(N, from, to, N-1, false); int[] X = new int[N]; for(int i = 0; i< N; i++)X[i] = ni(); long[][] DP = new long[N][2]; long[] ways = new long[2]; for(int u = N-1; u>= 0; u--){ ways[X[u]] = 1; ways[X[u]^1] = 0; for(int v:G[u]){ long w0 = (ways[0]*DP[v][1] + ways[0]*DP[v][0])%MOD; long w1 = (ways[1]*DP[v][1] + ways[0]*DP[v][1]+ways[1]*DP[v][0])%MOD; ways[0] = w0; ways[1] = w1; } DP[u] = new long[]{ways[0], ways[1]}; } pn(DP[0][1]); } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} void exit(boolean b){if(!b)System.exit(0);} static void debug(Object... o){System.err.println(Arrays.deepToString(o));} final long IINF = (long)2e18; final int INF = (int)1e9+2; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8; static boolean multipleTC = false, memory = false, fileIO = false; FastReader in;PrintWriter out; void run() throws Exception{ long ct = System.currentTimeMillis(); if (fileIO) { in = new FastReader(""); out = new PrintWriter(""); } else { in = new FastReader(); out = new PrintWriter(System.out); } //Solution Credits: Taranpreet Singh int T = multipleTC? ni():1; pre(); for (int t = 1; t <= T; t++) solve(t); out.flush(); out.close(); System.err.println(System.currentTimeMillis() - ct); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } int[][] make(int n, int[] from, int[] to, int e, boolean f){ int[][] g = new int[n][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = to[i]; if(f)g[to[i]][--cnt[to[i]]] = from[i]; } return g; } int[][][] makeS(int n, int[] from, int[] to, int e, boolean f){ int[][][] g = new int[n][][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0}; if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1}; } return g; } int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));} int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;} long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){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
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
b020e428e5407a0ca751679f450f5e8a
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author beginner1010 */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { ArrayList<Integer>[] G; int[] color; int MOD = (int) 1e9 + 7; long[][] dp; long mod(long x) { x %= MOD; if (x < 0) x += MOD; return x; } void dfs(int node, int parent) { for (Integer children : G[node]) if (children != parent) { dfs(children, node); long[] preDP = new long[2]; // refers to the previous children preDP[0] = dp[node][0]; preDP[1] = dp[node][1]; dp[node][0] = mod(preDP[0] * (dp[children][0] + dp[children][1])); dp[node][1] = mod(preDP[1] * (dp[children][1] + dp[children][0]) + preDP[0] * dp[children][1]); } return; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); G = new ArrayList[n]; for (int i = 0; i < n; i++) G[i] = new ArrayList<Integer>(); for (int i = 0; i < n - 1; i++) { int p = in.nextInt(); G[i + 1].add(p); G[p].add(i + 1); } color = new int[n]; dp = new long[n + 1][2]; for (int i = 0; i < n; i++) { color[i] = in.nextInt(); dp[i][color[i]] = 1; } dfs(0, -1); out.println(dp[0][1]); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
27805a7033e6860f4c6604efd6ddee2c
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
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(); } void dfs(int i, int par) { dp[i][0] = 1; for(int j : adj[i]) { if(j != par) { dfs(j, i); dp[i][1] = dp[i][1] * dp[j][0] % mod; dp[i][1] = (dp[i][1] + dp[i][0] * dp[j][1] % mod) % mod; dp[i][0] = (dp[i][0] * dp[j][0]) % mod; } } // considering case of cutting just above edge if(col[i] == 0) dp[i][0] = (dp[i][0] + dp[i][1]) % mod; else dp[i][1] = dp[i][0]; } ArrayList<Integer> adj[]; int col[]; long dp[][]; long mod = (long)1e9 + 7; public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = sc.nextInt(); adj = new ArrayList[n]; for(int i = 0; i < n; ++i) adj[i] = new ArrayList<>(); for(int i = 1; i < n; ++i) adj[sc.nextInt()].add(i); col = new int[n]; for(int i = 0; i < n; ++i) col[i] = sc.nextInt(); dp = new long[n][2]; dfs(0, -1); w.print(dp[0][1]); w.close(); } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
26ed10942830b4937e51271a186f9dc1
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.io.*; import java.util.*; public class B implements Runnable{ public static void main (String[] args) {new Thread(null, new B(), "_cf", 1 << 28).start();} int MOD = 1000000007; public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println("Go!"); int n = fs.nextInt(); ArrayList<Integer>[] adj = new ArrayList[n]; for(int i = 0; i < n; i++) adj[i] = new ArrayList<>(); for(int i = 1; i < n; i++) { int p = fs.nextInt(); adj[p].add(i); } int[] colors = fs.nextIntArray(n); int[] queue = new int[n]; int tail = 0; queue[tail++] = 0; for(int i = 0; i < tail; i++) { int u = queue[i]; for(int v : adj[u]) queue[tail++] = v; } int[][] dp = new int[2][n]; for(int i = n-1; i >= 0; i--) { int u = queue[i]; dp[0][u] = 1; dp[1][u] = 0; for(int v : adj[u]) { dp[1][u] = mult(dp[0][v], dp[1][u]); dp[1][u] = add(dp[1][u], mult(dp[1][v], dp[0][u])); dp[0][u] = mult(dp[0][u], dp[0][v]); } if(colors[u] == 1) dp[1][u] = dp[0][u]; else dp[0][u] = add(dp[0][u], dp[1][u]); } out.println(dp[1][0]); out.close(); } int add(int a, int b) { return (a + b) % MOD; } int mult(long a, long b) { a *= b; return (int)(a%MOD); } 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) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), 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
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
bce74193fe71655f7af907203b0f351a
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.io.*; import java.util.*; public class B { static final int P = 1_000_000_007; BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; List<Integer>[] g; void solve() throws IOException { int n = nextInt(); g = new List[n]; for (int i = 0; i < n; i++) { g[i] = new ArrayList<>(0); } for (int i = 1; i < n; i++) { g[nextInt()].add(i); } int[] col = new int[n]; for (int i = 0; i < n; i++) { col[i] = nextInt(); } int[][] dp = new int[n][2]; for (int i = n - 1; i >= 0; i--) { dp[i][col[i]] = 1; for (int to : g[i]) { int new1 = 0; int new0 = 0; // take new1 = (int) ((long) dp[i][1] * dp[to][0] % P + (long) dp[i][0] * dp[to][1] % P) % P; new0 = (int) ((long) dp[i][0] * dp[to][0] % P); // skip new1 += (int) ((long) dp[i][1] * dp[to][1] % P); new1 %= P; new0 += (int) ((long) dp[i][0] * dp[to][1] % P); new0 %= P; dp[i][0] = new0; dp[i][1] = new1; } } out.println(dp[0][1]); } B() 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 B(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
6e0117b454ab1ff9e5589c62cdab4601
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.util.*; import java.io.*; public class ApplemanAndTree { public static InputReader in; public static PrintWriter out; public static final int MOD = (int) (1e9 + 7); public static ArrayList<Integer>[] graph; public static boolean[] isBlack; public static long[] no, one; @SuppressWarnings("unchecked") public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); no = new long[n]; one = new long[n]; isBlack = new boolean[n]; graph = new ArrayList[n]; for(int i = 0; i < n; i++) graph[i] = new ArrayList<Integer>(); Arrays.fill(no, 1); for(int u = 1; u < n; u++) { int v = in.nextInt(); graph[u].add(v); graph[v].add(u); } for(int i = 0; i < n; i++) isBlack[i] = (in.nextInt() == 1); DFS(0, -1); out.println(one[0]); out.close(); } public static void DFS(int curr, int par) { for(Integer next : graph[curr]) { if(next == par) continue; DFS(next, curr); one[curr] = (one[curr]*no[next])%MOD; one[curr] += (no[curr]*one[next])%MOD; no[curr] = (no[curr]*no[next])%MOD; } if(isBlack[curr]) one[curr] = no[curr]; else no[curr] += one[curr]; no[curr] %= MOD; one[curr] %= MOD; } static class Node implements Comparable<Node> { int next; long dist; public Node(int u, int v) { this.next = u; this.dist = v; } public void print() { out.println(next + " " + dist + " "); } public int compareTo(Node n) { return Integer.compare(-this.next, -n.next); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
2b6260d7e861bd5288532596ab10fc60
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
/** * DA-IICT * Author : Savaliya Sagar */ import java.io.*; import java.math.*; import java.util.*; public class B461 { InputStream is; PrintWriter out; int n; int mod = (int) (1e9+7); ArrayList<Integer> g[]; int color[]; //0>>white 1>>for black long dp[][]; int ans = 1; long old[] = new long[2]; void solve() { n = ni(); g = new ArrayList[n]; dp = new long[n][2]; for(int i=0;i<n;i++) g[i] = new ArrayList<>(); for(int i=0;i<n-1;i++){ int u = ni(); g[u].add(i+1); g[i+1].add(u); } color = na(n); dfs(0,-1); out.println(dp[0][1]); } void dfs(int u,int p){ dp[u][1] = color[u]; dp[u][0] = 1-color[u]; for(int k:g[u]){ if(k==p) continue; dfs(k,u); old[0] = dp[u][0]; old[1] = dp[u][1]; //if k is not in subtree of u dp[u][0] = mul(old[0],dp[k][1]); dp[u][1] = mul(old[1],dp[k][1]); //if k is in subtree of u dp[u][0] = add(dp[u][0],mul(old[0],dp[k][0])); dp[u][1] = add(dp[u][1],add(mul(old[1],dp[k][0]),mul(old[0],dp[k][1]))); } } long mul(long a,long b){ return (a*b)%mod; } long add(long a,long b){ long ret = a+b; if(ret>=mod) ret -= mod; return ret; } void run() throws Exception { String INPUT = "/media/sagar407/D/java workspace/11Input_output/input.txt"; is = oj ? System.in : new FileInputStream(INPUT); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { new B461().run(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); } 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 (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
7911c4e2d43ceb9c94f5c2df9321e90d
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { private static class Node{ public List<Node> childs=new ArrayList<>(); public int color=0; public long whiteNum=0; public long blackNum=0; } public static void dfs(Node node){ long mod=1000000007; for (Node child : node.childs) { dfs(child); long old0=node.whiteNum, old1=node.blackNum; node.whiteNum=old0*(child.whiteNum+child.blackNum)%mod; node.blackNum=(old1*(child.whiteNum+child.blackNum)+old0*child.blackNum)%mod; } } public static void main(String[] args) { Scanner scanner =new Scanner(System.in); int n=scanner.nextInt(); Node[] vertex=new Node[n]; for (int i = 0; i < n; i++) { vertex[i]=new Node(); } for (int i = 0; i < n - 1; i++) { int p=scanner.nextInt(); vertex[p].childs.add(vertex[i+1]); } for (int i = 0; i < n; i++) { vertex[i].color=scanner.nextInt(); vertex[i].blackNum=vertex[i].color; vertex[i].whiteNum=vertex[i].color^1; } dfs(vertex[0]); System.out.println(vertex[0].blackNum); } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
830d1314e1b5ec2a3dcc1f443103b0c9
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { static class node { int color; List<node> childs; long blackNum = 0; long whiteNum = 0; node(int color) { this.color = color; childs = new ArrayList<>(); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = Integer.valueOf(in.nextLine()); String[] nodes = in.nextLine().split(" ");//n-1 String[] colors = in.nextLine().split(" ");//n node[] tree = new node[n]; for (int i = 0; i < colors.length; i++) { tree[i] = new node(Integer.valueOf(colors[i])); if (Integer.valueOf(colors[i]) == 1) { tree[i].blackNum = 1; } else { tree[i].whiteNum= 1; } } for (int i = 0; i < nodes.length; i++) { tree[Integer.valueOf(nodes[i])].childs.add(tree[i + 1]); } getNum(tree[0]); System.out.println(tree[0].blackNum); } } static void getNum(node node) { for (node child : node.childs) { getNum(child); long bn = node.blackNum; long wn = node.whiteNum; node.blackNum = ((bn * child.blackNum) % 1000000007 + (bn * child.whiteNum)% 1000000007 + (wn * child.blackNum)% 1000000007)% 1000000007; node.whiteNum = ((wn * child.whiteNum)% 1000000007 + (wn * child.blackNum)% 1000000007)% 1000000007; } } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
b7e5b3d31d94e9e66a13014d562a9b9e
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
/*See this : https://abitofcs.blogspot.com/2014/12/dynamic-programming-on-tree-forming-up.html */ import java.util.*; import java.io.*; public class lp1{ static PrintWriter out = new PrintWriter(System.out); static int MOD = 1000000007; static LinkedList<Integer> l[]; static long dp[][]; static int[] col; static void dfs(int u,int p){ dp[u][0] = 1 - col[u]; dp[u][1] = col[u]; long zero, one; for(Integer v : l[u]){ if(v==p) continue; dfs(v,u); zero = dp[u][0]; one = dp[u][1]; dp[u][0] = 0; dp[u][1] = 0; dp[u][0] = zero * dp[v][1]; dp[u][0] %= MOD; dp[u][1] = one * dp[v][1]; dp[u][1] %= MOD; dp[u][0] += zero * dp[v][0]; dp[u][0] %= MOD; dp[u][1] += one * dp[v][0] + zero * dp[v][1]; dp[u][1] %= MOD; } } public static void main(String[] args){ int n = ni(); l = new LinkedList[n]; dp = new long[n][2]; col = new int[n]; for(int i=0;i<n;i++) l[i] = new LinkedList(); for(int i=0;i<(n-1);i++) { int p = ni(); l[i+1].add(p); l[p].add(i+1); } for(int i=0;i<n;i++) col[i] = ni(); dfs(0,-1); pn(dp[0][1]); out.flush(); } static int BIT[]; static void add(int index,int val) { while(index<BIT.length) { BIT[index] = BIT[index]+val; index = index + (index&(-index)); } } static int get_sum(int index) { int sum=0; while(index>0) { sum = sum+BIT[index]; index = index- (index&(-index)); } return sum; } static void dfs(LinkedList<Integer> l[],int s,int p) { for(Integer I : l[s]) if(I!=p) dfs(l,I,s); } static int[] ai(int n) // it will give in array of size n { int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = ni(); return a; } static long[] al(int n) // it will give in array of size n { long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = nl(); return a; } static void p(Object o) { out.print(o); } static void pn(Object o) { out.println(o); } static int abs(int x) { return x>0 ? x : -x; } static long gcd(long a,long b) { if(b%a==0) return a; return gcd(b%a,a); } static void subtract_1(char s[]) // it will subtract 1 from the given number. number should be positive { if(s[0]=='0') // number is zero return; int n = s.length,i=n-1; while(s[i]=='0') i--; s[i] = (char)((int)(s[i]-'0') + 47); for(int j=i+1;j<n;j++) s[j]='9'; } static long pow(long a,long b,long md) { long ans=1; while(b>0) { if(b%2==1) ans = (ans*a)%md; a = (a*a)%md; b = b/2; } return ans; } static long min(long a,long b){ return a<b ? a : b; } static long max(long a,long b){ return a>b ? a : b; } static boolean pal(String s) { int n = s.length(),i1=0,i2=n-1; while(i1<i2) { if(s.charAt(i1)!=s.charAt(i2)) return false; i1++; i2--; } return true; } static String rev(String r) { String s = ""; int i= r.length()-1; while(i>=0) { s=s+r.charAt(i); i--; } return s; } static FastReader sc=new FastReader(); static int ni(){ int x = sc.nextInt(); return(x); } static long nl(){ long x = sc.nextLong(); return(x); } static String n(){ String str = sc.next(); return(str); } static String ns(){ String str = sc.nextLine(); return(str); } static double nd(){ double d = sc.nextDouble(); return(d); } 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
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
e9cef3f848c7e874a1d6e3886e809007
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.io.*; import java.util.*; public class Main{ static final int mod = 1000000007; static long[][] chart; public static void main(String[] args){ Scan scan = new Scan(); int n = scan.nextInt(); ArrayList<Integer>[] list = new ArrayList[n]; for(int i=0;i<n;i++) list[i] = new ArrayList<Integer>(); boolean[] black = new boolean[n]; for(int i=1;i<n;i++){ int v = scan.nextInt(); list[i].add(v); list[v].add(i); } for(int i=0;i<n;i++) black[i] = (scan.nextInt() == 1); chart = new long[n][2]; long result = walk(0, list, black, -1); System.out.println(result); } static long walk(int root, ArrayList<Integer>[] list, boolean[] black, int parent){ chart[root][0] = 1; chart[root][1] = 0; for(Integer in : list[root]){ int next = in; if(parent == next) continue; walk(next, list, black, root); chart[root][1] *= chart[next][0]; chart[root][1] += chart[root][0] * chart[next][1]; chart[root][0] *= chart[next][0]; chart[root][0] %= mod; chart[root][1] %= mod; } if(black[root]){ chart[root][1] = chart[root][0]; }else{ chart[root][0] += chart[root][1]; } chart[root][0] %= mod; chart[root][1] %= mod; return chart[root][1]; } } class Scan implements Iterator<String>{ BufferedReader buffer; StringTokenizer tok; Scan(){ buffer = new BufferedReader(new InputStreamReader(System.in)); } @Override public boolean hasNext(){ while(tok == null || !tok.hasMoreElements()){ try{ tok = new StringTokenizer(buffer.readLine()); }catch(Exception e){ return false; } } return true; } @Override public String next(){ if(hasNext()) return tok.nextToken(); return null; } @Override public void remove(){ throw new UnsupportedOperationException(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } String nextLine(){ if(hasNext()) return tok.nextToken("\n"); return null; } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
2207cc800888348b47e6890e80f59466
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
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 = {-1, 1, 0, 0}; int[] dy = {0, 0, -1, 1}; int n; List<List<Integer>> graph; int[] black; long[][] dp; void solve() throws IOException { n = nextInt(); graph = new ArrayList<>(); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } for (int i = 0; i < n - 1; i++) { int v = i + 1; int u = nextInt(); graph.get(v).add(u); graph.get(u).add(v); } black = nextIntArr(n); dp = new long[n][2]; dfs(0, -1); out(dp[0][1]); } void dfs(int cur, int parent) { long res0 = 1 - black[cur]; long res1 = black[cur]; for (int nxt : graph.get(cur)) { if (nxt == parent) { continue; } long prevRes0 = res0; long prevRes1 = res1; res0 = 0; res1 = 0; dfs(nxt, cur); res0 += prevRes0 * dp[nxt][1]; res0 %= MOD; res1 += prevRes1 * dp[nxt][1]; res1 %= MOD; res1 += prevRes0 * dp[nxt][1]; res1 %= MOD; res1 += prevRes1 * dp[nxt][0]; res1 %= MOD; res0 += prevRes0 * dp[nxt][0]; res0 %= MOD; } dp[cur][0] = res0; dp[cur][1] = res1; } 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; } } int gcd(int a, int b) { while(a != 0 && b != 0) { int 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
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
2b1017e207d9bfed03fd3921e287cf65
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); new Main().run(in, out); out.close(); } public static int mod = 1_000_000_007; long[][] dp; List<Integer>[] adj; int[] x; void run(FastScanner in, PrintWriter out) { int n = in.nextInt(); adj = new List[n]; for (int i = 0; i < n; i++) adj[i] = new ArrayList<>(); for (int v = 1; v < n; v++) { int u = in.nextInt(); adj[u].add(v); adj[v].add(u); } x = new int[n]; for (int i = 0; i < n; i++) x[i] = in.nextInt(); // dp[i][0] = ways to go from node i with 0 black nodes // dp[i][1] = ways to go from node i with 1 black node dp = new long[n][2]; go(0, -1); out.println(dp[0][1]); } void go(int u, int p) { dp[u][0] = 1; dp[u][1] = 0; // ways to have 0 black nodes up to u -> // no black nodes up to child1 * no black nodes up to child2 * ... // + ways to have 1 black node up to u (and cut the edge above u) // ways to have 1 black node up to u // = ways to have 1 black node from child1 * no black node from child2 * ... // + ways to have 0 black nodes from child1 * one black node from child2 * ... // = dp[v1][1]*dp[v2][0]*dp[v3][0]*... // + dp[v1][0]*dp[v2][1]*dp[v3][0]*... // + dp[v1][0]*dp[v2][0]*dp[v3][1]*... for (int v : adj[u]) { if (v == p) continue; go(v, u); dp[u][1] = (dp[u][1] * dp[v][0]); dp[u][1] = (dp[u][1] + dp[v][1] * dp[u][0]) % mod; dp[u][0] = (dp[u][0] * dp[v][0]) % mod; } if (x[u] == 1) { // black node dp[u][1] = dp[u][0]; // the one black node we propagate will be itself } else { // number of ways to prop 0 node increases by cutting parent edge dp[u][0] = (dp[u][0] + dp[u][1]) % mod; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } 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()); } } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
fbf51f992391a80dc1bd4235a3f1cf8c
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.List; import java.math.BigInteger; import java.io.OutputStream; import java.util.Iterator; import java.io.PrintWriter; import java.io.Writer; import java.io.IOException; import java.util.Arrays; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.Comparator; /** * 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { Graph graph; long[][] dp; int[] X; int MOD=1_000_000_007; public void solve(int testNumber, InputReader in, OutputWriter out) { int n=in.readInt(); int[] parent= IOUtils.readIntArray(in, n - 1); graph= Graph.createTree(parent); dp=new long[n][2]; ArrayUtils.fill(dp, -1); X=IOUtils.readIntArray(in, n); out.printLine(dp(0, 1)); //for (int i=0; i<n; i++) out.printLine(i, dp(i, 0), dp(i, 1)); } long dp(int u, int black) { if (dp[u][black]!=-1) return dp[u][black]; long ret; if (X[u]==0) { if (black==0) { ret = 1; for (int i = graph.firstOutbound(u); i != -1; i = graph.nextOutbound(i)) { int v = graph.destination(i); ret = ret * (dp(v, 0) + dp(v, 1)) % MOD; } } else { long prod = 1; ret=0; for (int i = graph.firstOutbound(u); i != -1; i = graph.nextOutbound(i)) { int v = graph.destination(i); prod = prod * (dp(v, 0) + dp(v, 1)) % MOD; } for (int i = graph.firstOutbound(u); i != -1; i = graph.nextOutbound(i)) { int v = graph.destination(i); ret=(ret+prod* IntegerUtils.reverse((dp(v, 0) + dp(v, 1)) % MOD, MOD)%MOD*dp(v, 1)%MOD)%MOD; } } } else if (black==0) ret=0; else { ret = 1; for (int i = graph.firstOutbound(u); i != -1; i = graph.nextOutbound(i)) { int v = graph.destination(i); ret = ret * (dp(v, 0) + dp(v, 1)) % MOD; } } return dp[u][black]=ret; } } class Graph { public static final int REMOVED_BIT = 0; protected int vertexCount; protected int edgeCount; private int[] firstOutbound; private int[] firstInbound; private Edge[] edges; private int[] nextInbound; private int[] nextOutbound; private int[] from; private int[] to; private long[] weight; public long[] capacity; private int[] reverseEdge; private int[] flags; public Graph(int vertexCount, int edgeCapacity) { this.vertexCount = vertexCount; firstOutbound = new int[vertexCount]; Arrays.fill(firstOutbound, -1); from = new int[edgeCapacity]; to = new int[edgeCapacity]; nextOutbound = new int[edgeCapacity]; flags = new int[edgeCapacity]; } public static Graph createTree(int[] parent) { Graph graph = new Graph(parent.length + 1, parent.length); for (int i = 0; i < parent.length; i++) graph.addSimpleEdge(parent[i], i + 1); return graph; } public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) { ensureEdgeCapacity(edgeCount + 1); if (firstOutbound[fromID] != -1) nextOutbound[edgeCount] = firstOutbound[fromID]; else nextOutbound[edgeCount] = -1; firstOutbound[fromID] = edgeCount; if (firstInbound != null) { if (firstInbound[toID] != -1) nextInbound[edgeCount] = firstInbound[toID]; else nextInbound[edgeCount] = -1; firstInbound[toID] = edgeCount; } this.from[edgeCount] = fromID; this.to[edgeCount] = toID; if (capacity != 0) { if (this.capacity == null) this.capacity = new long[from.length]; this.capacity[edgeCount] = capacity; } if (weight != 0) { if (this.weight == null) this.weight = new long[from.length]; this.weight[edgeCount] = weight; } if (reverseEdge != -1) { if (this.reverseEdge == null) { this.reverseEdge = new int[from.length]; Arrays.fill(this.reverseEdge, 0, edgeCount, -1); } this.reverseEdge[edgeCount] = reverseEdge; } if (edges != null) edges[edgeCount] = createEdge(edgeCount); return edgeCount++; } protected final GraphEdge createEdge(int id) { return new GraphEdge(id); } public final int addFlowWeightedEdge(int from, int to, long weight, long capacity) { if (capacity == 0) { return addEdge(from, to, weight, 0, -1); } else { int lastEdgeCount = edgeCount; addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge()); return addEdge(from, to, weight, capacity, lastEdgeCount); } } protected int entriesPerEdge() { return 1; } public final int addWeightedEdge(int from, int to, long weight) { return addFlowWeightedEdge(from, to, weight, 0); } public final int addSimpleEdge(int from, int to) { return addWeightedEdge(from, to, 0); } public final int firstOutbound(int vertex) { int id = firstOutbound[vertex]; while (id != -1 && isRemoved(id)) id = nextOutbound[id]; return id; } public final int nextOutbound(int id) { id = nextOutbound[id]; while (id != -1 && isRemoved(id)) id = nextOutbound[id]; return id; } public final int destination(int id) { return to[id]; } public final boolean flag(int id, int bit) { return (flags[id] >> bit & 1) != 0; } public final boolean isRemoved(int id) { return flag(id, REMOVED_BIT); } protected void ensureEdgeCapacity(int size) { if (from.length < size) { int newSize = Math.max(size, 2 * from.length); if (edges != null) edges = resize(edges, newSize); from = resize(from, newSize); to = resize(to, newSize); nextOutbound = resize(nextOutbound, newSize); if (nextInbound != null) nextInbound = resize(nextInbound, newSize); if (weight != null) weight = resize(weight, newSize); if (capacity != null) capacity = resize(capacity, newSize); if (reverseEdge != null) reverseEdge = resize(reverseEdge, newSize); flags = resize(flags, newSize); } } protected final int[] resize(int[] array, int size) { int[] newArray = new int[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private long[] resize(long[] array, int size) { long[] newArray = new long[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private Edge[] resize(Edge[] array, int size) { Edge[] newArray = new Edge[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } protected class GraphEdge implements Edge { protected int id; protected GraphEdge(int id) { this.id = id; } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } class ArrayUtils { public static void fill(long[][] array, long value) { for (long[] row : array) Arrays.fill(row, value); } } class IntegerUtils { public static long power(long base, long exponent, long mod) { if (base >= mod) base %= mod; if (exponent == 0) return 1 % mod; long result = power(base, exponent >> 1, mod); result = result * result % mod; if ((exponent & 1) != 0) result = result * base % mod; return result; } public static long reverse(long number, long module) { return power(number, module - 2, module); } } interface Edge { }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
e9b2e49fe71622815de655090302fe0f
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
/* * Code Author: Akshay Miterani * DA-IICT */ import java.io.*; import java.math.*; import java.text.*; import java.util.*; public class A { static double eps=(double)1e-15; static long mod=(int)1e9+7; static long hai[]; static long nahi[]; static long ans=1; static boolean black[]; static ArrayList<ArrayList<Integer>> arr; public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException{ InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); //----------My Code---------- int n=in.nextInt(); arr=new ArrayList<ArrayList<Integer>>(); for(int i=0;i<n;i++){ arr.add(new ArrayList<Integer>()); } for(int i=0;i<n-1;i++){ int u=in.nextInt(); int v=i+1; arr.get(u).add(v); arr.get(v).add(u); } hai=new long[n]; nahi=new long[n]; black=new boolean[n]; for(int i=0;i<n;i++){ if(in.nextInt()==1) black[i]=true; } dfs(0,-1); out.println(hai[0]); out.close(); //---------------The End------------------ } static void dfs(int u,int p){ nahi[u]=1; hai[u]=0; for(int x:arr.get(u)){ if(x==p) continue; dfs(x,u); hai[u]=hai[u]*nahi[x]+nahi[u]*hai[x]; hai[u]%=mod; nahi[u]=nahi[u]*nahi[x]; nahi[u]%=mod; } if(black[u]){ hai[u]=nahi[u]; } else{ nahi[u]+=hai[u]; nahi[u]%=mod; } } static class Pair implements Comparable<Pair> { int u; int v; BigInteger bi; 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) { return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } 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; } 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; } 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 nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
f6d911292d89330db26c51d375614198
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class utkarsh { InputStream is; PrintWriter out; long maxl = (long) 4e18, mod = (long)1e9 + 7L; ArrayList<Integer> a[]; int c[]; long dp[][]; void dfs(int s){ dp[s][c[s]] = 1; for(int x : a[s]){ //System.out.println(x); dfs(x); long u, v; u = dp[s][1] * dp[x][0]; u %= mod; u += dp[s][1] * dp[x][1]; u %= mod; u += dp[s][0] * dp[x][1]; u %= mod; v = dp[s][0] * dp[x][0]; v %= mod; v += dp[s][0] * dp[x][1]; v %= mod; dp[s][1] = u; dp[s][0] = v; } } void solve(){ //Enter code here utkarsh int i, n; n = ni(); a = new ArrayList[n]; for(i = 0; i < n; i++) a[i] = new ArrayList<>(); for(i = 0; i < n-1; i++) a[ni()].add(i+1); c = na(n); dp = new long[n][2]; dfs(0); out.println(dp[0][1]); } long modpow(long base, long exp, long modulus) { base %= modulus; long result = 1L; while (exp > 0) { if ((exp & 1)==1) result = (result * base) % modulus; base = (base * base) % modulus; exp >>= 1; } return result; } public static void main(String[] args) { new utkarsh().run(); } void run(){ is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte(){ if(ptr >= len){ ptr = 0; try{ len = is.read(input); }catch(IOException e){ throw new InputMismatchException(); } if(len <= 0){ return -1; } } return input[ptr++]; } boolean isSpaceChar(int c){ return !( c >= 33 && c <= 126 ); } int skip(){ int b = readByte(); while(b != -1 && isSpaceChar(b)){ b = readByte(); } return b; } char nc(){ return (char)skip(); } String ns(){ int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)){ sb.appendCodePoint(b); b=readByte(); } return sb.toString(); } int ni(){ int n = 0,b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')){ b = readByte(); } if(b == '-'){ minus = true; b = readByte(); } if(b == -1){ return -1; } while(b >= '0' && b <= '9'){ n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl(){ long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')){ b = readByte(); } if(b == '-'){ minus = true; b = readByte(); } while(b >= '0' && b <= '9'){ n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd(){ return Double.parseDouble(ns()); } float nf(){ return Float.parseFloat(ns()); } int[] na(int n){ int a[] = new int[n]; for(int i = 0; i < n; i++){ a[i] = ni(); } return a; } char[] ns(int n){ char c[] = new char[n]; int i,b = skip(); for(i = 0; i < n; i++){ if(isSpaceChar(b)){ break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
03b7a8f11d31581190cc2e3b1a069c33
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
/* * Author Ayub Subhaniya * Institute DA-IICT */ import java.io.*; import java.math.*; import java.util.*; @SuppressWarnings("unchecked") public class A { InputStream in; PrintWriter out; long mod=(long)1e9+7; ArrayList<Integer> g[]; int n; int c[]; long dp[][]; void solve() { n=ni(); c=new int[n]; g=new ArrayList[n]; for (int i=0;i<n;i++) g[i]=new ArrayList<>(); for (int i=1;i<=n-1;i++) { int u=ni(); g[u].add(i); g[i].add(u); } for (int i=0;i<n;i++) c[i]=ni(); dp=new long[n][2]; dfs(0,0); out.println(dp[0][0]); } /* * State * 1-> top part containing 1 black * 2-> top part containing 0 black */ void dfs(int u,int p) { for (int v:g[u]) { if (v!=p) dfs(v,u); } dp[u][1]=1; for (int v:g[u]) { if (v!=p) { dp[u][0]=mul(dp[u][0],dp[v][1]); dp[u][0]=add(dp[u][0],mul(dp[v][0],dp[u][1])); dp[u][1]=mul(dp[u][1],dp[v][1]); } } if (c[u]==1) dp[u][0]=dp[u][1]; else dp[u][1]=add(dp[u][1],dp[u][0]); } long add(long a, long b) { long x = (a + b); while (x >= mod) x -= mod; return x; } long sub(long a, long b) { long x = (a - b); while (x < 0) x += mod; return x; } long mul(long a, long b) { a %= mod; b %= mod; long x = (a * b); return x % mod; } void run() throws Exception { String INPUT = "C:/Users/ayubs/Desktop/input.txt"; in = oj ? System.in : new FileInputStream(INPUT); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new A().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = in.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean inSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && inSpaceChar(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 (!(inSpaceChar(b))) { // when nextLine, (inSpaceChar(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 && !(inSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 8
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
205f72c51a49709d04b226e78ec81785
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.io.*; import java.util.*; public class Solution { private static Reader in; private static PrintWriter out; private static int[] eadj, eprev, elast, par; private static int eidx; public static int mod = 1000000007; private static void addEdge (int a, int b) { eadj[eidx] = b; eprev[eidx] = elast[a]; elast[a] = eidx++; eadj[eidx] = a; eprev[eidx] = elast[b]; elast[b] = eidx++; } public static void main(String[] args) throws IOException { in = new Reader(); out = new PrintWriter(System.out, true); int N = in.nextInt(); eadj = new int[2 * N]; eprev = new int[2 * N]; elast = new int[N]; par = new int[N]; eidx = 0; Arrays.fill (elast, -1); for (int i = 1; i < N; i++) { addEdge(i, in.nextInt()); } int[] col = new int[N]; for (int i = 0; i < N; i++) col[i] = in.nextInt(); int[] queue = new int[N]; int front = 0, back = 0; boolean[] vis = new boolean[N]; queue[back++] = 0; vis[0] = true; par[0] = -1; while (front < back) { int node = queue[front++]; for (int e = elast[node]; e != -1; e = eprev[e]) { if (vis[eadj[e]]) continue; par[eadj[e]] = node; vis[eadj[e]] = true; queue[back++] = eadj[e]; } } long[][] dp = new long[2][N]; for (int i = N - 1; i >= 0; i--) { int node = queue[i]; if (col[node] == 0) { long m = 1; for (int e = elast[node]; e != -1; e = eprev[e]) { if (eadj[e] == par[node]) continue; m = (m * (dp[0][eadj[e]] + dp[1][eadj[e]])) % mod; } dp[0][node] = m; } else { dp[0][node] = 0; } if (col[node] == 1) { long m = 1; for (int e = elast[node]; e != -1; e = eprev[e]) { if (eadj[e] == par[node]) continue; m = (m * (dp[0][eadj[e]] + dp[1][eadj[e]])) % mod; } dp[1][node] = m; } else { long prodall = 1; int idx = -1; boolean two = false; for (int e = elast[node]; e != -1; e = eprev[e]) { if (eadj[e] == par[node]) continue; if ((dp[0][eadj[e]] + dp[1][eadj[e]]) % mod == 0) { if (idx == -1) { idx = eadj[e]; } else { two = true; } } else { prodall = (prodall * (dp[0][eadj[e]] + dp[1][eadj[e]])) % mod; } } long m = 0; if (!two) { if (idx == -1) { for (int e = elast[node]; e != -1; e = eprev[e]) { if (eadj[e] == par[node]) continue; long a = prodall * inv(dp[0][eadj[e]] + dp[1][eadj[e]], mod) % mod; a = a * dp[1][eadj[e]] % mod; m = (m + a) % mod; } } else { m = prodall * dp[1][idx] % mod; } } dp[1][node] = m; } } out.println (dp[1][0]); out.close(); System.exit(0); } public static long inv (long N, long M) { long x = 0, lastx = 1, y = 1, lasty = 0, q, t, a = N, b = M; while (b != 0) { q = a / b; t = a % b; a = b; b = t; t = x; x = lastx - q * x; lastx = t; t = y; y = lasty - q * y; lasty = t; } return (lastx + M) % M; } 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[1024]; 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
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 6
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
b370525770e27aa1ae85e0aa10175dad
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.util.Arrays; import java.util.ArrayList; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Random; import java.util.HashMap; import java.util.List; import java.io.BufferedReader; import java.util.Map; import java.math.BigInteger; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * @author shu_mj @ http://shu-mj.com */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { Scanner in; PrintWriter out; public void solve(int testNumber, Scanner in, PrintWriter out) { this.in = in; this.out = out; run(); } void run() { int n = in.nextInt(); V[] vs = new V[n]; for (int i = 0; i < n; i++) { vs[i] = new V(); } for (int i = 0; i < n - 1; i++) { int p = in.nextInt(); vs[p].sons.add(vs[i + 1]); vs[i + 1].sons.add(vs[p]); } for (int i = 0; i < n; i++) { vs[i].color = (in.nextInt() == 1); } dfs(vs[0], null); out.println(vs[0].black); } final long M = (int) (1e9 + 7); private void dfs(V v, V fa) { long b = 0, w = 0; if (v.color) b = 1; else w = 1; for (V u : v.sons) if (u != fa) { dfs(u, v); long nw = 0, nb = 0; // connect nw += u.white * w; nw %= M; nb += u.white * b; nb %= M; nb += u.black * w; nb %= M; // disConnect nw += u.black * w; nw %= M; nb += u.black * b; nb %= M; b = nb; w = nw; } v.black = b; v.white = w; } class V { List<V> sons = new ArrayList<V>(); boolean color; long white; long black; } } class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } private void eat(String s) { st = new StringTokenizer(s); } public String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } public boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } public String next() { hasNext(); return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 6
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
438525b1eb269362d004fab3a47648ae
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.util.Arrays; import java.util.ArrayList; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Random; import java.util.HashMap; import java.util.List; import java.io.BufferedReader; import java.util.Map; import java.math.BigInteger; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * @author shu_mj @ http://shu-mj.com */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { Scanner in; PrintWriter out; public void solve(int testNumber, Scanner in, PrintWriter out) { this.in = in; this.out = out; run(); } void run() { int n = in.nextInt(); V[] vs = new V[n]; for (int i = 0; i < n; i++) { vs[i] = new V(); } for (int i = 0; i < n - 1; i++) { int p = in.nextInt(); vs[p].sons.add(vs[i + 1]); vs[i + 1].sons.add(vs[p]); } for (int i = 0; i < n; i++) { vs[i].color = (in.nextInt() == 1); } dfs(vs[0], null); out.println(vs[0].black); } final int M = (int) (1e9 + 7); private void dfs(V v, V fa) { for (V u : v.sons) if (u != fa) { dfs(u, v); } if (v.color) { v.black = 1; for (V u : v.sons) if (u != fa) { v.black = (int) ((long) v.black * (u.black + u.white) % M); } } else { v.white = 1; for (V u : v.sons) if (u != fa) { v.white = (int) ((long) v.white * (u.black + u.white) % M); } for (V u : v.sons) if (u != fa) { v.black += (int) ((long) v.white * inv(u.black + u.white) % M * u.black % M); v.black %= M; } v.black = (v.black % M + M) % M; } } private int inv(int i) { i %= M; return (int) Num.inv(i, M); } class V { List<V> sons = new ArrayList<V>(); boolean color; int white; int black; } } class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } private void eat(String s) { st = new StringTokenizer(s); } public String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } public boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } public String next() { hasNext(); return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } class Num { public static long inv(long a, long mod) { if (a == 1) return 1; return inv(mod % a, mod) * (mod - mod / a) % mod; } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 6
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
9b35cb988cd7b74debd59327a864b646
train_004.jsonl
1409061600
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k &lt; n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).
256 megabytes
import java.util.ArrayList; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import java.io.BufferedReader; import java.math.BigInteger; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * @author shu_mj @ http://shu-mj.com */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { Scanner in; PrintWriter out; public void solve(int testNumber, Scanner in, PrintWriter out) { this.in = in; this.out = out; run(); } void run() { int n = in.nextInt(); V[] vs = new V[n]; for (int i = 0; i < n; i++) { vs[i] = new V(); } for (int i = 0; i < n - 1; i++) { int p = in.nextInt(); vs[p].sons.add(vs[i + 1]); vs[i + 1].sons.add(vs[p]); } for (int i = 0; i < n; i++) { vs[i].color = (in.nextInt() == 1); } dfs(vs[0], null); out.println(vs[0].black); } final int M = (int) (1e9 + 7); private void dfs(V v, V fa) { for (V u : v.sons) if (u != fa) { dfs(u, v); } if (v.color) { v.black = 1; for (V u : v.sons) if (u != fa) { v.black = (int) ((long) v.black * (u.black + u.white) % M); } } else { v.white = 1; for (V u : v.sons) if (u != fa) { v.white = (int) ((long) v.white * (u.black + u.white) % M); } for (V u : v.sons) if (u != fa) { v.black += (int) ((long) v.white * inv(u.black + u.white) % M * u.black % M); v.black %= M; } v.black = (v.black % M + M) % M; } } private int inv(int i) { return BigInteger.valueOf(i).modInverse(BigInteger.valueOf(M)).intValue(); } class V { List<V> sons = new ArrayList<V>(); boolean color; int white; int black; } } class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } private void eat(String s) { st = new StringTokenizer(s); } public String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } public boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } public String next() { hasNext(); return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"]
2 seconds
["2", "1", "27"]
null
Java 6
standard input
[ "dp", "dfs and similar", "trees" ]
e571191fadf6b0b26bd2f16295f32077
The first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
2,000
Output a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).
standard output
PASSED
db54e5a2157150f8abba9d616cb2a695
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import javax.print.attribute.SupportedValuesAttribute; import java.io.*; import java.util.*; public class Problem1 { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(in, out); out.close(); } static class TaskB { public void solve(InputReader in, PrintWriter out) { int T = in.nextInt(); while(T-->0) { int n = in.nextInt(); HashMap<Integer, Integer> maxHeight = new HashMap<>(); ArrayList<Integer> xVals = new ArrayList<>(); int[][] points = new int[n][2]; for(int i = 0; i < n; i++) { int x = in.nextInt(); int y = in.nextInt(); points[i][0] = x; points[i][1] = y; if(!(maxHeight.containsKey(x))) { xVals.add(x); maxHeight.put(x, y); }else{ maxHeight.put(x, Math.max(maxHeight.get(x), y)); } } boolean good = true; for(int i = 0; i < n; i++) { for(int g = 0; g < n; g++) { if(i==g)continue; if(points[i][0]<points[g][0] && points[i][1]>points[g][1]) { good = false; break; } } if(!good)break; } if(good) { Collections.sort(xVals); int len = xVals.size(); int currentX = 0; int currentY = 0; String direction = ""; boolean ok = false; for(int i = 0; i < len; i++) { int theInt =xVals.get(i); while(theInt-currentX != 0) { if(theInt < currentX) { ok = true; break; } direction+="R"; currentX++; } while(maxHeight.get(theInt) - currentY!= 0) { if(maxHeight.get(theInt) < currentY) { ok = true; break; } direction+="U"; currentY++; } if(ok)break; } if(ok) { out.println("NO"); } else { out.println("YES"); out.println(direction); } }else{ out.println("NO"); } } } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public InputReader(InputStream inputStream) { this.reader = new BufferedReader( new InputStreamReader(inputStream)); } public String next() { while (!tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } 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; } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
f6ca817934d762d8817652dfd1863f2e
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Scanner; public class Main implements Runnable, AutoCloseable { Scanner in = new Scanner(new BufferedInputStream(System.in)); PrintStream out = new PrintStream(new BufferedOutputStream(System.out)); @Override public void run() { int t = in.nextInt(); // int t = 1; for (int i = 0; i < t; i++) { doOnce(); } } 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) { return Integer.compare(x + y, o.x + o.y); } public void to(StringBuilder sb, Point o) { if (this.x > o.x || this.y > o.y) { throw new IllegalArgumentException(); } for (int i = this.x; i < o.x; i++) { sb.append('R'); } for (int i = this.y; i < o.y; i++) { sb.append('U'); } } } private void doOnce() { int n = in.nextInt(); Point[] points = new Point[n + 1]; points[0] = new Point(0, 0); for (int i = 1; i <= n; i++) { points[i] = new Point(in.nextInt(), in.nextInt()); } Arrays.sort(points); StringBuilder sb = new StringBuilder(); try { for (int i = 1; i <= n; i++) { points[i - 1].to(sb, points[i]); } out.println("YES"); out.println(sb); } catch (IllegalArgumentException e) { out.println("NO"); } } // if (test(n, m, k)) { // out.println("YES"); // } else { // out.println("NO"); // } public static void main(String[] args) { try (Main main = new Main()) { main.run(); } } @Override public void close() { out.close(); } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
71d55b893142be677637e60b3644d4d2
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
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.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author EigenFunk */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); BCollectingPackages solver = new BCollectingPackages(); solver.solve(1, in, out); out.close(); } static class BCollectingPackages { public void solve(int testNumber, FastScanner in, PrintWriter out) { int t = in.nextInt(); for (int i = 0; i < t; i++) { int n = in.nextInt(); Pair[] p = new Pair[n]; for (int j = 0; j < n; j++) { p[j] = new Pair(in.nextInt(), in.nextInt()); } Arrays.sort(p); StringBuilder res = new StringBuilder(); int currX = 0; int currY = 0; boolean d = true; for (int j = 0; j < p.length; j++) { if (p[j].x < currX) { d = false; break; } else { res.append("R".repeat(p[j].x - currX)); currX = p[j].x; } if (p[j].y < currY) { d = false; break; } else { res.append("U".repeat(p[j].y - currY)); currY = p[j].y; } } if (d) { out.println("YES"); out.println(res.toString()); } else { out.println("NO"); } } } class Pair implements Comparable<Pair> { public final int x; public final int y; public Pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(Pair o) { if (this.x == o.x) { return this.y - o.y; } else { return this.x - o.x; } } public String toString() { return "Pair{" + "x=" + x + ", y=" + y + '}'; } } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public FastScanner(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
405e759e2c462e8d1f4a8d53ce73e9c8
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { FastReader scan = new FastReader(); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("marathon.out"))); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)),true); Task solver = new Task(); int t = scan.nextInt(); //int t = 1; for(int i = 1; i <= t; i++) solver.solve(i, scan, out); out.close(); } static class Task { public void solve(int testNumber, FastReader sc, PrintWriter pw) { int n = sc.nextInt(); tup[] arr = new tup[n]; for (int i = 0; i < n; i++) { arr[i] = new tup(sc.nextInt(), sc.nextInt()); } Arrays.sort(arr); StringBuilder sb = new StringBuilder(); int lastb = 0; int lasta = 0; for (int i = 0; i < n - 1; i++) { if(arr[i].b<lastb){ pw.println("NO"); return; } if (arr[i].a<arr[i+1].a){ for(int j=lasta;j<arr[i].a;j++){ sb.append("R"); lasta = arr[i].a; } for(int j=lastb;j<arr[i].b;j++){ sb.append("U"); lastb = arr[i].b; } } } if(arr[n-1].b<lastb){ pw.println("NO"); return; } for(int j=lasta;j<arr[n-1].a;j++){ sb.append("R"); } for(int j=lastb;j<arr[n-1].b;j++){ sb.append("U"); } pw.println("YES\n"+sb); } } static class tup implements Comparable<tup>{ int a, b; tup(int a, int b){ this.a=a; this.b=b; } @Override public int compareTo(tup o) { return a!=o.a?Integer.compare(a,o.a):Integer.compare(b,o.b); } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
f582c124f196160794b1be87f9fd24ef
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import javax.swing.plaf.synth.SynthSeparatorUI; public class temp1 { static long sx = 0, sy = 0, t = 0; static int[] ele = new int[(int) 1e6]; static int[] cnt = new int[(int) 1e6]; public static void main(String[] args) throws IOException { Reader scn = new Reader(); int t = scn.nextInt(); z: while (t-- != 0) { int n = scn.nextInt(); ArrayList<pair> p = new ArrayList<>(); while (n-- != 0) { p.add(new pair(scn.nextInt(), scn.nextInt())); } Collections.sort(p); StringBuilder sb = new StringBuilder(); int mx = 0, my = 0; for (pair rp : p) { if (rp.y < my) { System.out.println("NO"); continue z; } for (int i = 0; i < rp.x - mx; i++) sb.append("R"); for (int i = 0; i < rp.y - my; i++) sb.append("U"); mx = rp.x; my = rp.y; } System.out.println("YES"); System.out.println(sb); } } // _________________________TEMPLATE_____________________________________________________________ // private static int gcd(int a, int b) { // if(a== 0) // return b; // // return gcd(b%a,a); // } // static class comp implements Comparator<pair> { // // @Override // public int compare(pair o1, pair o2) { // // return (int) (o1.y - o1.y); // } // // } private static class pair implements Comparable<pair> { int x, y; pair(int a, int b) { x = a; y = b; } @Override public int compareTo(pair o) { if (this.x != o.x) return this.x - o.x; else return this.y - o.y; } } 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[100000 + 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; } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
68990a016b0c5db22aef9f3c8165f42f
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.io.*; import java.util.*; /* * To execute Java, please define "static void main" on a class * named Solution. * * If you need more classes, simply define them inline. */ public class CollectingPackages { private static String getPath(int x1, int y1,int x2,int y2){ StringBuilder sb = new StringBuilder(); for(int i=0;i<x2-x1;i++) sb.append("R"); for(int i=0;i<y2-y1;i++) sb.append("U"); //System.out.println(" path " + sb.toString()); return sb.toString(); } public static void main(String[] args) { //System.out.println(getPath(0,0,0,2)); Scanner sc = new Scanner(System.in); int tests = sc.nextInt(); while(tests > 0){ int points = sc.nextInt(); PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->{ if(a[0] == b[0]) { return Integer.compare(a[1],b[1]); } return Integer.compare(a[0],b[0]); }); while(points > 0) { pq.offer(new int[]{sc.nextInt(), sc.nextInt()}); points--; } //int prevX = 0; //int prevY = 0; int[] prev = new int[]{0,0}; StringBuilder path = new StringBuilder(); int[] current = pq.poll(); path.append(getPath(prev[0],prev[1],current[0],current[1])); if(pq.isEmpty()){ System.out.println("YES"); System.out.println(path); } prev = new int[]{current[0],current[1]}; while(!pq.isEmpty()){ current = pq.poll(); //System.out.println("Processing " + Arrays.toString(current) + " prev " + prevX + " " + prevY); if(current[1] <prev[1]){ System.out.println("NO"); break; } else { path.append(getPath(prev[0],prev[1],current[0],current[1])); prev = new int[]{current[0],current[1]}; //System.out.println(Arrays.toString(current)); if(pq.isEmpty()){ System.out.println("YES"); System.out.println(path); } } } tests--; } } } /* Your previous Plain Text content is preserved below: Idea use a priority queue sort based on X if X is same sort by Y this will make sure from 00 to 22 RRUU will be selected , raher than UURR or RURU next observation is you can always reach first point from point 1 to n if you find something that is going down i mean Y is less that y seen so far, return NO lets see if it holds */
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
83aa4e1a7bc98f2cc98a83206f0449dd
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
// package cf615; import java.io.*; import java.util.*; public class Main{ static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public String next(){ try{ while(st==null||!st.hasMoreElements()){ st = new StringTokenizer(br.readLine()); } }catch(Exception e){ e.printStackTrace(); } return st.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public String nextLine(){ String s = ""; try{ s = br.readLine(); }catch(Exception e){ e.printStackTrace(); } return s; } } public static class Pair{ int x; int y; Pair(int x,int y){ this.x = x; this.y = y; } } public static void solve(int testNumber,FastReader in,PrintWriter out){ int n = in.nextInt(); int a[] = new int[n]; ArrayList<Pair> li = new ArrayList<>(); for(int i = 0; i < n; i++){ li.add(new Pair(in.nextInt(),in.nextInt())); } Collections.sort(li, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if(o1.x == o2.x){ return Integer.compare(o1.y,o2.y); } return Integer.compare(o1.x,o2.x); } }); for(int i = 1; i < n;i++){ int y1 = li.get(i).y; int y2 = li.get(i-1).y; if(y2>y1){ out.println("NO"); return; } } out.println("YES"); StringBuilder path=new StringBuilder(); int j=0,k=0; for (int i = 0; i < n; i++) { int x = li.get(i).x; int y = li.get(i).y; for(;j<x;j++){ path.append("R"); } for (;k<y;k++){ path.append("U"); } } out.println(path); } public static void main(String[] args){ FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); for(int i = 0; i < t;i++){ solve(i,in,out); } out.flush(); out.close(); } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
80064621e0bb42c552ccb0f25582abb3
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(System.out)); String str= br.readLine(); int t = Integer.parseInt(str); for(int h=0; h<t; h++) { int n= Integer.parseInt(br.readLine()); List<int[]> list= new ArrayList<>(); int nm[] = {0, 0}; for(int i=0; i<n; i++) { int nn[] = new int[2]; String s[]= br.readLine().split(" "); nn[0] = Integer.parseInt(s[0]); nn[1] = Integer.parseInt(s[1]); list.add(nn); } list.add(nm); Collections.sort(list, (o1, o2) -> { if(o1[0]==o2[0]) return Integer.compare(o1[1], o2[1]); else return Integer.compare(o1[0], o2[0]); }); boolean b= true; StringBuilder sb= new StringBuilder(); for(int i=1; i<n+1; i++) { if(list.get(i-1)[0]>list.get(i)[0] || list.get(i-1)[1]>list.get(i)[1]) { b=false; break; } for(int j=0; j<list.get(i)[0]-list.get(i-1)[0]; j++) sb.append('R'); for(int j=0; j<list.get(i)[1]-list.get(i-1)[1]; j++) sb.append('U'); } if(b) { System.out.println("YES"); System.out.println(sb.toString()); } else System.out.println("NO"); } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
1956875baa6041a0cc7eafdc3b2e6c9e
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class B_collectingPackages { public static void sorte(int arr[], int arr2[]) { int n = arr.length; for (int i = 1; i < n; ++i) { int key = arr[i]; int key2 = arr2[i]; int j = i - 1; while (j >= 0 && arr[j] > key || (j >= 0 && arr[j] == key && arr2[j] > key2)) { arr[j + 1] = arr[j]; arr2[j+1] = arr2[j]; j = j - 1; } // while (j >= 0 && arr[j] == key && arr2[j] > arr2[i]) { // arr[j+1] = arr[j]; // arr2[j+1] = arr2[j]; // j--; // } arr[j + 1] = key; arr2[j+1] = key2; } } public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(System.in); PrintWriter pw = new PrintWriter(System.out); int queries = sc.nextInt(); while (queries --> 0) { int n = sc.nextInt(); int[][] arr = new int[n][2]; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) { arr[i][j] = sc.nextInt(); } } int[] arr1 = new int[n]; int[] arr2 = new int[n]; for (int i = 0; i < arr1.length; i++) { arr1[i] = arr[i][0]; arr2[i] = arr[i][1]; } sorte(arr1, arr2); for (int i = 0; i < arr.length; i++) { arr[i][0] = arr1[i]; arr[i][1] = arr2[i]; } //pw.println(Arrays.deepToString(arr)); boolean can = true; for (int i = 0; i < n-1; i++) { if (arr[i+1][1]-arr[i][1] < 0) { can = false; break; } } if (!can) { pw.println("NO"); } else { pw.println("YES"); StringBuilder str = new StringBuilder(""); for (int j = 0; j < arr[0][0]; j++) { str.append("R"); } for (int j = 0; j < arr[0][1]; j++) { str.append("U"); } for (int i = 0; i < n-1; i++) { for (int j = 0; j < arr[i+1][0]-arr[i][0]; j++) { str.append("R"); } for (int j = 0; j < arr[i+1][1]-arr[i][1]; j++) { str.append("U"); } //pw.println(str.toString()); } pw.println(str.toString()); } } pw.close(); } static class FastScanner { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastScanner(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int peek() { if (numChars == -1) { return -1; } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) { return -1; } } return buf[curChar]; } public int 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 String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) { s = readLine0(); } return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) { return readLine(); } else { return readLine0(); } } public BigInteger readBigInteger() { try { return new BigInteger(nextString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } 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 boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) { read(); } return value == -1; } public String next() { return nextString(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] nextIntArray(int n){ int[] array=new int[n]; for(int i=0;i<n;++i)array[i]=nextInt(); return array; } public int[] nextSortedIntArray(int n){ int array[]=nextIntArray(n); PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for(int i = 0; i < n; i++){ pq.add(array[i]); } int[] out = new int[n]; for(int i = 0; i < n; i++){ out[i] = pq.poll(); } return out; } public int[] nextSumIntArray(int n){ int[] array=new int[n]; array[0]=nextInt(); for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt(); return array; } public ArrayList<Integer>[] nextGraph(int n, int m){ ArrayList<Integer>[] adj = new ArrayList[n]; for(int i = 0; i < n; i++){ adj[i] = new ArrayList<Integer>(); } for(int i = 0; i < m; i++){ int u = nextInt(); int v = nextInt(); u--; v--; adj[u].add(v); adj[v].add(u); } return adj; } public ArrayList<Integer>[] nextTree(int n){ return nextGraph(n, n-1); } public long[] nextLongArray(int n){ long[] array=new long[n]; for(int i=0;i<n;++i)array[i]=nextLong(); return array; } public long[] nextSumLongArray(int n){ long[] array=new long[n]; array[0]=nextInt(); for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt(); return array; } public long[] nextSortedLongArray(int n){ long array[]=nextLongArray(n); Arrays.sort(array); return array; } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
984c527a2c9d9c22fbb650e3d27d503c
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader reader; static StringTokenizer stoken; static PrintWriter out; static int ni() throws Exception { return Integer.parseInt(ns()); } static long nl() throws Exception { return Long.parseLong(ns()); } static double nd() throws Exception { return Double.parseDouble(ns()); } static String ns() throws Exception { if (stoken == null || !stoken.hasMoreTokens()) stoken = new StringTokenizer(reader.readLine()); return stoken.nextToken(); } public static void main(String[] args) throws Exception { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true); int Q = ni(); for (int q = 0; q < Q; q++) { int n = ni(); Point[] pp = new Point[n]; for (int i = 0; i < n; i++) { pp[i] = new Point(ni(), ni()); } Arrays.sort(pp); String s = ""; boolean pos = true; int cx = 0, cy = 0; for (int i = 0; i < n; i++) { int nx = pp[i].x, ny = pp[i].y; if (nx < cx || ny < cy) { pos = false; break; } for (int j = 0; j < nx - cx; j++) s += "R"; for (int j = 0; j < ny - cy; j++) s += "U"; cx = nx; cy = ny; } if (pos) { out.println("YES"); out.println(s); } else out.println("NO"); } } static class Point implements Comparable<Point> { public int x; public int y; Point() {} Point(int a, int b) {x = a; y = b;} public int compareTo(Point other) { if (x == other.x) return y - other.y; return x - other.x; } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
a852b9cf3239c1bfb3f078139a2e7fe8
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { class Pair { int h, w; Pair(int h, int w) { this.h = h; this.w = w; } } public void solve() throws Exception { int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); Pair[] p = new Pair[n]; for(int i = 0 ; i < n ; i++){ int r = sc.nextInt(); int u = sc.nextInt(); p[i] = new Pair(r,u); } Arrays.sort(p , new Comparator<Pair>() { public int compare(Pair a,Pair b){ if(a.h == b.h){ return a.w - b.w; } return a.h-b.h; } }); String ans = ""; int r = 0; int u = 0; boolean pos = true; for(int i = 0 ; i < n ; i++){ if(p[i].h >= r && p[i].w >= u){ int rr = p[i].h-r; for(int x = 0 ; x < rr ; x++){ ans = ans + "R"; } int uu = p[i].w-u; for(int x = 0 ; x < uu ; x++){ ans = ans + "U"; } r = p[i].h; u = p[i].w; } else { pos = false; break; } } if(pos){ out.println("YES"); out.println(ans); } else { out.println("NO"); } } } static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out; @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); solve(); } catch (Throwable uncaught) { Solution.uncaught = uncaught; } finally { out.close(); } } public static void main(String[] args) throws Throwable { Thread thread = new Thread(null, new Solution(), "", (1 << 26)); thread.start(); thread.join(); if (Solution.uncaught != null) { throw Solution.uncaught; } } } 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 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
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
10ec06e8900df2988e6f815871563cfb
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*; import java.lang.*; public class Hello { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++) { int n=sc.nextInt(); if(n!=1) { int[] arr1 =new int[n+1]; int[] arr2 =new int[n+1]; arr1[0]=0; arr2[0]=0; for(int j=1;j<n+1;j++) { arr1[j]=sc.nextInt(); arr2[j]=sc.nextInt(); } for(int j=1;j<n+1;j++) { for(int k=1;k<n;k++) { if(arr1[k]>arr1[k+1]) { int temp=arr1[k]; arr1[k]=arr1[k+1]; arr1[k+1]=temp; temp=arr2[k]; arr2[k]=arr2[k+1]; arr2[k+1]=temp; } else if(arr1[k]==arr1[k+1]) { if(arr2[k]>arr2[k+1]) { int temp=arr2[k]; arr2[k]=arr2[k+1]; arr2[k+1]=temp; } } } } int flag=0; StringBuilder s= new StringBuilder(); for(int j=0;j<n;j++) { int temp=arr1[j + 1] - arr1[j]; s.append("R".repeat(Math.max(0, temp))); temp=arr2[j+1]-arr2[j]; if(temp>=0) { s.append("U".repeat(Math.max(0, temp))); } else { System.out.println("NO"); flag=1; break; } } if(flag==0) { System.out.println("YES"); System.out.println(s); } } else { int a=sc.nextInt(); int b=sc.nextInt(); System.out.println("YES"); String s = "R".repeat(Math.max(0, a)) + "U".repeat(Math.max(0, b)); System.out.println(s); } } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
621e6a714c56508b9e1ba20dd8e42bf9
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*; public class b { public static void main(String[] args) { Scanner kb = new Scanner(System.in); int tt = kb.nextInt(); for(int t = 0; t < tt; t++) { int n = kb.nextInt(); Point[] packages = new Point[n]; for(int i = 0; i < n; i++) { packages[i] = new Point(kb.nextInt(), kb.nextInt()); } Arrays.sort(packages); // System.out.println(Arrays.toString(packages)); int i = 0; Point pos = new Point(0,0); String str = ""; boolean flag = false; while(i < n) { int xdiff = packages[i].x - pos.x; if(xdiff<0) { flag = true; break; } while(xdiff>0) { str+="R"; xdiff--; pos.x++; } int ydiff = packages[i].y - pos.y; if(ydiff < 0) { flag = true; break; } while(ydiff>0) { str+="U"; ydiff--; pos.y++; } i++; // System.out.println(pos); } if(flag) { System.out.println("NO"); } else { System.out.println("YES\n"+str); } } } static class Point implements Comparable<Point>{ int x, y; Point(int x, int y){ this.x = x; this.y = y; } public int compareTo(Point o) { Point origin = new Point(0,0); if(dist(origin)<=o.dist(origin)) return -1; return 1; } public int dist(Point o) { int dist = Math.abs(x-o.x + y-o.y); return dist; } public String toString() { return "("+x+","+y+")"; } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
de292fd2e7a3a43d7730653549776cbd
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.Scanner; import java.util.*; public class JavaApplication9 { static class Pair { int f; int s; Pair(int f, int s) { this.f = f; this.s = s; } } static class sortCoordinates implements Comparator<Pair> { public int compare(Pair a, Pair b) { double dis1 = Math.sqrt(a.f*a.f+a.s*a.s); double dis2 = Math.sqrt(b.f*b.f+b.s*b.s); return (dis1 > dis2 ? 1 : ((dis1 < dis2) ? -1 : 0)); } } public static void main(String args[]) { //Reader io = new Reader(); Scanner io = new Scanner(System.in); int t = io.nextInt(); while(t-- != 0) { int n = io.nextInt(); Pair[] c = new Pair[n+1]; c[0] = new Pair(0, 0); for(int i = 1; i <= n; i++) c[i] = new Pair(io.nextInt(), io.nextInt()); Arrays.sort(c, new sortCoordinates()); boolean poss = true; for(int i = 1; poss && i <= n; i++) if((c[i].f >= c[i-1].f && c[i].s < c[i-1].s) || (c[i].s >= c[i-1].s && c[i].f < c[i-1].f)) poss = false; if(!poss) { System.out.println("NO"); continue; } String sol = ""; /*ArrayList<String>[] sols = new ArrayList[n-1]; for(int i = 0; i < n-1; i++) sols[i] = new ArrayList<>();*/ for(int i = 1; i <= n; i++) { int nR = c[i].f - c[i-1].f; int nU = c[i].s - c[i-1].s; while(nR-- != 0) sol += "R"; while(nU-- != 0) sol += "U"; } System.out.println("YES"); System.out.println(sol); } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
9893dc53524eed24431962a6f1a53324
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*; public class Solution1294B { public static class Point implements Comparable<Point> { int x; int y; public Point(int xCod, int yCod) { this.x = xCod; this.y = yCod; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Point point = (Point) o; return x == point.x && y == point.y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public int compareTo(Point o) { return 0; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); while (t-- > 0) { int n = scanner.nextInt(); List<Point> list = new ArrayList<>(); for (int i = 0; i < n; ++i) { Point p = new Point(scanner.nextInt(), scanner.nextInt()); list.add(p); } list.sort((o1, o2) -> { if (o1.x != o2.x) return Integer.compare(o1.x, o2.x); return Integer.compare(o1.y, o2.y); }); solve(list); } } public static void solve(List<Point> list) { int x = 0; int y = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); ++i) { Point cur = list.get(i); if (cur.x < x || cur.y < y) { System.out.println("NO"); return; } int xDiff = cur.x - x; int yDiff = cur.y - y; sb.append("R".repeat(Math.max(0, xDiff))); sb.append("U".repeat(Math.max(0, yDiff))); x = cur.x; y = cur.y; } System.out.println("YES"); System.out.println(sb.toString()); } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
fb230225ce216674ed349fccc7adb6c8
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
// package com.company; import javax.swing.plaf.IconUIResource; import java.util.*; import java.io.*; import java.lang.*; /* ** @author jigar_nainuji */ public class Main{ public static void main(String args[]){ PrintWriter out=new PrintWriter(System.out); InputReader in=new InputReader(System.in); TASK solver = new TASK(); int t = in.nextInt(); // int t=1; for(int i=0;i<t;i++) { solver.solve(in,out,i); } out.close(); } static class TASK { static int mod = 1000000007; void solve(InputReader in, PrintWriter out, int testNumber) { int n = in.nextInt(); ArrayList<pair> al = new ArrayList<>(); for(int i=0;i<n;i++) { int x = in.nextInt(); int y = in.nextInt(); al.add(new pair(x,y)); } Collections.sort(al, new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if(o1.x==o2.x) return o1.y-o2.y; return o1.x-o2.x; } }); String s=""; int x=0,y=0; boolean flag=true; for(int i=0;i<n;i++) { if(al.get(i).x==x) { for(int j=0;j<al.get(i).y-y;j++) s+="U"; x=al.get(i).x; y=al.get(i).y; } else { if(al.get(i).y<y) { flag=false; break; } else { for(int j=0;j<al.get(i).x-x;j++) s+="R"; for(int j=0;j<al.get(i).y-y;j++) s+="U"; x=al.get(i).x; y=al.get(i).y; } } } if(flag) { System.out.println("YES"); System.out.println(s); } else System.out.println("NO"); } } static class pair{ int x; int y; pair(int x,int y) { this.x=x; this.y=y; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
b9fcd8e35c253f735805cb4e39efe946
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner scner = new Scanner(System.in); Map<Integer, Integer> map = new HashMap<>(); StringBuilder ans= new StringBuilder(); int cases = scner.nextInt(); for (int i = 0; i < cases; i++) { Set<Map<Integer, Integer>> pairs = new HashSet<>(); List<Integer> Xs = new ArrayList<>(); List<Integer> Ys = new ArrayList<>(); Set<Map<Integer, Integer>> postSortingPair = new HashSet<>(); int packages = scner.nextInt(); for (int j = 0; j < packages; j++) { int x = scner.nextInt(); int y = scner.nextInt(); Xs.add(x); Ys.add(y); Map<Integer, Integer> pair = new HashMap<>(); pair.put(x, y); pairs.add(pair); } Collections.sort(Xs); Collections.sort(Ys); StringBuilder steps = new StringBuilder(); for (int l = 0; l < Xs.size(); l++) { int x = Xs.get(l); int y = Ys.get(l); Map<Integer, Integer> pair = new HashMap<>(); pair.put(x, y); postSortingPair.add(pair); if (l == 0) { steps.append("R".repeat(x)); steps.append("U".repeat(y)); } else { steps.append("R".repeat(x - Xs.get(l - 1))); steps.append("U".repeat(y - Ys.get(l - 1))); } } boolean possible= pairs.equals(postSortingPair); if (possible){ ans.append("YES"+"\n"); ans.append(steps+"\n"); } else{ ans.append("NO"+"\n"); } } System.out.println(ans); } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
a74ebd0e3a6501ee854531895e2fe595
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; import java.util.Collections; import java.util.ArrayList; /** * 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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { int t = in.nextInt(); for (int i = 0; i < t; i++) { ArrayList<Pair> a = new ArrayList<>(); int n = in.nextInt(); for (int j = 0; j < n; j++) { a.add(new Pair(in.nextInt(), in.nextInt())); } Collections.sort(a); boolean isBad = false; Pair prev = new Pair(0, 0); String ans = ""; for (int j = 0; j < n; j++) { int x = a.get(j).x; int y = a.get(j).y; if (!(x >= prev.x && y >= prev.y)) { isBad = true; break; } ans += "R".repeat(x - prev.x) + "U".repeat(y - prev.y); prev = a.get(j); } if (isBad) out.println("NO"); else { out.println("YES"); out.println(ans); } } } } static class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(Pair o) { if (x < o.x) return -1; else if (x > o.x) return 1; else if (y < o.y) return -1; else if (y > o.y) return 1; return 0; } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
66c003f3ee06fdeb891c98c2c9fed545
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Solution { private static class Coords { private final int x; private final int y; private Coords(int x, int y) { this.x = x; this.y = y; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int tests = scanner.nextInt(); for (int t = 0; t < tests; t++) { List<Coords> coords = new ArrayList<>(); int packages = scanner.nextInt(); for (int p = 0; p < packages; p++) { coords.add(new Coords(scanner.nextInt(), scanner.nextInt())); } coords.sort((c1, c2) -> { if (c1.y == c2.y) { return Integer.compare(c1.x, c2.x); } return Integer.compare(c1.y, c2.y); }); StringBuilder res = new StringBuilder(); Coords prev = new Coords(0, 0); boolean can = true; for (Coords coord : coords) { String toAppend = getFromTo(prev, coord); if (toAppend.equals("")) { System.out.println("NO"); can = false; break; } res.append(toAppend); prev = coord; } if (can) { System.out.println("YES"); System.out.println(res.toString()); } } } private static String getFromTo(Coords src, Coords dst) { StringBuilder sb = new StringBuilder(); if (src.x > dst.x || src.y > dst.y) { return ""; } int x = src.x; while (x < dst.x) { sb.append('R'); x++; } int y = src.y; while (y < dst.y) { sb.append('U'); y++; } return sb.toString(); } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
91f94d411e38ead99457272994ae45b3
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { static Vector<Integer>[] tree; public void solve() throws Exception { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); Pair pair[]=new Pair[n]; for(int i=0;i<n;i++) { int x=sc.nextInt(); int y=sc.nextInt(); pair[i]=new Pair(x,y); } Arrays.sort(pair, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if(p1.x==p2.x) return p1.y - p2.y; else return p1.x - p2.x; } }); StringBuilder result=new StringBuilder(); int xx=0; int yy=0; boolean flag=true; // System.out.println(pair[0].x+" "+pair[0].y); for(int i=0;i<n;i++) { if(i==0) { for(int j=0;j<pair[i].x;j++) { result.append("R"); } for(int j=0;j<pair[i].y;j++) { result.append("U"); } } else { if(pair[i].y<pair[i-1].y) { out.println("NO"); flag=false; break; } else { for(int j=pair[i-1].x;j<pair[i].x;j++) { result.append("R"); } for(int j=pair[i-1].y;j<pair[i].y;j++) { result.append("U"); } } } } if(flag) { out.println("YES"); out.println(result); } } } class Pair { int x; int y; // Constructor public Pair(int x, int y) { this.x = x; this.y = y; } } static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out; @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); solve(); } catch (Throwable uncaught) { Solution.uncaught = uncaught; } finally { out.close(); } } public static void main(String[] args) throws Throwable { Thread thread = new Thread(null, new Solution(), "", (1 << 26)); thread.start(); thread.join(); if (Solution.uncaught != null) { throw Solution.uncaught; } } } 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 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
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
3fafb5248bde1ff0de5dfb1dbfe2275a
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class B { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); final int t = scanner.nextInt(); boolean[][] matrix = new boolean[1001][1001]; for (int i = 0; i < t; i++) { for (boolean[] booleans : matrix) Arrays.fill(booleans, false); final int n = scanner.nextInt(); for (int j = 0; j < n; j++) { final int x = scanner.nextInt(); final int y = scanner.nextInt(); matrix[x][y] = true; } boolean able = true; for (int y = 0, currX = 0; y < 1001; y++) { for (int x = 0; x < 1001; x++) { if (matrix[x][y]) { if (x < currX) { able = false; break; } currX = x; } } } if (!able) { System.out.println("NO"); continue; } System.out.println("YES"); StringBuilder buffer = new StringBuilder(); for (int y = 0, currX = 0, currY = 0; y < 1001; ++y) for (int x = 0; x < 1001; x++) if (matrix[x][y]) { buffer.append("R".repeat(x - currX)).append("U".repeat(y - currY)); currX = x; currY = y; } System.out.println(buffer); } scanner.close(); } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
e9a927ac120167fdbc8b3e5e6483f7af
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Ribhav */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BCollectingPackages solver = new BCollectingPackages(); solver.solve(1, in, out); out.close(); } static class BCollectingPackages { public void solve(int testNumber, FastReader s, PrintWriter out) { int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); BCollectingPackages.coord[] arr = new BCollectingPackages.coord[n]; for (int i = 0; i < n; i++) { arr[i] = new BCollectingPackages.coord(s.nextInt(), s.nextInt()); } Arrays.sort(arr); int currX = 0; int currY = 0; int i = 0; boolean ok = true; StringBuilder ans = new StringBuilder(); while (i < n) { if (arr[i].x < currX || arr[i].y < currY) { ok = false; break; } while (currX != arr[i].x) { ans.append("R"); currX++; } while (currY != arr[i].y) { ans.append("U"); currY++; } i++; } if (!ok) { out.println("NO"); } else { out.println("YES"); out.println(ans.toString()); } } } private static class coord implements Comparable<BCollectingPackages.coord> { int x; int y; public coord(int x, int y) { this.x = x; this.y = y; } public int compareTo(BCollectingPackages.coord o) { if (this.x == o.x) { return Integer.compare(this.y, o.y); } return Integer.compare(this.x, o.x); } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int 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
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
0732d3268b59a6d9f69a678c6e314dea
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { FastReader sc = new FastReader(); int t = sc.nextInt(); ArrayList<int[][]> arr = new ArrayList<>(); for(int i=0; i<t; i++) { int n = sc.nextInt(); int[][] a = new int[n][2]; for(int j=0; j<n; j++) { a[j][0] = sc.nextInt(); a[j][1] = sc.nextInt(); } arr.add(a); } for(int i=0; i<t; i++) { result(arr.get(i)); } } private static void result(int[][] a) { Arrays.sort(a, new Comparator<int[]>() { public int compare(int[] o1, int[] o2) { if(o1[0] == o2[0]) return o1[1] - o2[1]; return o1[0] - o2[0]; } }); if(a.length == 1) { System.out.println("YES"); String s = ""; s = s.concat(new String(new char[a[0][0]]).replace("\0", "R")); s = s.concat(new String(new char[a[0][1]]).replace("\0", "U")); System.out.println(s); } else { int i; for(i= 1; i<a.length; i++) if(a[i][1] < a[i-1][1]) break; if(i< a.length) System.out.println("NO"); else { String s = ""; s = s.concat(new String(new char[a[0][0]]).replace("\0", "R")); s = s.concat(new String(new char[a[0][1]]).replace("\0", "U")); for(int j=1; j<a.length; j++) { s = s.concat(new String(new char[a[j][0] - a[j-1][0]]).replace("\0", "R")); s = s.concat(new String(new char[a[j][1] - a[j-1][1]]).replace("\0", "U")); } System.out.println("YES"); System.out.println(s); } } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
aa486dea1d66eb4ca0919cd39426b76f
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*; public class collectingPackages { static class pair{ int x; int y; public pair(int x,int y){ this.x=x; this.y=y; } } public static void main(String[]args){ Scanner scn= new Scanner(System.in); int t= scn.nextInt(); while(t>0){ int n= scn.nextInt(); pair[]arr= new pair[n]; for(int i=0;i<n;i++){ int a=scn.nextInt(); int b= scn.nextInt(); arr[i]=new pair(a,b); } pairSort(arr); String str=""; boolean flag=true; for(int i=0;i<n;i++){ String ans=""; if(i==0){ ans=fill(0,0,"",arr[i].x,arr[i].y); }else{ ans=fill(arr[i-1].x,arr[i-1].y,"",arr[i].x,arr[i].y); } if(ans.length()==0){ flag=false; break; } str+=ans; } if(flag==false) System.out.println("NO"); else { System.out.println("YES"); System.out.println(str); } t--; } scn.close(); } public static String fill(int srcx,int srcy,String str, int desx,int desy){ if(srcx>desx || srcy>desy) return ""; if(srcx==desx && srcy==desy){ return str; } String right=fill(srcx+1,srcy,str+"R",desx,desy); if(right.length()!=0) return right; String up=fill(srcx,srcy+1,str+"U",desx,desy); return up; } public static void pairSort(pair []arr){ for(int j=1;j<arr.length;j++){ for(int i=0;i<arr.length-j;i++){ if(arr[i].x>arr[i+1].x){ pair temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; }else if(arr[i].x==arr[i+1].x){ if(arr[i].y> arr[i+1].y){ pair temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } } } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
43a4f882632646918dce88ca8a8d4752
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.io.*; import java.util.*; public class CodeForces { public static void main(String[] args) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); //array a is sorted in non-descending order //array b is sorted in non-ascending order int T=Integer.parseInt(infile.readLine()); for(int loop=1;loop<=T;loop++){ int N=Integer.parseInt(infile.readLine()); Pair[] array = new Pair[N]; for(int i=0;i<array.length;i++){ String[] temp=infile.readLine().split(" "); array[i]=new Pair(Integer.parseInt(temp[0]),Integer.parseInt(temp[1])); } Arrays.sort(array); StringBuilder ret=new StringBuilder(); int x=0; int y=0; boolean state=true; for(Pair ele:array){ if(ele.x>=x&&ele.y>=y){ build(ret,ele.x-x,ele.y-y); x=ele.x; y=ele.y; } else{ state=false; break; } } if(state){ System.out.println("YES"); System.out.println(ret.toString()); } else{ System.out.println("NO"); } } } private static void build(StringBuilder s, int x, int y){ for(int i=1;i<=x;i++){ s.append("R"); } for(int i=1;i<=y;i++){ s.append("U"); } } } class Pair implements Comparable<Pair>{ public int x; public int y; public Pair(int a,int b){ x=a; y=b; } public int compareTo(Pair p){ if(p.x==x){ return y-p.y; } else return x-p.x; } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
e7fbacf8157291582d80fd31d078a1c0
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*; public class MyClass { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); outer :while(t-->0){ int n = sc.nextInt(); int[][] arr = new int[n][2]; for(int i =0;i<n;i++) { arr[i][0] = sc.nextInt(); arr[i][1] = sc.nextInt(); } Arrays.sort(arr,(a,b) -> a[0] == b[0] ? Integer.compare(a[1],b[1]) : Integer.compare(a[0],b[0])); StringBuilder sb = new StringBuilder(); boolean ok = true; int x = 0, y = 0; for(int i=0;i<n;i++) { if(arr[i][1] < y) { ok = false; break; } while(x < arr[i][0]) { sb.append("R"); x++; } while(y < arr[i][1]) { sb.append("U"); y++; } } if(ok) { System.out.println("YES"); System.out.println(sb); } else { System.out.println("NO"); } } }}
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
9caaba029281386bb534e8f3e53fb499
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.math.*; import java.io.*; import java.util.*; import java.awt.*; public class CP { public static void main(String[] args) throws Exception { new Solver().solve(); } } class Solver { final Helper hp; final int MAXN = 1000_006; final long MOD = (long) 1e9 + 7; Solver() { hp = new Helper(MOD, MAXN); hp.initIO(System.in, System.out); } void solve() throws Exception { int i, j, k; for (int tc = hp.nextInt(); tc > 0; --tc) { int N = hp.nextInt(); int[][] C = new int[N][]; for (i = 0; i < N; ++i) C[i] = hp.getIntArray(2); Arrays.sort(C, (a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1])); int currX = 0, currY = 0; StringBuilder sb = new StringBuilder(); boolean ok = true; for (int[] p : C) { if (currX > p[0] || currY > p[1]) ok = false; while (currX < p[0]) { sb.append("R"); ++currX; } while (currY < p[1]) { sb.append("U"); ++currY; } } if (ok) { hp.println("YES"); hp.println(sb); } else { hp.println("NO"); } } hp.flush(); } } class Helper { final long MOD; final int MAXN; final Random rnd; public Helper(long mod, int maxn) { MOD = mod; MAXN = maxn; rnd = new Random(); } public static int[] sieve; public static ArrayList<Integer> primes; public void setSieve() { primes = new ArrayList<>(); sieve = new int[MAXN]; int i, j; for (i = 2; i < MAXN; ++i) if (sieve[i] == 0) { primes.add(i); for (j = i; j < MAXN; j += i) { sieve[j] = i; } } } public static long[] factorial; public void setFactorial() { factorial = new long[MAXN]; factorial[0] = 1; for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD; } public long getFactorial(int n) { if (factorial == null) setFactorial(); return factorial[n]; } public long ncr(int n, int r) { if (r > n) return 0; if (factorial == null) setFactorial(); long numerator = factorial[n]; long denominator = factorial[r] * factorial[n - r] % MOD; return numerator * pow(denominator, MOD - 2, MOD) % MOD; } public long[] getLongArray(int size) throws Exception { long[] ar = new long[size]; for (int i = 0; i < size; ++i) ar[i] = nextLong(); return ar; } public int[] getIntArray(int size) throws Exception { int[] ar = new int[size]; for (int i = 0; i < size; ++i) ar[i] = nextInt(); return ar; } public String[] getStringArray(int size) throws Exception { String[] ar = new String[size]; for (int i = 0; i < size; ++i) ar[i] = next(); return ar; } public String joinElements(long[] ar) { StringBuilder sb = new StringBuilder(); for (long itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(int[] ar) { StringBuilder sb = new StringBuilder(); for (int itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(String[] ar) { StringBuilder sb = new StringBuilder(); for (String itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(Object[] ar) { StringBuilder sb = new StringBuilder(); for (Object itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } public int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public long max(long[] ar) { long ret = ar[0]; for (long itr : ar) ret = Math.max(ret, itr); return ret; } public int max(int[] ar) { int ret = ar[0]; for (int itr : ar) ret = Math.max(ret, itr); return ret; } public long min(long[] ar) { long ret = ar[0]; for (long itr : ar) ret = Math.min(ret, itr); return ret; } public int min(int[] ar) { int ret = ar[0]; for (int itr : ar) ret = Math.min(ret, itr); return ret; } public long sum(long[] ar) { long sum = 0; for (long itr : ar) sum += itr; return sum; } public long sum(int[] ar) { long sum = 0; for (int itr : ar) sum += itr; return sum; } public void shuffle(int[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public void shuffle(long[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public long pow(long base, long exp, long MOD) { base %= MOD; long ret = 1; while (exp > 0) { if ((exp & 1) == 1) ret = ret * base % MOD; base = base * base % MOD; exp >>= 1; } return ret; } static byte[] buf = new byte[2048]; static int index, total; static InputStream in; static BufferedWriter bw; public void initIO(InputStream is, OutputStream os) { try { in = is; bw = new BufferedWriter(new OutputStreamWriter(os)); } catch (Exception e) { } } public void initIO(String inputFile, String outputFile) { try { in = new FileInputStream(inputFile); bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputFile))); } catch (Exception e) { } } private int scan() throws Exception { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } public String next() throws Exception { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) sb.append((char) c); return sb.toString(); } public int nextInt() throws Exception { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') c = scan(); for (; c >= '0' && c <= '9'; c = scan()) val = (val << 3) + (val << 1) + (c & 15); return neg ? -val : val; } public long nextLong() throws Exception { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') c = scan(); for (; c >= '0' && c <= '9'; c = scan()) val = (val << 3) + (val << 1) + (c & 15); return neg ? -val : val; } public void print(Object a) throws Exception { bw.write(a.toString()); } public void printsp(Object a) throws Exception { print(a); print(" "); } public void println() throws Exception { bw.write("\n"); } public void println(Object a) throws Exception { print(a); println(); } public void flush() throws Exception { bw.flush(); } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
b15412b23026b76b03a055bd1af4632d
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*;import java.io.*;import java.math.*; public class Main { static class Pair{ int x,y; public Pair(int x,int y){ this.x=x; this.y=y; } } static class sortByCoord implements Comparator<Pair>{ public int compare(Pair A,Pair B){ if(A.x!=B.x) return (A.x)-(B.x); return (A.y-B.y); } } public static void process()throws IOException { int n=ni(); Pair arr[]=new Pair[n+1]; for(int i=1;i<=n;i++) arr[i]=new Pair(ni(),ni()); arr[0]=new Pair(0,0); Arrays.sort(arr,new sortByCoord()); int cx=0,cy=0; StringBuilder res = new StringBuilder(); for(int i=1;i<=n;i++){ Pair go_to=arr[i]; int gx=arr[i].x,gy=arr[i].y; if(gx<cx || gy<cy){ pn("NO"); return; } while(cx<gx) { cx++; res.append('R'); } while(cy<gy){ cy++; res.append('U'); } } pn("YES\n"+res); } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { out = new PrintWriter(System.out); sc=new AnotherReader(); boolean oj = true; oj = System.getProperty("ONLINE_JUDGE") != null; if(!oj) sc=new AnotherReader(100); long s = System.currentTimeMillis(); int t=1; t=ni(); while(t-->0) process(); out.flush(); if(!oj) System.out.println(System.currentTimeMillis()-s+"ms"); System.out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);System.out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} static boolean multipleTC=false; static long mod=(long)1e9+7l; static long mpow(long x, long n) { if(n == 0) return 1; if(n % 2 == 0) { long root = mpow(x, n / 2); return root * root % mod; }else { return x * mpow(x, n - 1) % mod; } } static long mcomb(long a, long b) { if(b > a - b) return mcomb(a, a - b); long m = 1; long d = 1; long i; for(i = 0; i < b; i++) { m *= (a - i); m %= mod; d *= (i + 1); d %= mod; } long ans = m * mpow(d, mod - 2) % mod; return ans; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
e52a416fadbf4f53034f8f275e1abd4d
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*; import static java.lang.Math.*; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigInteger; public class Main { static int mod = 1000000007; static int MOD = 1000000007; static int temp = 998244353; static final long M = (int)1e9+7; static class Pair implements Comparable<Pair> { int first, second; public Pair(int aa, int bb) { first = aa; second = bb; } public int compareTo(Pair p) { // if(a == p.a) return b - p.b; // return a - p.a; if(first == p.first) return second - p.second; return first - p.first; } } /* * IO FOR 2D GRID IN JAVA * char[][] arr = new char[n][m]; //grid in Q. for(int i = 0;i<n;i++) { char[] nowLine = sc.next().toCharArray(); for(int j = 0;j<m;j++) { arr[i][j] = nowLine[i]; } } * */ 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 next() 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; } int[] readArray(int n) throws IOException { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } 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 BigInteger nextBigInteger() { // TODO Auto-generated method stub return null; } } public static boolean isPrime(long n) { if(n == 1) { return false; } for(long i = 2;i*i<=n;i++) { if(n%i == 0) { return false; } } return true; } public static List<Integer> Sieve(int n) { boolean prime[] = new boolean[n+1]; Arrays.fill(prime, true); List<Integer> l = new ArrayList<>(); for (int p=2; p*p<=n; p++) { if (prime[p] == true) { for(int i=p*p; i<=n; i += p) { prime[i] = false; } } } for (int p=2; p<=n; p++) { if (prime[p] == true) { l.add(p); } } return l; } public static int gcd(int a, int b) { if(b == 0) return a; else return gcd(b,a%b); } public static long LongGCD(long a, long b) { if(b == 0) return a; else return LongGCD(b,a%b); } public static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } public static int phi(int n) //euler totient function { int result = 1; for (int i = 2; i < n; i++) if (gcd(i, n) == 1) result++; return result; } public static int[] computePrefix(int arr[], int n) { int[] prefix = new int[n]; prefix[0] = arr[0]; for(int i = 1;i<n;i++) { prefix[i] = prefix[i-1]+arr[i]; } return prefix; } public static int fastPow(int x, int n) //include mod at each step if asked and in args of fn too { if(n == 0) return 1; else if(n%2 == 0) return fastPow(x*x,n/2); else return x*fastPow(x*x,(n-1)/2); } public static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(int n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. public static long nCr(int n, int r, int p) { if (n<r) return 0; if (r == 0) return 1; int[] fac = new int[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } public static int LowerBound(int a[], int x) { int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } public static int UpperBound(int a[], int x) { int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } public static void Sort(int[] a) { List<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); //Collections.reverse(l); //Use to Sort decreasingly for (int i=0; i<a.length; i++) a[i]=l.get(i); } //MODULO OPS for addition and multiplication public static long perfomMod(long x){ return ((x%M + M)%M); } public static long addMod(long a, long b){ return perfomMod(perfomMod(a)+perfomMod(b)); } public static long mulMod(long a, long b){ return perfomMod(perfomMod(a)*perfomMod(b)); } public static void main(String[] args) throws IOException { Reader sc = new Reader(); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); loop: while(t-- > 0) { int n = sc.nextInt(); ArrayList<Pair> l = new ArrayList<>(); for(int i = 0;i<n;i++) { int u = sc.nextInt(), v = sc.nextInt(); Pair curr = new Pair(u,v); l.add(curr); } Collections.sort(l); Pair curr = new Pair(0,0); String ap = ""; boolean ok = true; for(int i = 0;i<n;i++) { int r = l.get(i).first - curr.first; int u = l.get(i).second - curr.second; if(r < 0 || u < 0) { System.out.println("NO"); ok = false; continue loop; } while(r-- > 0) { ap += "R"; } while(u-- > 0) { ap += "U"; } curr = l.get(i); } if(ok == true) { System.out.println("YES"); System.out.println(ap); } } out.close(); } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
f0f5f86d4bdb0f34f6cbb9d64593262c
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Cf131 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 Cf131(),"Main",1<<27).start(); } static class Pair { int z; int o; Pair(int z,int o) { this.z=z; this.o=o; } } static class Edge implements Comparable<Edge> { int end, wght; public Edge(int end, int wght) { this.end = end; this.wght = wght; } public int compareTo(Edge edge) { return this.wght - edge.wght; } } public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); StringBuilder tem1 = new StringBuilder(); StringBuilder tem2 = new StringBuilder(); String[] u = new String[1001]; String[] r = new String[1001]; u[0]=""; for(int i=1;i<1001;i++){ tem1.append("U"); tem2.append("R"); u[i] = tem1.toString(); r[i] = tem2.toString(); } int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); // w.println(n); int max = -1; ArrayList<PriorityQueue<Integer>> p = new ArrayList<PriorityQueue<Integer>>(); for(int i=0;i<1001;i++){ p.add(new PriorityQueue<Integer>()); } StringBuilder s = new StringBuilder(); for(int i=0;i<n;i++){ int x = sc.nextInt(); int y = sc.nextInt(); p.get(x).add(y); max = max(x,max); } int z = 0; int y=0; int f = 0; for(int i=0;i<=max;i++){ if(f==1)break; int li = p.get(i).size(); for(int j=0;j<li;j++){ z = p.get(i).poll()-y; if(z>=0){ s.append(u[z]); y = y+z; } else{ w.println("NO"); f=1; break; } } if(i<max) s.append("R"); // w.print(s.toString()+" "); } if(f==0){ w.println("YES"); w.println(s.toString()); } } w.flush(); w.close(); } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
3d83101ac0c09f993234e24407d478f3
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.io.*; import java.util.*; public class CF1294B extends PrintWriter { CF1294B() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1294B o = new CF1294B(); o.main(); o.flush(); } static class P { int x, y; P(int x, int y) { this.x = x; this.y = y; } } void main() { int t = sc.nextInt(); byte[] cc = new byte[2000]; while (t-- > 0) { int n = sc.nextInt(); P[] pp = new P[n + 1]; pp[0] = new P(0, 0); for (int i = 1; i <= n; i++) { int x = sc.nextInt(); int y = sc.nextInt(); pp[i] = new P(x, y); } Arrays.sort(pp, (p, q) -> p.x != q.x ? p.x - q.x : p.y - q.y); boolean yes = true; int k = 0; for (int i = 1; i <= n; i++) { int x = pp[i].x - pp[i - 1].x; int y = pp[i].y - pp[i - 1].y; if (x < 0 || y < 0) { yes = false; break; } while (x-- > 0) cc[k++] = 'R'; while (y-- > 0) cc[k++] = 'U'; } if (yes) { println("YES"); println(new String(cc, 0, k)); } else println("NO"); } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
45f3cbb14cebe3e156bd142acc73a20d
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ar { 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 (final 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 (final IOException e) { e.printStackTrace(); } return str; } } static boolean[] seen; static Map<Integer, Integer> map; static Map<Long, Long> lmap; static Set<Character> charset; static Set<Integer> set; static int[] arr; static int[][] dp; static int rem = (int) 1e9 + 7; static List<List<Integer>> graph; static int[][] kmv = { { 2, 1 }, { 1, 2 }, { 2, -1 }, { -1, 2 }, { -2, 1 }, { 1, -2 }, { -1, -2 }, { -2, -1 } }; static char[] car; static boolean[] primes; static int MAX = (int) 1e4 + 1; static double[] dar; static long[] lar; static long[][] dlar; static void Sieve() { primes = new boolean[MAX]; primes[0] = true; primes[1] = true; for (int i = 2; i * i < MAX; i++) { if (!primes[i]) { for (int j = i * i; j < MAX; j += i) { primes[j] = true; } } } } public static void main(String[] args) throws java.lang.Exception { FastReader scn = new FastReader(); int T = scn.nextInt(); for (int t = 0; t < T; t++) { int n = scn.nextInt(); dp = new int[n][2]; for (int i = 0; i < n; i++) { dp[i][0] = scn.nextInt(); dp[i][1] = scn.nextInt(); } Arrays.sort(dp, (a, b) -> a[0] - b[0]); int i = 0; int lx = 0, ly = 0; boolean isWrong = false; StringBuilder sb = new StringBuilder(); while (i < n) { if (i + 1 < n && dp[i][0] == dp[i + 1][0]) { PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (a[1] - b[1])); pq.add(new int[] { dp[i][0], dp[i][1] }); i++; while (i < n && dp[i][0] == dp[i - 1][0]) { pq.add(new int[] { dp[i][0], dp[i][1] }); i++; } while (!pq.isEmpty()) { int[] sub = pq.poll(); boolean ans = helper(sb, sub, lx, ly); if (!ans) { isWrong = true; break; } else { lx = sub[0]; ly = sub[1]; } } } else { boolean ans = helper(sb, dp[i], lx, ly); if (!ans) { isWrong = true; break; } else { lx = dp[i][0]; ly = dp[i][1]; } i++; } if (isWrong) { break; } } if (isWrong) { System.out.print("NO" + "\n"); } else { System.out.print("YES" + "\n"); System.out.print(sb+"\n"); } } } static boolean helper(StringBuilder sb, int[] newpos, int lx, int ly) { int diffx = newpos[0] - lx; int diffy = newpos[1] - ly; if (diffx < 0 || diffy < 0) return false; for (int i = 0; i < diffx; i++) { sb.append('R'); } for (int i = 0; i < diffy; i++) { sb.append('U'); } return true; } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
23fcfdfc7e8f5dd2e554cf0db9b7809d
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*; public class CollectingPackages { static class Pair{ int x; int y; public Pair(int x, int y){ this.x=x; this.y=y; } } static class Compare { public void compare(Pair arr[], int n) { Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { return p1.x - p2.x ; } }); } public void compare2(Pair arr[], int n) { Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { return p1.y - p2.y ; } }); } } public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); Pair arr[]=new Pair[n]; for (int i = 0; i < n; i++) { int x=s.nextInt(); int y=s.nextInt(); arr[i]= new Pair(x, y); } Compare obj = new Compare(); obj.compare(arr, n); obj.compare2(arr, n); // for (int i = 0; i <n ; i++) { // System.out.println(arr[i].x + " "+ arr[i].y); // } StringBuilder ans=new StringBuilder(); int curr=0, right=0, up=0; boolean acc=true; for(int i=0;i<n;i++){ Pair now=arr[i]; int r=now.x; int u=now.y; if(acc==true) { if (r >= right) { for (int j = 0; j < r - right; j++) ans.append('R'); right = r; } else acc=false; if (u >= up) { for (int j = 0; j < u-up; j++) ans.append('U'); up=u; } else acc=false; } } if(acc) { System.out.println("YES"); System.out.println(ans.toString()); } else System.out.println("NO"); } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
453689c96a5357a1111bb3289cedf505
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; import java.util.StringTokenizer; public class Collecting_Packages { public static void main(String[] args) { // TODO Auto-generated method stub Scanner t = new Scanner(System.in); int test = t.nextInt(); while (test-- > 0) { int n = t.nextInt(); Pair[] a = new Pair[n]; for (int i = 0; i < n; i++) { int x = t.nextInt(); int y = t.nextInt(); a[i] = new Pair(x, y); } Compare1 ob1 = new Compare1(); ob1.compare(a, n); Compare2 ob2 = new Compare2(); ob2.compare(a, n); StringBuilder s = new StringBuilder(); int x = 0, y = 0, dx = 0, dy = 0, flag = 0; for (int i = 0; i < n; i++) { dx = a[i].x - x; dy = a[i].y - y; x = a[i].x; y = a[i].y; if (dx < 0 || dy < 0) { flag = 1; break; } while (dx-- > 0) s.append("R"); while (dy-- > 0) s.append("U"); } if (flag == 0) { System.out.println("YES"); System.out.println(s); } else { System.out.println("NO"); } } } } class Pair { int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } } class Compare1 { static void compare(Pair arr[], int n) { Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { return p1.x - p2.x; } }); } } class Compare2 { static void compare(Pair arr[], int n) { Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { return p1.y - p2.y; } }); } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
b80cfa912a76dc51832184559f14020f
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class B { public static void main(String[] args) { Scanner input = new Scanner(System.in); int num = input.nextInt(); for (int i = 0; i < num; i++) { int n = input.nextInt(); int[][] arr = new int[n][2]; for (int j = 0; j < n; j++) { for (int k = 0; k < 2; k++) arr[j][k] = input.nextInt(); } Arrays.sort(arr, (o1, o2) -> { // 2차원배열 μ •λ ¬ -참고함. if (o1[0] == o2[0]) return Integer.compare(o1[1], o2[1]); else return Integer.compare(o1[0], o2[0]); }); int count = 0; for (int j = 0; j < n - 1; j++) { if (arr[j][1] > arr[j + 1][1]) { count++; break; } } int right; int up; if (count > 0) System.out.println("NO"); else { System.out.println("YES"); for(int j = 0; j < 1; j++) { for(int k = 0; k < arr[0][0]; k++) System.out.print("R"); for(int k = 0; k < arr[0][1]; k++) System.out.print("U"); } for (int j = 0; j < n - 1; j++) { right = arr[j + 1][0] - arr[j][0]; up = arr[j + 1][1] - arr[j][1]; for(int k = 0; k < right; k++) System.out.print("R"); for(int k = 0; k < up; k++) System.out.print("U"); } } System.out.println(); } } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
c8aa8e9ca3ed6c0db23e3ebf225148e2
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args){ Scanner in = new Scanner(System.in); int tcase = in.nextInt(); while(tcase-->0) { List<Pair> list = new ArrayList<>(); int count = in.nextInt(); for(int i=0 ; i<count ; i++) list.add(new Pair(in.nextInt(),in.nextInt())); list.sort((a, b) -> a.first == b.first ? Integer.compare(a.second, b.second) : Integer.compare(a.first, b.first)); StringBuilder ans = new StringBuilder(); int right=0, up=0 , sw=0; for(int i=0 ; i<list.size() ; i++){ if(list.get(i).first>=right){ ans.append("R".repeat(Math.max(0, (list.get(i).first - right)))); }else{ sw++; break; } right=list.get(i).first; if(list.get(i).second>=up){ ans.append("U".repeat(Math.max(0, (list.get(i).second - up)))); }else{ sw++; break; } up=list.get(i).second; } if(sw==0) System.out.println("YES\n"+ans); else System.out.println("NO"); } } } class Pair{ int first; int second; public Pair(int x , int y){ first=x; second=y; } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
cbda3a0c14c50220ac7d6f1249148dd6
train_004.jsonl
1579703700
There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j &lt; t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args){ Scanner in = new Scanner(System.in); int tcase = in.nextInt(); while(tcase-->0) { List<Pair> list = new ArrayList<>(); int count = in.nextInt(); for(int i=0 ; i<count ; i++) list.add(new Pair(in.nextInt(),in.nextInt())); Collections.sort(list,Comparator.comparingInt(p -> p.first)); int k=0; for(int i=0 ; i<count-1 ; i++){ int flag=Integer.MAX_VALUE; while(true){ if(list.get(i).first == list.get(i+1).first){ flag=Math.min(flag,i); i++; k++; }else break; if(i==count-1) break; } if(k!=0) { list.subList(flag, i + 1).sort(Comparator.comparingInt(p -> p.second)); } k=0; } StringBuilder ans = new StringBuilder(); boolean sw=true; List<Pair> listb = new ArrayList<>(); listb.add(new Pair(0,0)); for(int i=0 ; i<list.size() ; i++){ int r = list.get(i).first-listb.get(i).first; int u = list.get(i).second-listb.get(i).second; if(r<0 || u<0) { System.out.println("NO"); sw=false; break; } ans.append("R".repeat(r)); ans.append("U".repeat(u)); listb.add(list.get(i)); } if(sw) System.out.println("YES\n"+ans); } } } class Pair{ int first; int second; public Pair(int x , int y){ first=x; second=y; } }
Java
["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"]
1 second
["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"]
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
Java 11
standard input
[ "implementation", "sortings" ]
b01c627abc00f97767c237e304f8c17f
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) β€” the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le 1000$$$) β€” the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.
1,200
Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path β€” a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.
standard output
PASSED
82ad69445ccf14b0f18aa40cbe55b961
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Scanner_ { //global methods static class MyReader { BufferedReader br; StringTokenizer st; public MyReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String ne() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(ne()); } long nl() { return Long.parseLong(ne()); } double nd() { return Double.parseDouble(ne()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { new Thread(null, null, "Rahsut", 1 << 25) { public void run() { try { Freak(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static long modPow(long x, long p, long m) { if (p == 0) return 1; if (p % 2 == 0) return modPow((x * x) % m, p >> 1, m) % m; return x * (modPow(x, p - 1, m) % m) % m; } static long mul(long a, long b, long m) { a %= m; b %= m; return (a * b) % m; } static long gcd(long a,long b) { if(b%a==0) return a; return gcd(b%a,a); } static long lcm(long a, long b) { a/=gcd(a,b); return a*b; } public static class Pair implements Comparable<Pair> { long x, y; Pair(long x, long y) { this.x = x; this.y = y; } public int compareTo(Pair o) { if (x != o.x) return (int)x - (int)o.x; return (int)y - (int)o.y; } public String toString() { return x + " " + y; } } //global variables static MyReader sc = new MyReader(); static StringBuilder sb = new StringBuilder(); static PrintWriter pw = new PrintWriter(System.out, true); static int dir1[][]= {{1,0},{-1,0},{0,1},{0,-1}},n,q,t; static int dir2[][] ={{1,-1},{-1,1},{1,1},{-1,-1}}; static long dp[][], mod = (long)1e9 + 7; static void Freak() throws IOException { int t =sc.ni(); while(t-->0) { int n= sc.ni(), x = sc.ni(),ans = 0; char arr[]= sc.ne().toCharArray(); int bal[]= new int[n]; bal[0]=(arr[0]=='0')?1:-1; for(int i =1;i<n;i++) { bal[i]=bal[i-1] + ((arr[i]=='0')?1:-1); } if(x==0) ans++; if(bal[n-1]!=0) { for(int i : bal) { if((x-i) % bal[n-1] == 0 && (x-i)/bal[n-1] >= 0) ans++; } }else { int cnt = 0; for(int i : bal) if(i==x) cnt++; if(cnt>0) { ans = -1; } } sb.append(ans+"\n"); } pw.println(sb); pw.flush(); pw.close(); } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
60655e660dd43fda31c2864591d5a62d
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
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 Mufaddal Naya */ 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); BInfinitePrefixes solver = new BInfinitePrefixes(); solver.solve(1, in, out); out.close(); } static class BInfinitePrefixes { public void solve(int testNumber, InputReader c, OutputWriter w) { int tc = c.readInt(); while (tc-- > 0) { int n = c.readInt(), x = c.readInt(); char s[] = c.readString().toCharArray(); int pref[] = new int[n + 1]; for (int i = 1; i <= n; i++) { if (s[i - 1] == '1') { pref[i] = pref[i - 1] - 1; } else { pref[i] = pref[i - 1] + 1; } } int res = 0; if (x == 0) { res++; } for (int i = 1; i <= n; i++) { int req = x - pref[i]; if (req == 0 && pref[n] == 0) { res = -1; break; } if (pref[n] != 0 && req % pref[n] == 0 && req * (long) pref[n] >= 0) { res++; } } w.printLine(res); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
a77e5ffae64a4873a5586d5ac284858c
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.io.*; import java.util.*; public class MainClass { public static void main(String[] args)throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); StringBuilder stringBuilder = new StringBuilder(); while (t -- > 0) { String s1[] = in.readLine().split(" "); int n = Integer.parseInt(s1[0]); int x = Integer.parseInt(s1[1]); String s = in.readLine(); int[] A = new int[n + 1]; int c1 = 0; int c2 = 0; for (int i=1;i<=n;i++) { char ch = s.charAt(i - 1); if (ch == '0') c1++; else c2++; A[i] = c1 - c2; } int sum = A[n]; int ans = 0; if (sum == 0) { for (int i=0;i<=n;i++) { if (A[i] == x) { ans = -1; break; } } } else { for (int i=0;i<n;i++) { int d = x - A[i]; if (d % sum != 0) continue; else { int k = d / sum; if (k >= 0) ans ++; } } } stringBuilder.append(ans).append("\n"); } System.out.println(stringBuilder); } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
3e536e38eea1c4de5020f0d33bb7683a
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; /** * # * * @author pttrung */ public class B_Edu_Round_81 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int T = in.nextInt(); for (int z = 0; z < T; z++) { int n = in.nextInt(); int x = in.nextInt(); int[] data = new int[n]; String tmp = in.next(); int total = 0; for (int i = 0; i < n; i++) { data[i] = tmp.charAt(i) - '0'; if (data[i] == 0) { total++; } else { total--; } } if (total != 0) { int result = 0; int cur = 0; for (int i = 0; i < n; i++) { if (data[i] == 0) { cur++; } else { cur--; } int need = x - cur; //System.out.println(need + " " + total); if (need % total == 0 && (need / total) >= 0) { result++; } } if (x == 0) { result++; } out.println(result); } else { boolean found = false; int cur = 0; for (int i = 0; i < n; i++) { if (data[i] == 0) { cur++; } else { cur--; } if (cur == x) { found = true; break; } } if (found) { out.println(-1); } else { if (x == 0) { out.println(1); } else { out.println(0); } } } } out.close(); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * (val * a); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
cb846ba61b93bdc844674492bc996bd9
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
// Working program with FastReader import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc=new FastReader(); int t=sc.nextInt(); while(t>0) { t--; int n=sc.nextInt(); long x=sc.nextLong(); String s=sc.next(); StringBuilder sb=new StringBuilder(s); int i; // int max=0; int count=0; int min=(n+1); int max=-(n+1); HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); int ar[]=new int[n+1]; for(i=0;i<(n);i++) { if(sb.charAt(i)=='0') { count++; ar[i+1]=ar[i]+1;} else { count--; ar[i+1]=ar[i]-1; } } int total=count; int answer = 0; for (i=0; i<n; i++) { if (total == 0) { if (ar[i] == x) { answer = -1; } } else { long diff = x-(long) ar[i]; if (diff%total == 0 && diff/total >= 0) { answer++; } } } System.out.println(answer); } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
4d57bb030278d5ed991067769285a60f
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.awt.*; import java.io.*; import java.util.*; public class CandidateCode { public static void main(String[] args) throws Exception { // Scanner sc = new Scanner(System.in); FastReader sc = new FastReader(); int t=sc.nextInt(); while (t-->0){ int n=sc.nextInt(),x=sc.nextInt(); String s=sc.next(); int c=0; for (int i=0;i<n;i++){ if (s.charAt(i)=='0')c++; else c--; } int curr=0,ans=0; boolean inf=false; for (int i=0;i<n;i++){ if (c==0){ if (curr==x) { inf = true; break; } }else if ((x-curr)%c==0 && (x-curr)/c>=0)ans++; if (s.charAt(i)=='0')curr++; else curr--; } if (inf) System.out.println(-1); else System.out.println(ans); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
5141dd6f1ed966d84b5200de6879f8c2
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; import java.io.*; public class codeforces { static class Student{ int x,y,z; Student(int x,int y,int z){ this.x=x; this.y=y; this.z=z; } } static int prime[]; static void sieveOfEratosthenes(int n) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. int pos=0; prime= new int[n+1]; for(int p = 2; p*p <=n; p++) { // If prime[p] is not changed, then it is a prime if(prime[p] == 0) { // Update all multiples of p prime[p]=p; for(int i = p*p; i <= n; i += p) prime[i] = p; } } } static class Sortbyroll implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student c, Student b) { return b.x - c.x; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Edge{ int a,b; Edge(int a,int b){ this.a=a; this.b=b; } } static class Trie{ HashMap<Character,Trie>map; int c; Trie(){ map=new HashMap<>(); //z=null; //o=null; c=0; } } //static long ans; static int parent[]; static int rank[]; static int b[][]; static int bo[]; static int ho[]; static int seg[]; //static int pos; // static long mod=1000000007; //static int dp[][]; static HashMap<Integer,Integer>map; static PriorityQueue<Student>q=new PriorityQueue<>(); //static Stack<Integer>st; // static ArrayList<Character>ans; static ArrayList<ArrayList<Integer>>adj; static int ans; static Trie root; static long fac[]; static long mod=(long)(998244353); static void solve()throws IOException{ FastReader sc=new FastReader(); int a,b,t,i,ans,pos,c; String s; t=sc.nextInt(); while(t>0){ ans=0; c=0; pos=0; a=sc.nextInt(); b=sc.nextInt(); s=sc.nextLine(); int dp[]=new int[s.length()]; c=0; for(i=0;i<s.length();i++){ if(s.charAt(i)=='0') ++c; else --c; dp[i]=c; } for(i=0;i<s.length();i++){ if(c==0&&dp[i]==b) { pos=1; break; } } if(pos==1) System.out.println(-1); else{ if(b==0) ++ans; for(i=0;i<s.length();i++){ if(c!=0){ if((b-dp[i])/c>=0&&(int)(Math.abs(b-dp[i]))%(int)(Math.abs(c))==0) ++ans; } } System.out.println(ans); } --t; } } static void dfs(Trie root,int k){ if(root==null) return; for(char i='A';i<='Z';i++){ if(root.map.containsKey(i)){ ans+=root.map.get(i).c/k; dfs(root.map.get(i),k); } } } static long nCr(long n, long r, long p) { return (fac[(int)n]* modInverse(fac[(int)r], p) % p * modInverse(fac[(int)(n-r)], p) % p) % p; } //static int prime[]; //static int dp[]; public static void main(String[] args){ //long sum=0; try { codeforces.solve(); } catch (Exception e) { e.printStackTrace(); } } static long modInverse(long n, long p) { return power(n, p-(long)2, p); } static long power(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y %(long)2!=0) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res%p; } static int find(int x) { // Finds the representative of the set // that x is an element of while(parent[x]!=x) { // if x is not the parent of itself // Then x is not the representative of // his set, x=parent[x]; // so we recursively call Find on its parent // and move i's node directly under the // representative of this set } return x; } static void union(int x, int y) { // Find representatives of two sets int xRoot = find(x), yRoot = find(y); // Elements are in the same set, no need // to unite anything. if (xRoot == yRoot) return; // If x's rank is less than y's rank if (rank[xRoot] < rank[yRoot]) // Then move x under y so that depth // of tree remains less parent[xRoot] = yRoot; // Else if y's rank is less than x's rank else if (rank[yRoot] < rank[xRoot]) // Then move y under x so that depth of // tree remains less parent[yRoot] = xRoot; else // if ranks are the same { // Then move y under x (doesn't matter // which one goes where) parent[yRoot] = xRoot; // And increment the the result tree's // rank by 1 rank[xRoot] = rank[xRoot] + 1; } } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
0a30b8de71eaf98491721d56aa28a265
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.util.*; public class InfinitePrefixes { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(),x=sc.nextInt(); String s=sc.next(); long cnt=0; for(int i=0;i<n;i++) { if(s.charAt(i)=='0')cnt++; else cnt--; } long ans=0; StringBuilder st=new StringBuilder(); if(cnt==0) { for(int i=0;i<n;i++) { if(cnt==x) { ans=-1;break; } if(s.charAt(i)=='0')cnt++; else cnt--; } } else { long tt=cnt; cnt=0; for(int i=0;i<n;i++) { long dif=x-cnt; if(dif%tt==0 && dif/tt>=0)ans++; if(s.charAt(i)=='0')cnt++; else cnt--; } } System.out.println(ans); } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
a5c1b11770bd9599e4a864df84dfbff2
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyScanner in = new MyScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); BInfinitePrefixes solver = new BInfinitePrefixes(); solver.solve(1, in, out); out.close(); } static class BInfinitePrefixes { public void solve(int testNumber, MyScanner in, PrintWriter out) { int T = in.nextInt(); for (int i = 0; i < T; i++) { int n = in.nextInt(); int x = in.nextInt(); String s = in.next(); out.println(solve_case(n, x, s)); } } private int solve_case(int n, int x, String s) { int[] integral = new int[n]; integral[0] = s.charAt(0) == '0' ? 1 : -1; for (int i = 1; i < n; i++) { integral[i] = integral[i - 1] + (s.charAt(i) == '0' ? 1 : -1); } int last = integral[n - 1]; if (last == 0) { for (int i = 0; i < n; i++) { if (integral[i] == x) return -1; } return 0; } int count = 0; for (int i = 0; i < n; i++) { if ((x - integral[i]) % last == 0) { if ((x - integral[i]) / last >= 0) { count++; } } } if (x == 0) count++; return count; } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
d5e4790cd0e395b8c51aea07996fe34d
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.io.*; import java.util.*; public class Main { private static FastScanner in = new FastScanner(); private static FastOutputJ out = new FastOutputJ(); public void run() { int t = in.nextInt(); for (int i = 0; i < t; i++) { int len = in.nextInt(); int want = in.nextInt(); char[] s = in.next().toCharArray(); int[] diff = new int[s.length]; boolean anyEqual = false; long ans = 0; for (int j = 0; j < s.length; j++) { int prev = j == 0 ? 0 : diff[j - 1]; diff[j] = prev + (s[j] == '0' ? 1 : -1); if (diff[j] == want) { anyEqual = true; // ans++; } } int totalDiff = diff[diff.length - 1]; if (want == 0) { ans++; } if (totalDiff == 0) { if (anyEqual) { out.println("-1"); } else { out.println(ans); } continue; } for (int j = 0; j < diff.length; j++) { int a = (want - diff[j]); int b = totalDiff; if (a < 0 && b >= 0 || a > 0 && b <= 0) { continue; } if (b < 0 && a < 0) { a = -a; b = -b; } if (a % b == 0) { ans++; } } out.println(ans); } } public static void main(String[] args) { new Main().run(); out.flush(); out.close(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { this(System.in); } FastScanner(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } FastScanner(File file) { try { br = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } public String nextLine() { try { return br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } } class FastOutputJ { private final BufferedWriter bf; public FastOutputJ(OutputStream outputStream) { bf = new BufferedWriter(new OutputStreamWriter(outputStream)); } public FastOutputJ() { this(System.out); } private void printOne(Object s) { try { bf.write(s.toString()); } catch (IOException e) { throw new RuntimeException(e); } } public void println(Object s) { printOne(s); printOne("\n"); } public void print(Object... os) { printd("", os); } public void printd(String delimiter, Object... os) { for (Object o : os) { printOne(o); printOne(delimiter); } } public void flush() { try { bf.flush(); } catch (IOException e) { throw new RuntimeException(e); } } public void close() { try { bf.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
266b97788d4c8fc6f711af189c583848
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
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; import java.util.*; public class A3 { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } public static void solve(InputReader sc, PrintWriter pw) { int i,j=0; // int t=1; int t=sc.nextInt(); u:while(t-->0){ long n=sc.nextLong(); long x=sc.nextLong(); String s=sc.next(); char ch[]=s.toCharArray(); long p[]=new long[(int)n+1]; HashMap<Long,Long> map=new HashMap<>(); map.put(0L,0L); long min=0,max=0; for(i=1;i<=n;i++){ p[i]=p[i-1]+((ch[i-1]=='0')?1:-1); if(x<0){ p[i]=p[i-1]+((ch[i-1]=='0')?-1:1); } // pw.println("**"+p[i]); min=Math.min(min,p[i]); max=Math.max(max,p[i]); if(map.containsKey(p[i])){ map.put(p[i],map.get(p[i])+1); // pw.println("%"+p[i]+" "+map.get(p[i])); } else{ map.put(p[i],1L); } } x=Math.abs(x); long last=p[(int)n]; if(last==0&&map.containsKey(x)){ pw.println("-1"); } else if(last==0){ pw.println("0"); } else if(last<0&&x>max){ pw.println("0"); } else{ long h=x,c=0; if(h==0) c+=1; if(h>max&&last>0){ long jj=last; h=h%jj+(max-max%jj)+jj; } else if(h<min&&last<0){ long jj=-1*last; long m=min/jj-2; h+=m*jj; // h=h%last+(min-min%last)-2*last; } // pw.println(h+" "+max+" "+min); while((last>0&&h>=min)||(last<0&&h<=max)){ c+=(map.containsKey(h)==true)?map.get(h):0; h-=last; } pw.println(c); } // pw.println(); } } static class Pair implements Comparable<Pair>{ int a; int b; // int i; Pair(int a,int b){ this.a=a; this.b=b; // this.i=i; } public int compareTo(Pair p){ if(a>p.a) return 1; if(a==p.a) return (b-p.b); return -1; } } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long fast_pow(long base,long n,long M){ if(n==0) return 1; if(n==1) return base; long halfn=fast_pow(base,n/2,M); if(n%2==0) return ( halfn * halfn ) % M; else return ( ( ( halfn * halfn ) % M ) * base ) % M; } static long modInverse(long n,long M){ return fast_pow(n,M-2,M); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
c592bdf68c13a4423a69fc727c06b78f
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.util.Scanner; public class B1295 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int t=0; t<T; t++) { int N = in.nextInt(); int X = in.nextInt(); char[] S = in.next().toCharArray(); int[] balance = new int[N+1]; for (int n=0; n<N; n++) { if (S[n] == '0') { balance[n+1] = balance[n]+1; } else { balance[n+1] = balance[n]-1; } } int total = balance[N]; int answer = 0; for (int n=0; n<N; n++) { if (total == 0) { if (balance[n] == X) { answer = -1; } } else { int diff = X-balance[n]; if (diff%total == 0 && diff/total >= 0) { answer++; } } } System.out.println(answer); } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
91a69c4cd1f7c17f61acbb578c906ac9
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
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 * * @author Sparsh Sanchorawala */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader s, PrintWriter w) { int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(), x = s.nextInt(); char[] a = s.next().toCharArray(); int[] pre = new int[n]; pre[0] = 1 - 2 * (a[0] - '0'); for (int i = 1; i < n; i++) pre[i] = pre[i - 1] + 1 - 2 * (a[i] - '0'); if (pre[n - 1] == 0) { boolean check = false; for (int i = 0; i < n; i++) if (pre[i] == x) check = true; if (check) w.println(-1); else w.println(0); continue; } int res = 0; if (x == 0) res++; for (int i = 0; i < n; i++) { long d = x - pre[i]; if (Math.abs(d) % Math.abs(pre[n - 1]) == 0 && d / pre[n - 1] >= 0) res++; } w.println(res); } } } 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 String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
fe0a7a4f7f734ffa2d49b0b90a500154
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { private static final int N_MAX = 100000; public static void solveCase(FastIO io, int testCase) { int N = io.nextInt(); int X = io.nextInt(); char[] S = io.nextLine().toCharArray(); int[] prefix = new int[N + 1]; CountMap<Integer> cm = new CountMap<>(); for (int i = 0; i < N; ++i) { int add = (S[i] == '0') ? 1 : -1; prefix[i + 1] = prefix[i] + add; cm.addCount(prefix[i], 1); } // System.out.format("N = %d, X = %d, prefix = %s\n", N, X, Arrays.toString(prefix)); if (prefix[N] == 0) { if (cm.getCount(X) > 0) { io.println(-1); } else { io.println(0); } return; } int total = 0; for (Map.Entry<Integer, Integer> kvp : cm.entrySet()) { int num = kvp.getKey(); int freq = kvp.getValue(); int diff = X - num; if (diff % prefix[N] != 0) { continue; } int repeats = diff / prefix[N]; if (repeats < 0) { continue; } total += freq; } io.println(total); } private static class CountMap<T> extends HashMap<T, Integer> { public int getCount(T k) { return getOrDefault(k, 0); } public void addCount(T k, int v) { int next = getCount(k) + v; if (next == 0) { remove(k); } else { put(k, next); } } } public static void solve(FastIO io) { int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.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 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; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = 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; } 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 printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
36fd797bceda80090d63e5d8cd3f031f
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { private static final int N_MAX = 100000; public static void solveCase(FastIO io, int testCase) { int N = io.nextInt(); int X = io.nextInt(); char[] S = io.nextLine().toCharArray(); int[] prefix = new int[N + 1]; CountMap<Integer> cm = new CountMap<>(); for (int i = 0; i < N; ++i) { int add = (S[i] == '0') ? 1 : -1; prefix[i + 1] = prefix[i] + add; cm.addCount(prefix[i], 1); } if (prefix[N] == 0) { if (cm.getCount(X) > 0) { io.println(-1); } else { io.println(0); } return; } int total = 0; for (Map.Entry<Integer, Integer> kvp : cm.entrySet()) { int num = kvp.getKey(); int freq = kvp.getValue(); int diff = X - num; if (diff % prefix[N] != 0) { continue; } int repeats = diff / prefix[N]; if (repeats < 0) { continue; } total += freq; } io.println(total); } private static class CountMap<T> extends HashMap<T, Integer> { public int getCount(T k) { return getOrDefault(k, 0); } public void addCount(T k, int v) { int next = getCount(k) + v; if (next == 0) { remove(k); } else { put(k, next); } } } public static void solve(FastIO io) { int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.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 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; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = 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; } 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 printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
fb093199a8b05b63d3223e46e43e4d51
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* I'm working for the day I will surpass you https://www.a2oj.com/Ladder16.html */ import java.util.*; import java.io.*; import java.math.*; public class x1295B { public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); while(T-->0) { st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int X = Integer.parseInt(st.nextToken()); String input = infile.readLine(); int[] arr = new int[N]; for(int i=0; i < N; i++) { if(input.charAt(i) == '1') arr[i]--; else arr[i]++; } int res = 0; int total = 0; for(int i=0; i < N; i++) { total += arr[i]; if(total == X) res++; } if(total == 0) { if(res == 0) sb.append(res); else sb.append(-1); sb.append("\n"); } else { //limited res = 0; int temp = 0; for(int i=0; i < N; i++) { if(pos(total, temp, X)) res++; temp += arr[i]; } sb.append(res+"\n"); } } System.out.print(sb); } public static boolean pos(int total, int small, int X) { if(X == small) return true; if(X-small > 0 && total < 0) return false; if(X-small < 0 && total > 0) return false; int dif = Math.abs(X-small); return dif%Math.abs(total) == 0; } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
e7b41b5ba1f0a22d82b969f36a656457
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); static int MOD = 1000000007; public static void main(String[] args) throws IOException { Main m = new Main(); m.solve(); m.close(); } void close() throws IOException { pw.flush(); pw.close(); br.close(); } int readInt() throws IOException { return Integer.parseInt(br.readLine()); } long readLong() throws IOException { return Long.parseLong(br.readLine()); } int[] readIntLine() throws IOException { String[] tokens = br.readLine().split(" "); int[] A = new int[tokens.length]; for (int i = 0; i < A.length; i++) A[i] = Integer.parseInt(tokens[i]); return A; } long[] readLongLine() throws IOException { String[] tokens = br.readLine().split(" "); long[] A = new long[tokens.length]; for (int i = 0; i < A.length; i++) A[i] = Long.parseLong(tokens[i]); return A; } void solve() throws IOException { int T = readInt(); for (int t = 0; t < T; t++) { int[] nx = readIntLine(); int x = nx[1]; // [-10^9, 10^9] String s = br.readLine(); int balance = 0; Map<Integer, Integer> properPrefixes = new HashMap<>(); properPrefixes.put(0, 1); for (int i = 0; i < s.length() - 1; i++) { if (s.charAt(i) == '0') balance++; else balance--; properPrefixes.put(balance, properPrefixes.getOrDefault(balance, 0) + 1); } balance += s.charAt(s.length() - 1) == '0' ? 1 : -1; if (balance == 0) { if (properPrefixes.containsKey(x)) pw.println("-1"); else pw.println("0"); continue; } int ans = 0; for (int p : properPrefixes.keySet()) { if ((x - p) % balance == 0) { int a = (x - p) / balance; if (a >= 0) { ans += properPrefixes.get(p); } } } pw.println(ans); } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
98c2959179a6a444757c0fdfc2effb64
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.util.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Hello { public static void main (String[] args) throws IOException { // Reader s=new Reader(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pt=new PrintWriter(System.out); int T=Integer.parseInt(br.readLine()); while(T-->0) { String s=(br.readLine()); StringTokenizer st=new StringTokenizer(s," "); int n=Integer.parseInt(st.nextToken()); int x=Integer.parseInt(st.nextToken()); s=br.readLine(); int arr[]=new int[n]; int z=0,o=0; boolean b=false; for(int i=0;i<n;i++) { if(s.charAt(i)=='1') o++; else z++; arr[i]=z-o; if(!b&&arr[i]==x) b=true; } if(arr[n-1]==0&&b) { pt.println(-1); continue; } else if(arr[n-1]==0&&!b) { pt.println(0); continue; } else { int c=0; for(int i=0;i<n;i++) if((x-arr[i])%arr[n-1]==0&&(x-arr[i])/arr[n-1]>=0) c++; if(x==0) c+=1; pt.println(c); } } pt.close(); } static int power(int a,int n, int p) { // Initialize result int res = 1; // Update 'a' if 'a' >= p a = a % p; while (n > 0) { // If n is odd, multiply 'a' with result if ((n & 1) == 1) res = (res * a) % p; // n must be even now n = n >> 1; // n = n/2 a = (a * a) % p; } return res; } // If n is prime, then always returns true, // If n is composite than returns false with // high probability Higher value of k increases // probability of correct result. static boolean isPrime(int n, int k) { // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Try k times while (k > 0) { // Pick a random number in [2..n-2] // Above corner cases make sure that n > 4 int a = 2 + (int)(Math.random() % (n - 4)); // Fermat's little theorem if (power(a, n - 1, n) != 1) return false; k--; } return true; } static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } static int frequency(long arr[], long k) { int c=0; for(int i=0;i<arr.length;i++) if(arr[i]==k) c++; return c; } static void remove(long arr[], long k) { int i; for(i=0;i<arr.length;i++) if(arr[i]==k) { for(int j=i+1;j<arr.length;j++) arr[j-1]=arr[j]; break; } } void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long [n1]; long R[] = new long [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
866d19e491a0a489f7fcabccf5f7d886
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { //Code starts FastReader ip = new FastReader(); OutputStream output = System.out; PrintWriter out = new PrintWriter(output); int t=ip.nextInt(); while(t-->0){ int n=ip.nextInt(); long x=ip.nextLong(); String s=ip.nextLine(); long[] arr =new long[n]; long c=0; for(int i=0;i<s.length();i++){ if(s.charAt(i)=='0') c++; else c--; arr[i]=c; } if(arr[n-1]==0){ boolean f=false; for(int i=0;i<n;i++){ if(arr[i]==x){ f=true; break; } } if(f){ out.println(-1); }else{ out.println(0); } }else{ long bal=arr[n-1]; long count=0; if(x==0){ count++; } for(int i=0;i<n;i++){ if((x-arr[i])%bal==0 && (x-arr[i])/bal>=0){ count++; } } out.println(count); } } out.close(); //Code ends } static class FastReader { BufferedReader br; StringTokenizer st; 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\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
56c397ca5e9a2ff073cae06eabe80435
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.io.*; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Map; public class Infinite_Prefixes_1295B implements Runnable { @Override public void run() { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); //int t = in.nextInt(); // Scanner has functions to read ints, longs, strings, chars, etc. String s = in.nextLine(); int t = Integer.parseInt(s); for (int i = 0; i < t; i++) { s = in.nextLine(); //System.out.println("this is the first line" + s); String[] str = s.split(" "); //System.out.println(str.length); s = in.nextLine(); //System.out.println(s); int res = getRes(Integer.parseInt(str[0]), Integer.parseInt(str[1]), s); w.println(res); } w.flush(); w.close(); } private static int getRes(int n, int x, String s) { int res = 0, l = s.length(); int[] prefix = new int[l + 1]; for (int i = 0; i < s.length(); i++) { prefix[i + 1] = s.charAt(i) == '0' ? prefix[i] + 1 : prefix[i] - 1; } if (prefix[l] == 0) { for (int i = 0; i <= l; i++) { if (prefix[i] == x) return -1; } return 0; } if (x == 0) res++; for (int i = 1; i <= l; i++) { int diff = x - prefix[i]; if (diff % prefix[l] == 0 && diff / prefix[l] >= 0) res++; } return res; } 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 Infinite_Prefixes_1295B(),"Main",1<<27).start(); } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
64bc948168fa6cae36a11d67f7e8d176
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.io.*; import java.util.Random; import java.util.StringTokenizer; public class c { public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); int t = scan.nextInt(); for(int tt = 1; tt <= t; tt++) solver.solve(tt, scan, out); out.close(); } static class Task { public void solve(int testNumber, FastReader scan, PrintWriter out) { int n = scan.nextInt(), x = scan.nextInt(); int[] count = new int[n]; String s = scan.next(); for(int i = 0; i < n; i++) { if(i > 0) count[i] = count[i-1]; if(s.charAt(i) == '0') count[i] += x < 0 ? -1 : 1; else count[i] += x < 0 ? 1 : -1; } x = Math.abs(x); int ans = x == 0 ? 1 : 0; if(count[n-1] < 0) { for(int i = 0; i < n; i++) { if(count[i] >= x && (count[i] - x) % (-count[n-1]) == 0) ans++; } out.println(ans); } else if(count[n-1] == 0) { for(int i = 0; i < n; i++) if(count[i] == x) ans++; out.println(ans == 0 ? 0 : -1); } else { for(int i = 0; i < n; i++) { if(count[i] <= x && (x - count[i]) % count[n-1] == 0) ans++; } out.println(ans); } } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } 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\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
6b78b2a87aa3807a859a0070e764feef
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.io.*; import java.util.Random; import java.util.StringTokenizer; public class c { public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); int t = scan.nextInt(); for(int tt = 1; tt <= t; tt++) solver.solve(tt, scan, out); out.close(); } static class Task { public void solve(int testNumber, FastReader scan, PrintWriter out) { int n = scan.nextInt(), x = scan.nextInt(); int[] count = new int[n], curr = new int[n]; String s = scan.next(); for(int i = 0; i < n; i++) { if(i > 0) count[i] = count[i-1]; if(s.charAt(i) == '0') curr[i] = x < 0 ? -1 : 1; else curr[i] = x < 0 ? 1 : -1; count[i] += curr[i]; } x = Math.abs(x); int ans = x == 0 ? 1 : 0; if(count[n-1] < 0) { for(int i = 0; i < n; i++) { if(count[i] >= x && (count[i] - x) % (-count[n-1]) == 0) ans++; } out.println(ans); } else if(count[n-1] == 0) { for(int i = 0; i < n; i++) if(count[i] == x) ans++; out.println(ans == 0 ? 0 : -1); } else { for(int i = 0; i < n; i++) { if(count[i] <= x && (x - count[i]) % count[n-1] == 0) ans++; } out.println(ans); } } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } 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\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
74db24ff2e1b668867caa4a6e5e5c57a
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
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 * * @author KharYusuf */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BInfinitePrefixes solver = new BInfinitePrefixes(); solver.solve(1, in, out); out.close(); } static class BInfinitePrefixes { public void solve(int testNumber, FastReader s, PrintWriter w) { int tt = s.nextInt(); while (tt-- > 0) { int n = s.nextInt(), x = s.nextInt(); char[] c = s.next().toCharArray(); int[] f = new int[2], tot = new int[n + 1]; for (int i = 0; i < n; i++) { f[c[i] - '0' ]++; tot[i + 1] += tot[i] + (c[i] - '0' == 0 ? 1 : -1); } int dif = f[0] - f[1]; long ans = 0; if (x == 0) ans++; for (int i = 1; i <= n; i++) { long req = x - tot[i]; if (dif == 0) { if (req == 0) { ans = -1; break; } continue; } if (req % dif == 0) { long more = req / dif; if (more >= 0) ans++; } } w.println(ans); } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int 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 String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public 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\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
566324e2292f71ac8dcf7cfce69127e5
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class B { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader s = new FastReader(); static PrintWriter out = new PrintWriter(System.out); private static int[] rai(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); } return arr; } private static int[][] rai(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = s.nextInt(); } } return arr; } private static long[] ral(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextLong(); } return arr; } private static long[][] ral(int n, int m) { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = s.nextLong(); } } return arr; } private static int ri() { return s.nextInt(); } private static long rl() { return s.nextLong(); } private static String rs() { return s.next(); } static int gcd(int a,int b) { if(b==0) { return a; } return gcd(b,a%b); } static boolean isPrime(int n) { //check if n is a multiple of 2 if (n % 2 == 0) return false; //if not, then just check the odds for (int i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } public static void main(String[] args) { StringBuilder ans = new StringBuilder(); int t = ri(); // int t=1; while (t-- > 0) { int n=ri(); long x=rl(); char[] arr=rs().toCharArray(); TreeMap<Integer,Integer> map=new TreeMap<>(); int[] dp=new int[n]; // dp[0]=1; if(arr[0]=='1') { if(x>=0) { dp[0] = -1; } else { dp[0]=1; } } else { if(x>=0) { dp[0] = 1; } else { dp[0]=-1; } } for(int i=1;i<n;i++) { dp[i]=dp[i-1]; if(arr[i]=='0') { if(x>=0) { dp[i]++; }else { dp[i]--; } } else { if(x>=0) { dp[i]--; }else { dp[i]++; } } } if(dp[n-1]==0) { x=Math.abs(x); int flag=0; for(int i:dp) { if(i==x) { flag=1; break; } } if(flag==1) { ans.append("-1\n"); } else { ans.append("0\n"); } continue; } // int max=Integer.MIN_VALUE; // for(int i:dp) // { // System.out.print(i+" "); //// max=Math.max(i,max); // } // System.out.println(); x=Math.abs(x); int last=dp[n-1]; long count=0; if(x==0) { count++; } for(int i:dp) { long val= (x-i); if(val%last==0) { // System.out.println(val); val=val/last; if(val>=0) { count++; } } } ans.append(count).append("\n"); } out.print(ans.toString()); out.flush(); } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
69be9db235536c01ce042743ab3c2222
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.util.*; import java.io.*; public class B { public static void main(String[] args) throws Exception { // FileInputStream inputStream = new FileInputStream("input.txt"); // FileOutputStream outputStream = new FileOutputStream("output.txt"); InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); int t = in.nextInt(); // int t = 1; for (int i = 0 ; i < t ; i++) { solver.solve(1, in, out); } out.close(); } static class Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int x = in.nextInt(); String s = in.next(); int[] bal = new int[n + 1]; if (s.charAt(0) == '0') bal[0] = 1; else bal[0] = -1; for (int i = 1 ; i < n ; i++) { bal[i] = bal[i - 1]; if (s.charAt(i) == '0') bal[i] += 1; else bal[i] -= 1; } bal[n] = bal[n - 1]; if (s.charAt(0) == '0') bal[n] += 1; else bal[n] -= 1; int d = bal[n] - bal[0]; int res = 0; if (d == 0) { for (int i = 0 ; i < n ; i++) { if (bal[i] == x) res += 1; } if (x == 0) res += 1; if (res > 0) res = -1; out.println(res); } else { if (x == 0) res = 1; for (int i = 0 ; i < n ; i++) { int k = (x - bal[i]) % d; int r = (x - bal[i]) / d; if (k == 0 && r >= 0) res += 1; } out.println(res); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
6e4fd4953c96e80ceb83cab04f16b20d
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class InfinitePrefixes 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); } } // if modulo is required set value accordingly public static long[][] matrixMultiply2dL(long t[][],long m[][]) { long res[][]= new long[t.length][m[0].length]; for(int i=0;i<t.length;i++) { for(int j=0;j<m[0].length;j++) { res[i][j]=0; for(int k=0;k<t[0].length;k++) { res[i][j]+=t[i][k]+m[k][j]; } } } return res; } static long combination(long n,long r) { long ans=1; for(long i=0;i<r;i++) { ans=(ans*(n-i))/(i+1); } return ans; } public static void main(String args[]) throws Exception { new Thread(null, new InfinitePrefixes(),"InfinitePrefixes",1<<27).start(); } // **just change the name of class from Main to reuquired** public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int tc=sc.nextInt(); while(tc-->0) { int n=sc.nextInt(); int x=sc.nextInt(); int bal[]= new int[n]; char ch[]= sc.next().toCharArray(); int c0=0,c1=0; for(int i=0;i<n;++i) { if(ch[i]=='1') c1++; else c0++; bal[i]=c0-c1; } boolean f=false; if(bal[n-1]==0) { if(x==0) { f=true; } for(int i=0;i<n;++i) { if(bal[i]==x) { f=true; break; } } } if(f) { w.println("-1"); continue; } if(bal[n-1]==0 && x!=0) { w.println("0"); continue; } //u or f1 is the number of times the complete string is required to get balance as x int ans=0; if(x==0) ans++; for(int i=0;i<n;++i) { int u=(int)Math.ceil((double)(x-bal[i])/(double)bal[n-1]); int f1=(int)Math.floor((double)(x-bal[i])/(double)bal[n-1]); if(u==f1 && u>=0) { ans++; //System.out.println("u:"+u+" index:"+i); } } w.println(ans); } System.out.flush(); w.close(); } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
ba0cc402a81027bba9796cd512db423e
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
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 Jaynil */ 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); BInfinitePrefixes solver = new BInfinitePrefixes(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class BInfinitePrefixes { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int x = in.nextInt(); String s = in.next(); long ans = 0; if (x == 0) ans++; int c = 0; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) { if (s.charAt(i) == '1') c--; else c++; a.add(c); } for (int t : a) { if (c == 0) { if (x == t) ans++; continue; } if ((x - t) % c == 0 && (((x - t) >= 0 && c > 0) || ((x - t) <= 0 && c < 0))) { ans++; } } if (c == 0 && ans >= 1) out.println(-1); else out.println(ans); } } 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\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
da3654fca2b0b8ffba2f08b08bafce5c
train_004.jsonl
1580308500
You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = Integer.parseInt(in.nextLine()); int n, x, k, cs; int[] p; String[] s; for (int i = 0; i < t; i++){ s = in.nextLine().split(" "); n = Integer.parseInt(s[0]); x = Integer.parseInt(s[1]); s = in.nextLine().split(""); k = 0; cs = 0; boolean f; p = new int[n]; for(int j = 0; j < n; j++) { if (s[j].equals("1")) cs--; else cs++; p[j] = cs; } if (cs == 0){ f = false; for(int j = 0; j < n; j++) if(x == p[j] || x == 0) f = true; if (f) System.out.println("-1"); else System.out.println("0"); } else{ if(x == 0){ k = 1; for(int j = 0; j < n; j++) if(((x - p[j]) % cs == 0 && (((x - p[j]) > 0 && cs > 0) || ((x - p[j]) < 0 && cs < 0))) || (p[j] == 0)) k++; } else{ for(int j = 0; j < n; j++){ if((x - p[j]) % cs == 0 && (((x - p[j]) > 0 && cs > 0) || ((x - p[j]) < 0 && cs < 0))) k++; else if (p[j] == x) k++; } } System.out.println(k); //(((x + p[j]) % cs == 0) && (((x + p[j]) > 0 && cs > 0) || ((x + p[j]) < 0 && cs < 0)) && (x + p[j] != 0)) } } } }
Java
["4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01"]
2 seconds
["3\n0\n1\n-1"]
NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.
Java 8
standard input
[ "math", "strings" ]
389be6455476db86a8a5d9d5343ee35a
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) β€” the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases β€” two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) β€” the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.
1,700
Print $$$T$$$ integers β€” one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.
standard output
PASSED
c3084834e2c092f8c6570f2dec8a6c89
train_004.jsonl
1537540500
There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
256 megabytes
import java.util.Scanner; public class zizo { public static void main(String args[]){ Scanner zizo=new Scanner(System.in); int n = zizo.nextInt(); long max = 0; long x = 0; long y = 0; for(int i = 0;i < n; i++){ long a = zizo.nextInt(); long b = zizo.nextInt(); max = Math.max(a+b, max); } System.out.println((max)); } }
Java
["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"]
1 second
["3", "4"]
NoteIllustration for the first example: Illustration for the second example:
Java 8
standard input
[ "geometry", "math" ]
7c41fb6212992d1b3b3f89694b579fea
First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).
900
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
standard output
PASSED
1553b0662a5ac6583b219632b6ee9395
train_004.jsonl
1537540500
There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
256 megabytes
import java.io.*; import java.util.*; /** * * @author Aaryan * AV */ public class Test { /* package codechef; // don't place package name! */ public static void main (String[] args) throws java.lang.Exception{ PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int l =0; int r=0; int max =Integer.MIN_VALUE; while(n-->0){ String str [] = br.readLine().split(" "); int k = Integer.parseInt(str[0]); int m = Integer.parseInt(str[1]); if(k+m>max){ max=k+m; } } out.println(max); out.flush(); } }
Java
["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"]
1 second
["3", "4"]
NoteIllustration for the first example: Illustration for the second example:
Java 8
standard input
[ "geometry", "math" ]
7c41fb6212992d1b3b3f89694b579fea
First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).
900
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
standard output
PASSED
639ec980b0663ed02b67dd223bc344de
train_004.jsonl
1537540500
There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
256 megabytes
//package All_in_all; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; import static java.lang.Math.abs; import static java.lang.Math.round; /** * Created by nikitos on 23.08.17. */ public class otrezok { public StreamTokenizer t; public int nextInt() throws IOException { t.nextToken(); return (int) t.nval; } public String nextString() throws IOException { t.nextToken(); return t.sval; } public void start() throws IOException { t = new StreamTokenizer( new BufferedReader(new InputStreamReader(System.in))); int n = nextInt(); long max = 0; int xM = 0; int yM = 0; for (int i = 0; i < n; i++) { int x = nextInt(); int y = nextInt(); if (x + y > max) { max = x + y; xM = x; yM = y; } } System.out.println(xM + yM); } public static void main(String[] args) throws IOException { new otrezok().start(); } }
Java
["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"]
1 second
["3", "4"]
NoteIllustration for the first example: Illustration for the second example:
Java 8
standard input
[ "geometry", "math" ]
7c41fb6212992d1b3b3f89694b579fea
First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).
900
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
standard output
PASSED
470aea938927dd0604312231c6384624
train_004.jsonl
1537540500
There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
256 megabytes
import java.util.Scanner; public class LinearArray { static class Point { int x=0,y=0; Point(int xx,int yy){ x=xx;y=yy; } } public static void main(String[] args) { Scanner sc= new Scanner(System.in); // int n=sc.nextInt(); // int fn=0; // int sn=0; // for(int i=0;i<n;i++) { // n--; // fn++; // if(fn%3!=0)break; // } // for(int i=0;i<n;i++) { // n--; // sn++; // if(sn%3!=0&&n%3!=0)break; // } // System.out.println(fn+" "+sn+" "+n); int n=sc.nextInt(); Point maxx=new Point(0, 0); Point maxy=new Point(0, 0); // for(int i=0;i<n;i++) { // Point p=new Point(sc.nextInt(), sc.nextInt()); // if(p.x>maxx.x)maxx=p;else maxx=(p.x==maxx.x)?(p.y>maxx.y)?p:maxx:maxx; // if(p.y>maxy.y)maxy=p;else maxy=(p.y==maxy.y)?(p.x>maxy.x)?p:maxy:maxy; // } // System.out.println(maxx.x+" "+maxx.y+" "+maxy.x+" "+maxy.y); // Point e=(maxx.x>maxy.y)?maxx:maxy; // System.out.println(e.x+" " +e.y); // int a=e.x+e.y; int max=0; for(int i=0;i<n;i++) { Point p=new Point(sc.nextInt(), sc.nextInt()); int sum=p.x+p.y; if(sum>max)max=sum; } System.out.println(max); } }
Java
["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"]
1 second
["3", "4"]
NoteIllustration for the first example: Illustration for the second example:
Java 8
standard input
[ "geometry", "math" ]
7c41fb6212992d1b3b3f89694b579fea
First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).
900
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
standard output
PASSED
8aeb4f7c7fa5da8eecfbaa0796d39016
train_004.jsonl
1537540500
There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Andrei Chugunov */ public class Main { private static class Solution { private void solve(FastScanner in, PrintWriter out) { int n = in.nextInt(); int[][] coords = new int[n][2]; //y = -x + b // b = y + x int max = 0; for (int i = 0; i < n; i++) { int x = in.nextInt(); int y = in.nextInt(); max = Math.max(max, x + y); } out.println(max); } } public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); Solution solver = new Solution(); solver.solve(in, out); out.flush(); //out.close(); } private static class FastScanner { private BufferedReader br; private StringTokenizer st; FastScanner(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream), 32768); st = null; } private String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"]
1 second
["3", "4"]
NoteIllustration for the first example: Illustration for the second example:
Java 8
standard input
[ "geometry", "math" ]
7c41fb6212992d1b3b3f89694b579fea
First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).
900
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
standard output
PASSED
938577524001ebf543e0436cbfbe03fe
train_004.jsonl
1537540500
There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scar= new Scanner(System.in); int n=scar.nextInt(); int c=0,max=0; int [][]a =new int [n][2]; for (int i=0;i<n;i++){ a[i][0]=scar.nextInt(); a[i][1]=scar.nextInt(); } for (int i=0;i<=n-1;i++){ c=a[i][0]+a[i][1]; if (c>max){ max=c; } } System.out.println(max); } }
Java
["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"]
1 second
["3", "4"]
NoteIllustration for the first example: Illustration for the second example:
Java 8
standard input
[ "geometry", "math" ]
7c41fb6212992d1b3b3f89694b579fea
First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).
900
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
standard output
PASSED
061d4f84699d464b4845b91e87d93229
train_004.jsonl
1537540500
There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
256 megabytes
import java.util.*; import java.io.*; public class Main { static long gcd(long a,long b) { //System.out.println("a "+a+" b "+b); if(b==0) { return a; } return gcd(b,a%b); } static void debug(Object... O) { System.out.println(Arrays.deepToString(O)); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static class Pair implements Comparable<Pair>{ int x,y; public Pair(int t,int i) { x = t; y = i; } public int compareTo(Pair p) { if(this.x != p.x) { return p.x-this.x; } return p.y-this.y; } } public static void main(String[] args) throws IOException{ //Scanner sc = new Scanner(System.in); Reader sc = new Reader(); int n = sc.nextInt(); long max = -1; while(n-- > 0) { long x = sc.nextLong(); long y = sc.nextLong(); max = Math.max(max, (x+y)); } System.out.println(max); } }
Java
["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"]
1 second
["3", "4"]
NoteIllustration for the first example: Illustration for the second example:
Java 8
standard input
[ "geometry", "math" ]
7c41fb6212992d1b3b3f89694b579fea
First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).
900
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
standard output
PASSED
d6118f47c6cc051053ceedfd5f6ea394
train_004.jsonl
1537540500
There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.lang.*; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main { private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int max = 0; for (int i = 0; i < n; i++) { int x = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int y = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); max = Math.max(max, x + y); } System.out.println(max); } }
Java
["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"]
1 second
["3", "4"]
NoteIllustration for the first example: Illustration for the second example:
Java 8
standard input
[ "geometry", "math" ]
7c41fb6212992d1b3b3f89694b579fea
First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).
900
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
standard output
PASSED
b9c520bacddc372504258e18583780e7
train_004.jsonl
1537540500
There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class B_CoverPoints { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int points = Integer.valueOf(br.readLine()); int answer = 0; for (int i = 0; i < points; i++) { String[] input = br.readLine().split(" "); int x = Integer.valueOf(input[0]); int y = Integer.valueOf(input[1]); if(answer < (x+y)){ answer = x+y; } } System.out.println(answer); } }
Java
["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"]
1 second
["3", "4"]
NoteIllustration for the first example: Illustration for the second example:
Java 8
standard input
[ "geometry", "math" ]
7c41fb6212992d1b3b3f89694b579fea
First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).
900
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
standard output
PASSED
80e2d0f5706ad29a82ca2b6abba621dd
train_004.jsonl
1537540500
There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
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(); long x,y; long max = 0; while(n--!=0){ x = in.nextLong(); y = in.nextLong(); max = (x+y > max)?x+y:max; } System.out.println(max); } }
Java
["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"]
1 second
["3", "4"]
NoteIllustration for the first example: Illustration for the second example:
Java 8
standard input
[ "geometry", "math" ]
7c41fb6212992d1b3b3f89694b579fea
First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).
900
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
standard output
PASSED
9b53783844290c2eeb6b9152935825ca
train_004.jsonl
1537540500
There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
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(); long x,y; long max = 0; while(n--!=0){ x = in.nextLong(); y = in.nextLong(); if(x+y > max) max = x+y; } System.out.println(max); } }
Java
["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"]
1 second
["3", "4"]
NoteIllustration for the first example: Illustration for the second example:
Java 8
standard input
[ "geometry", "math" ]
7c41fb6212992d1b3b3f89694b579fea
First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).
900
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
standard output
PASSED
fd0e7b640e4b52719f4a0fa5920a3a84
train_004.jsonl
1537540500
There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; import java.math.*; import static java.lang.Integer.*; import static java.lang.Double.*; import java.lang.Math.*; public class cover_points { public static void main(String[] args) throws Exception { new cover_points().run(); } public void run() throws Exception { FastIO file = new FastIO(); int n = file.nextInt(); long ans = 0; for (int i = 0; i < n; i++) ans = Math.max(ans, file.nextLong() + file.nextLong()); System.out.println(ans); } public static class FastIO { BufferedReader br; StringTokenizer st; public FastIO() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static long pow(long n, long p, long mod) { if (p == 0) return 1; if (p == 1) return n % mod; if (p % 2 == 0) { long temp = pow(n, p / 2, mod); return (temp * temp) % mod; } else { long temp = pow(n, (p - 1) / 2, mod); temp = (temp * temp) % mod; return (temp * n) % mod; } } public static long pow(long n, long p) { if (p == 0) return 1; if (p == 1) return n; if (p % 2 == 0) { long temp = pow(n, p / 2); return (temp * temp); } else { long temp = pow(n, (p - 1) / 2); temp = (temp * temp); return (temp * n); } } public static long gcd(long x, long y) { if (x == 0) return y; else return gcd(y % x, x); } 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; } }
Java
["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"]
1 second
["3", "4"]
NoteIllustration for the first example: Illustration for the second example:
Java 8
standard input
[ "geometry", "math" ]
7c41fb6212992d1b3b3f89694b579fea
First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).
900
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
standard output