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
51c65389219b231cf24403101ee18b13
train_002.jsonl
1526574900
You're given a tree with $$$n$$$ vertices.Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.
256 megabytes
import java.io.*; import java.util.*; public class TaskC { public static void main(String[] args) { new TaskC(System.in, System.out); } static class Solver implements Runnable { int n, ctr, answer; int[] ans; boolean[] poss; List<Integer> leaves; Set<Integer>[] adj; // BufferedReader in; InputReader in; PrintWriter out; void solve() throws IOException { n = in.nextInt(); leaves = new ArrayList<>(); adj = new Set[n]; ans = new int[2]; poss = new boolean[2]; Arrays.fill(poss, true); for (int i = 0; i < n; i++) adj[i] = new HashSet<>(); for (int i = 1; i < n; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; adj[u].add(v); adj[v].add(u); } if (n % 2 == 1) { out.println(-1); return; } int x = dfs(0, -1); ctr++; // int y = dfs(adj[0].iterator().next(), -1); out.println(answer); // System.out.println("x : " + x + ", y : " + y); // System.out.println("ans ; " + Arrays.toString(ans)); // System.out.println("poss : " + Arrays.toString(poss)); /* if (x == 0 && poss[0]) out.println(ans[0] - 1); else if (y == 0 && poss[1]) out.println(ans[1] - 1); else out.println(-1);*/ } int dfs(int node, int par) { int num = 0; for (int x : adj[node]) { if (x != par) { int num_nodes = dfs(x, node); if (num_nodes % 2 == 0) answer++; else num += num_nodes; } } return num + 1; } public Solver(InputReader in, PrintWriter out) { this.in = in; this.out = out; } @Override public void run() { try { solve(); } catch (IOException e) { e.printStackTrace(); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int arraySize) { int array[] = new int[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextInt(); return array; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } long result = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); result *= 10; result += c & 15; c = read(); } while (!isSpaceChar(c)); return result * sign; } public long[] nextLongArray(int arraySize) { long array[] = new long[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextLong(); return array; } public float nextFloat() { float result, div; byte c; result = 0; div = 1; c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean isNegative = (c == '-'); if (isNegative) c = (byte) read(); do { result = result * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') result += (c - '0') / (div *= 10); if (isNegative) return -result; return result; } public double nextDouble() { double ret = 0, div = 1; byte c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean neg = (c == '-'); if (neg) c = (byte) read(); do { ret = ret * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (!isNewLine(c)); return result.toString(); } public boolean isNewLine(int c) { return c == '\n'; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public void close() { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } public InputReader(InputStream stream) { this.stream = stream; } } static class CMath { static long power(long number, long power) { if (number == 1 || number == 0 || power == 0) return 1; if (power == 1) return number; if (power % 2 == 0) return power(number * number, power / 2); else return power(number * number, power / 2) * number; } static long modPower(long number, long power, long mod) { if (number == 1 || number == 0 || power == 0) return 1; number = mod(number, mod); if (power == 1) return number; long square = mod(number * number, mod); if (power % 2 == 0) return modPower(square, power / 2, mod); else return mod(modPower(square, power / 2, mod) * number, mod); } static long moduloInverse(long number, long mod) { return modPower(number, mod - 2, mod); } static long mod(long number, long mod) { return number - (number / mod) * mod; } static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } static long min(long... arr) { long min = arr[0]; for (int i = 1; i < arr.length; i++) min = Math.min(min, arr[i]); return min; } static long max(long... arr) { long max = arr[0]; for (int i = 1; i < arr.length; i++) max = Math.max(max, arr[i]); return max; } static int min(int... arr) { int min = arr[0]; for (int i = 1; i < arr.length; i++) min = Math.min(min, arr[i]); return min; } static int max(int... arr) { int max = arr[0]; for (int i = 1; i < arr.length; i++) max = Math.max(max, arr[i]); return max; } } static class Utils { static boolean nextPermutation(int[] arr) { for (int a = arr.length - 2; a >= 0; --a) { if (arr[a] < arr[a + 1]) { for (int b = arr.length - 1; ; --b) { if (arr[b] > arr[a]) { int t = arr[a]; arr[a] = arr[b]; arr[b] = t; for (++a, b = arr.length - 1; a < b; ++a, --b) { t = arr[a]; arr[a] = arr[b]; arr[b] = t; } return true; } } } } return false; } } public TaskC(InputStream inputStream, OutputStream outputStream) { // uncomment below line to change to BufferedReader // BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Thread thread = new Thread(null, new Solver(in, out), "TaskC", 1 << 29); try { thread.start(); thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } finally { in.close(); out.flush(); out.close(); } } }
Java
["4\n2 4\n4 1\n3 1", "3\n1 2\n1 3", "10\n7 1\n8 4\n8 10\n4 7\n6 5\n9 3\n3 5\n2 10\n2 5", "2\n1 2"]
1 second
["1", "-1", "4", "0"]
NoteIn the first example you can remove the edge between vertices $$$1$$$ and $$$4$$$. The graph after that will have two connected components with two vertices in each.In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is $$$-1$$$.
Java 8
standard input
[ "dp", "greedy", "graphs", "dfs and similar", "trees" ]
711896281f4beff55a8826771eeccb81
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) denoting the size of the tree. The next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ ($$$1 \le u, v \le n$$$) each, describing the vertices connected by the $$$i$$$-th edge. It's guaranteed that the given edges form a tree.
1,500
Output a single integer $$$k$$$ β€” the maximum number of edges that can be removed to leave all connected components with even size, or $$$-1$$$ if it is impossible to remove edges in order to satisfy this property.
standard output
PASSED
f571db1515da281fbe348ede3815ed74
train_002.jsonl
1526574900
You're given a tree with $$$n$$$ vertices.Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.
256 megabytes
import java.io.*; import java.util.*; public class A { static final boolean stdin = true; static final String filename = ""; static FastScanner br; static PrintWriter pw; public static void main(String[] args) throws IOException { if (stdin) { br = new FastScanner(); pw = new PrintWriter(new OutputStreamWriter(System.out)); } else { br = new FastScanner(filename + ".in"); pw = new PrintWriter(new FileWriter(filename + ".out")); } Solver solver = new Solver(); solver.solve(br, pw); } static class Solver { static boolean[] visited; static int[] children; static ArrayList<LinkedList<Integer>> adj; static int counter = -1; public void solve(FastScanner br, PrintWriter pw) throws IOException { int n = br.nextInt(); //odd can't be split properly if (n % 2 == 1) { pw.println(-1); } else { //for initial visiting in totChildren visited = new boolean[n];// 0 indexed //the total nodes in subtree including subroot children = new int[n]; //adjacency path list adj = new ArrayList<LinkedList<Integer>>(); //initialization for (int i = 0; i < n; i++) { adj.add(new LinkedList<Integer>()); children[i] = 0; } //storing the paths for (int i = 0; i < n - 1; i++) { int a = br.nextInt() - 1; int b = br.nextInt() - 1; adj.get(a).add(b); adj.get(b).add(a); } //recur totChildren(0); //output pw.println(counter); } pw.close(); } static int totChildren(int loc) { // visit it visited[loc] = true; // children from here is the sum of the children below int out = 1; for (int i = 0; i < adj.get(loc).size(); i++) { if (!visited[adj.get(loc).get(i)]) { children[adj.get(loc).get(i)] += totChildren(adj.get(loc).get(i)); out += children[adj.get(loc).get(i)]; } } if(out%2==0){ counter++; } return out; } } //sort by b then a static class Pair implements Comparable<Pair> { int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Pair o) { if (b != o.b) return b - o.b; return a - o.a; } } // fastscanner class static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4\n2 4\n4 1\n3 1", "3\n1 2\n1 3", "10\n7 1\n8 4\n8 10\n4 7\n6 5\n9 3\n3 5\n2 10\n2 5", "2\n1 2"]
1 second
["1", "-1", "4", "0"]
NoteIn the first example you can remove the edge between vertices $$$1$$$ and $$$4$$$. The graph after that will have two connected components with two vertices in each.In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is $$$-1$$$.
Java 8
standard input
[ "dp", "greedy", "graphs", "dfs and similar", "trees" ]
711896281f4beff55a8826771eeccb81
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) denoting the size of the tree. The next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ ($$$1 \le u, v \le n$$$) each, describing the vertices connected by the $$$i$$$-th edge. It's guaranteed that the given edges form a tree.
1,500
Output a single integer $$$k$$$ β€” the maximum number of edges that can be removed to leave all connected components with even size, or $$$-1$$$ if it is impossible to remove edges in order to satisfy this property.
standard output
PASSED
87f63a672e8b736513c8fedf795ebe60
train_002.jsonl
1526574900
You're given a tree with $$$n$$$ vertices.Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.
256 megabytes
import java.io.*; import java.util.*; public class A { static final boolean stdin = true; static final String filename = ""; static FastScanner br; static PrintWriter pw; public static void main(String[] args) throws IOException { if (stdin) { br = new FastScanner(); pw = new PrintWriter(new OutputStreamWriter(System.out)); } else { br = new FastScanner(filename + ".in"); pw = new PrintWriter(new FileWriter(filename + ".out")); } Solver solver = new Solver(); solver.solve(br, pw); } static class Solver { static boolean[] visited; static int[] children; static ArrayList<LinkedList<Integer>> adj; static int counter = 0; static boolean ever = false; public void solve(FastScanner br, PrintWriter pw) throws IOException { int n = br.nextInt(); //odd can't be split properly if (n % 2 == 1) { pw.println(-1); } else { //for initial visiting in totChildren visited = new boolean[n];// 0 indexed //the total nodes in subtree including subroot children = new int[n]; //adjacency path list adj = new ArrayList<LinkedList<Integer>>(); //initialization for (int i = 0; i < n; i++) { adj.add(new LinkedList<Integer>()); children[i] = 0; } //storing the paths for (int i = 0; i < n - 1; i++) { int a = br.nextInt() - 1; int b = br.nextInt() - 1; adj.get(a).add(b); adj.get(b).add(a); } // for (int i = 0; i < adj.size(); i++) { // for (int j = 0; j < adj.get(i).size(); j++) { // System.out.println("from " + (i + 1) + " to " + (adj.get(i).get(j) + 1)); // } // } // System.out.println("____"); //total nodes (essentially n) totChildren(0); // for (int i = 0; i < adj.size(); i++) { // for (int j = 0; j < adj.get(i).size(); j++) { // if (children[i] - children[j] % 2 == 0 && children[j] % 2 == 0 // && children[i] - children[j] != 0) { // counter++; // children[i] -= children[j]; // } // System.out.println("from " + (i + 1) + " to " + (adj.get(i).get(j) + 1)); // } // } // for (int i = 0; i < children.length; i++) { // System.out.println("children of " + (i + 1) + ": " + children[i]); // } // System.out.println(); //reset bools visited = new boolean[n]; for(int i = 1; i < n; i++){ if(children[i]%2==0) counter++; } //dfs through the tree and count possible edge removals //deefus(0); //output pw.println(counter); } pw.close(); } /* static void deefus(int loc) { visited[loc] = true; //for each of the nodes this points too for (int i = 0; i < adj.get(loc).size(); i++) { // System.out.println(adj.get(loc).get(i) + 1); if(!visited[adj.get(loc).get(i)]){ //if you can split this from the root, inc count and update the parent children if ((children[adj.get(loc).get(i)]) % 2 == 0) { counter++; } //go deeper into the tree deefus(adj.get(loc).get(i)); } } } */ static int totChildren(int loc) { // visit it visited[loc] = true; // paths // for (int i = 0; i < adj.size(); i++) { // for (int j = 0; j < adj.get(i).size(); j++) { // System.out.println("from " + (i + 1) + " to " + (adj.get(i).get(j) + 1)); // } // } // System.out.println(loc + 1 + " ^^^"); // children from here is the sum of the children below int out = 1; for (int i = 0; i < adj.get(loc).size(); i++) { // System.out.println(adj.get(loc).get(i) + 1); if (!visited[adj.get(loc).get(i)]) { // System.out.println("from here to " + (adj.get(loc).get(i) + 1)); children[adj.get(loc).get(i)] += totChildren(adj.get(loc).get(i)); out += children[adj.get(loc).get(i)]; } } return out; } } //sort by b then a static class Pair implements Comparable<Pair> { int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Pair o) { if (b != o.b) return b - o.b; return a - o.a; } } // fastscanner class static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4\n2 4\n4 1\n3 1", "3\n1 2\n1 3", "10\n7 1\n8 4\n8 10\n4 7\n6 5\n9 3\n3 5\n2 10\n2 5", "2\n1 2"]
1 second
["1", "-1", "4", "0"]
NoteIn the first example you can remove the edge between vertices $$$1$$$ and $$$4$$$. The graph after that will have two connected components with two vertices in each.In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is $$$-1$$$.
Java 8
standard input
[ "dp", "greedy", "graphs", "dfs and similar", "trees" ]
711896281f4beff55a8826771eeccb81
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) denoting the size of the tree. The next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ ($$$1 \le u, v \le n$$$) each, describing the vertices connected by the $$$i$$$-th edge. It's guaranteed that the given edges form a tree.
1,500
Output a single integer $$$k$$$ β€” the maximum number of edges that can be removed to leave all connected components with even size, or $$$-1$$$ if it is impossible to remove edges in order to satisfy this property.
standard output
PASSED
904437a1fc7603da4565038f38f4c282
train_002.jsonl
1526574900
You're given a tree with $$$n$$$ vertices.Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class C982 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); ArrayList<Integer> al[] = new ArrayList[t]; for (int i = 0; i < t; i++) { al[i] = new ArrayList<>(); } int tt = t - 1; while (tt-- > 0) { String s[] = br.readLine().split(" "); int x = Integer.parseInt(s[0]) - 1; int y = Integer.parseInt(s[1]) - 1; al[x].add(y); al[y].add(x); } int count[] = new int[t]; System.out.println(t % 2 == 1 ? -1 : dfs(al, 0, count, 0)); } static int ans = 0; public static int dfs(ArrayList<Integer> arr[], int start, int count[], int parent) { count[start] = 1; for (int x : arr[start]) { if (x != parent) { dfs(arr, x, count, start); count[start] += count[x]; if (count[x] % 2 == 0) ans++; } } return ans; } }
Java
["4\n2 4\n4 1\n3 1", "3\n1 2\n1 3", "10\n7 1\n8 4\n8 10\n4 7\n6 5\n9 3\n3 5\n2 10\n2 5", "2\n1 2"]
1 second
["1", "-1", "4", "0"]
NoteIn the first example you can remove the edge between vertices $$$1$$$ and $$$4$$$. The graph after that will have two connected components with two vertices in each.In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is $$$-1$$$.
Java 8
standard input
[ "dp", "greedy", "graphs", "dfs and similar", "trees" ]
711896281f4beff55a8826771eeccb81
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) denoting the size of the tree. The next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ ($$$1 \le u, v \le n$$$) each, describing the vertices connected by the $$$i$$$-th edge. It's guaranteed that the given edges form a tree.
1,500
Output a single integer $$$k$$$ β€” the maximum number of edges that can be removed to leave all connected components with even size, or $$$-1$$$ if it is impossible to remove edges in order to satisfy this property.
standard output
PASSED
19b7e3dd7dfe15ff7bef9c47f951f2e6
train_002.jsonl
1286002800
A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: the 2nd is on the same vertical line as the 1st, but x squares up the 3rd is on the same vertical line as the 1st, but x squares down the 4th is on the same horizontal line as the 1st, but x squares left the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one.Your task is to find the constellation with index k by the given Berland's star map.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class d32 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int r = in.nextInt(), c = in.nextInt(); boolean[][] map = new boolean[r][c]; int idx = in.nextInt(); for (int i = 0; i < r; i++) { String here = in.next(); for (int j = 0; j < c; j++) { map[i][j] = here.charAt(j) == '*'; } } int[][] delta = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; int maxS = (Math.min(r, c) - 1) / 2; for (int s = 1; s <= maxS; s++) { int maxr = r - s; for (int i = s; i < maxr; i++) { int maxc = c - s; for (int j = s; j < maxc; j++) { if (map[i][j]) { boolean works = true; for (int d = 0; d < delta.length; d++) { int nr = i + (delta[d][0] * s); int nc = j + (delta[d][1] * s); works &= map[nr][nc]; } if (works) { if (--idx == 0) { System.out.printf("%d %d\n", 1 + i, 1 + j); for (int d = 0; d < delta.length; d++) { int nr = i + (delta[d][0] * s); int nc = j + (delta[d][1] * s); System.out.printf("%d %d\n", nr+1, nc+1); } return; } } } } } } System.out.println(-1); } }
Java
["5 6 1\n....*.\n...***\n....*.\n..*...\n.***..", "5 6 2\n....*.\n...***\n....*.\n..*...\n.***..", "7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*..."]
2 seconds
["2 5\n1 5\n3 5\n2 4\n2 6", "-1", "4 4\n1 4\n7 4\n4 1\n4 7"]
null
Java 7
standard input
[ "implementation" ]
f13be8bcb3291ffcc555a268f421bf3a
The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty.
1,600
If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right.
standard output
PASSED
229b624f45de9893616a4ee31ed63b27
train_002.jsonl
1286002800
A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: the 2nd is on the same vertical line as the 1st, but x squares up the 3rd is on the same vertical line as the 1st, but x squares down the 4th is on the same horizontal line as the 1st, but x squares left the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one.Your task is to find the constellation with index k by the given Berland's star map.
256 megabytes
import java.util.List; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Zyflair Griffane */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; PandaScanner in = new PandaScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); D solver = new D(); solver.solve(1, in, out); out.close(); } } class D { final int BIAS = 300; public void solve(int testNumber, PandaScanner in, PrintWriter out) { boolean[][] star = new boolean[900][900]; int h = in.nextInt(); int w = in.nextInt(); int k = in.nextInt(); List<Star> lst = new ArrayList<Star>(); for (int i = 0; i < h; i++) { char[] c = in.next().toCharArray(); for (int j = 0; j < w; j++) { star[i + BIAS][j + BIAS] = c[j] == '*'; if (star[i + BIAS][j + BIAS]) { lst.add(new Star(i + BIAS, j + BIAS)); } } } Collections.sort(lst); for (int r = 1; r < 150; r++) { for (Star s: lst) { int x = s.x; int y = s.y; if (star[x - r][y] && star[x + r][y] && star[x][y - r] && star[x][y + r]) { if (k == 1) { x -= BIAS - 1; y -= BIAS - 1; out.println(x + " " + y); out.println((x - r) + " " + y); out.println((x + r) + " " + y); out.println(x + " " + (y - r)); out.println(x + " " + (y + r)); return; } else { k--; } } } } out.println("-1"); } public class Star implements Comparable<Star> { int x; int y; public Star(int x, int y) { this.x = x; this.y = y; } public int compareTo(Star o) { return x != o.x ? x - o.x : y - o.y; } } } class PandaScanner { public BufferedReader br; public StringTokenizer st; public InputStream in; public PandaScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(this.in = in)); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { return null; } } public String next() { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine().trim()); return next(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["5 6 1\n....*.\n...***\n....*.\n..*...\n.***..", "5 6 2\n....*.\n...***\n....*.\n..*...\n.***..", "7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*..."]
2 seconds
["2 5\n1 5\n3 5\n2 4\n2 6", "-1", "4 4\n1 4\n7 4\n4 1\n4 7"]
null
Java 7
standard input
[ "implementation" ]
f13be8bcb3291ffcc555a268f421bf3a
The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty.
1,600
If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right.
standard output
PASSED
8e3187bedad01ac87f677f22f62ab084
train_002.jsonl
1286002800
A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: the 2nd is on the same vertical line as the 1st, but x squares up the 3rd is on the same vertical line as the 1st, but x squares down the 4th is on the same horizontal line as the 1st, but x squares left the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one.Your task is to find the constellation with index k by the given Berland's star map.
256 megabytes
import java.util.*; import java.io.*; public class P32D { static class Con implements Comparable<Con> { final int r, c, d; Con(int r, int c, int d) { this.r=r; this.c=c; this.d=d; } public int compareTo(Con that) { if (d != that.d) return Integer.compare(d,that.d); if (r != that.r) return Integer.compare(r,that.r); return Integer.compare(c,that.c); } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String tmp[] = br.readLine().split(" "); int R = Integer.parseInt(tmp[0]); int C = Integer.parseInt(tmp[1]); int K = Integer.parseInt(tmp[2]); char[][] grid = new char[R][]; for (int r=0; r<R; r++) grid[r] = br.readLine().toCharArray(); for (int d=1; d<R && d<C; d++) for (int r=0; r<R && r+d<R; r++) if (r-d>=0) for (int c=0; c<C && c+d<C; c++) if (c-d>=0) if (grid[r][c] == '*' && grid[r-d][c] == '*' && grid[r+d][c] == '*' && grid[r][c-d] == '*' && grid[r][c+d] == '*') if (--K == 0) { System.out.printf("%d %d\n",r+1,c+1); System.out.printf("%d %d\n",r-d+1,c+1); System.out.printf("%d %d\n",r+d+1,c+1); System.out.printf("%d %d\n",r+1,c-d+1); System.out.printf("%d %d\n",r+1,c+d+1); return; } System.out.println(-1); } }
Java
["5 6 1\n....*.\n...***\n....*.\n..*...\n.***..", "5 6 2\n....*.\n...***\n....*.\n..*...\n.***..", "7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*..."]
2 seconds
["2 5\n1 5\n3 5\n2 4\n2 6", "-1", "4 4\n1 4\n7 4\n4 1\n4 7"]
null
Java 7
standard input
[ "implementation" ]
f13be8bcb3291ffcc555a268f421bf3a
The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty.
1,600
If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right.
standard output
PASSED
50cc6e3a30f965834390b79b630fd0cf
train_002.jsonl
1286002800
A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: the 2nd is on the same vertical line as the 1st, but x squares up the 3rd is on the same vertical line as the 1st, but x squares down the 4th is on the same horizontal line as the 1st, but x squares left the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one.Your task is to find the constellation with index k by the given Berland's star map.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class D implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer st; Random rnd; boolean[][] field; final int[] dx = {-1, 1, 0, 0}; final int[] dy = {0, 0, -1, 1}; boolean check(int n, int m, int x, int y, int r) { if(!field[x][y]) { return false; } for(int k = 0; k < 4; k++) { int nx = x + dx[k] * r, ny = y + dy[k] * r; if(nx < 0 || ny < 0 || nx >= n || ny >= m || !field[nx][ny]) { return false; } } return true; } void printAns(int x, int y, int r) { ++x; ++y; out.println(x + " " + y); for(int k = 0; k < 4; k++) { int nx = x + dx[k] * r, ny = y + dy[k] * r; out.println(nx + " " + ny); } } void solve() throws IOException { int n = nextInt(), m = nextInt(), num = nextInt(); field = new boolean[n][m]; for(int i = 0; i < n; i++) { String s = nextToken(); for(int j = 0; j < m; j++) { field[i][j] = s.charAt(j) == '*'; } } for(int k = 1; k <= Math.min(n, m); k++) { for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(check(n, m, i, j, k)) { --num; if(num == 0) { printAns(i, j, k); return; } } } } } out.println(-1); } public static void main(String[] args) { final boolean oldChecker = false; if(oldChecker) { new Thread(null, new D(), "yarrr", 1 << 24).start(); } else { new D().run(); } } public void run() { try { final String className = this.getClass().getName().toLowerCase(); try { in = new BufferedReader(new FileReader(className + ".in")); out = new PrintWriter(new FileWriter(className + ".out")); } catch (FileNotFoundException e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } rnd = new Random(); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(42); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["5 6 1\n....*.\n...***\n....*.\n..*...\n.***..", "5 6 2\n....*.\n...***\n....*.\n..*...\n.***..", "7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*..."]
2 seconds
["2 5\n1 5\n3 5\n2 4\n2 6", "-1", "4 4\n1 4\n7 4\n4 1\n4 7"]
null
Java 7
standard input
[ "implementation" ]
f13be8bcb3291ffcc555a268f421bf3a
The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty.
1,600
If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right.
standard output
PASSED
f2e3b8420fc78812c15e9a155fba5645
train_002.jsonl
1286002800
A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: the 2nd is on the same vertical line as the 1st, but x squares up the 3rd is on the same vertical line as the 1st, but x squares down the 4th is on the same horizontal line as the 1st, but x squares left the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one.Your task is to find the constellation with index k by the given Berland's star map.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class D_Round_32_Div2 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int m = in.nextInt(); int h = in.nextInt(); char[][] data = new char[n][m]; for (int i = 0; i < n; i++) { data[i] = in.next().toCharArray(); } int[] count = new int[Math.min(n, m) + 1]; int total = 0; for (int i = 1; i < n - 1; i++) { for (int j = 1; j < m - 1; j++) { if (data[i][j] == '*') { for (int k = 1; k <= Math.min(n, m); k++) { if (i - k < 0 || i + k >= n || j - k < 0 || j + k >= m) { break; } if (data[i - k][j] == data[i + k][j] && data[i][j - k] == data[i][j + k] && data[i][j - k] == data[i - k][j] && data[i][j - k] == data[i][j]) { count[k]++; total++; } } } } } if (total < h) { out.println(-1); } else { int last = 0; int k = 0; for (int i = 1; i < count.length; i++) { if (last + count[i] >= h) { k = i; h -= last; break; } last += count[i]; } //System.out.println(k + " " + h); for (int i = 1; i < n - 1 && h > 0; i++) { for (int j = 1; j < m - 1 && h > 0; j++) { //System.out.println(i + " " + j); if (i - k < 0 || i + k >= n || j - k < 0 || j + k >= m) { continue; } if (data[i][j] == '*' && data[i - k][j] == data[i + k][j] && data[i][j - k] == data[i][j + k] && data[i][j - k] == data[i - k][j] && data[i][j - k] == data[i][j]) { //System.out.println("HE HE " + i + " " + j); h--; if(h == 0){ i++; j++; out.println(i + " " + j); out.println((i - k) + " " + j); out.println((i + k) + " " + j); out.println(i + " " + (j - k)); out.println(i + " " + (j + k)); } } } } } out.close(); } static class Star implements Comparable<Star> { int x, y, z; public Star(int x, int y, int z) { super(); this.x = x; this.y = y; this.z = z; } @Override public int compareTo(Star o) { if (z != o.z) { return -Integer.compare(z, o.z); } else if (x != o.x) { return -Integer.compare(x, o.x); } return -Integer.compare(y, o.y); } } 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 x - o.x; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new // BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new // FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["5 6 1\n....*.\n...***\n....*.\n..*...\n.***..", "5 6 2\n....*.\n...***\n....*.\n..*...\n.***..", "7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*..."]
2 seconds
["2 5\n1 5\n3 5\n2 4\n2 6", "-1", "4 4\n1 4\n7 4\n4 1\n4 7"]
null
Java 7
standard input
[ "implementation" ]
f13be8bcb3291ffcc555a268f421bf3a
The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty.
1,600
If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right.
standard output
PASSED
b7f333a4440c974dc85b9c93c02d5da4
train_002.jsonl
1286002800
A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: the 2nd is on the same vertical line as the 1st, but x squares up the 3rd is on the same vertical line as the 1st, but x squares down the 4th is on the same horizontal line as the 1st, but x squares left the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one.Your task is to find the constellation with index k by the given Berland's star map.
256 megabytes
import static java.lang.Math.*; import static java.util.Arrays.*; import java.util.*; import java.io.*; public class Main { void solve() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); char[][] table = new char[n][m]; for (int i = 0; i < n; i++) table[i] = sc.next().toCharArray(); int[] di = new int[] {0, -1, 1, 0, 0}; int[] dj = new int[] {0, 0, 0, -1, 1}; for (int l = 1; l <= 151; l++) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int find = 0; for (int s = 0; s < 5; s++) { int ni = i + di[s] * l; int nj = j + dj[s] * l; if (0 <= ni && ni < n && 0 <= nj && nj < m && table[ni][nj] == '*') find++; else break; } if (find == 5) { k--; if (k == 0) { for (int s = 0; s < 5; s++) { int ni = i + di[s] * l; int nj = j + dj[s] * l; out.println((ni + 1) + " " + (nj + 1)); } return; } } } } } out.println(-1); return; } int calc(int n, int s) { if (n <= s) return n; int ma = (n + s - 1) / s; int r = n % s; if (r == 0) r = s; return ma * r; } static void tr(Object... os) { System.err.println(deepToString(os)); } void print(int[] a) { out.print(a[0]); for (int i = 1; i < a.length; i++) out.print(" " + a[i]); out.println(); } public static void main(String[] args) throws Exception { new Main().run(); } MyScanner sc = null; PrintWriter out = null; public void run() throws Exception { sc = new MyScanner(System.in); out = new PrintWriter(System.out); for (;sc.hasNext();) { solve(); out.flush(); } out.close(); } class MyScanner { String line; BufferedReader reader; StringTokenizer tokenizer; public MyScanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public void eat() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { line = reader.readLine(); if (line == null) { tokenizer = null; return; } tokenizer = new StringTokenizer(line); } catch (IOException e) { throw new RuntimeException(e); } } } public String next() { eat(); return tokenizer.nextToken(); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public boolean hasNext() { eat(); return (tokenizer != null && tokenizer.hasMoreElements()); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } } }
Java
["5 6 1\n....*.\n...***\n....*.\n..*...\n.***..", "5 6 2\n....*.\n...***\n....*.\n..*...\n.***..", "7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*..."]
2 seconds
["2 5\n1 5\n3 5\n2 4\n2 6", "-1", "4 4\n1 4\n7 4\n4 1\n4 7"]
null
Java 7
standard input
[ "implementation" ]
f13be8bcb3291ffcc555a268f421bf3a
The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty.
1,600
If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right.
standard output
PASSED
db843ebd5bb87a74c87fd6f667d441fc
train_002.jsonl
1286002800
A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: the 2nd is on the same vertical line as the 1st, but x squares up the 3rd is on the same vertical line as the 1st, but x squares down the 4th is on the same horizontal line as the 1st, but x squares left the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one.Your task is to find the constellation with index k by the given Berland's star map.
256 megabytes
import java.util.*; import java.math.*; public class Main{ static int n,m; public static void main(String[] args){ final int INF=1<<30; Scanner input=new Scanner(System.in); int n=input.nextInt(); int m=input.nextInt(); int k=input.nextInt(); char[][] a=new char[n+5][m+5]; int[] count=new int[310]; for(int i=1;i<=n;i++){ a[i]=(" "+input.next()).toCharArray(); } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(a[i][j]=='*'){ int u=1; while(true){ int up=i-u; int down=i+u; int left=j-u; int right=j+u; if(can(up,n)&&can(down,n)&&can(left,m)&&can(right,m)){ if((a[up][j]=='*')&&(a[down][j]=='*') &&(a[i][left]=='*')&&(a[i][right]=='*')){ count[u]++; } u++; }else{ break; } } } } } int sum=0; int r=0,num=0; for(int i=1;i<=300;i++){ sum=sum+count[i]; if(sum>=k){ r=i; num=k+count[i]-sum; break; } } if(sum<k){ System.out.println(-1); return; } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(a[i][j]=='*'){ int up=i-r; int down=i+r; int left=j-r; int right=j+r; if(can(up,n)&&can(down,n)&&can(left,m)&&can(right,m)){ if((a[up][j]=='*')&&(a[down][j]=='*') &&(a[i][left]=='*')&&(a[i][right]=='*')){ num--; if(num==0){ System.out.println(i+" "+j); System.out.println(up+" "+j); System.out.println(down+" "+j); System.out.println(i+" "+left); System.out.println(i+" "+right); return; } } } } } } } static boolean can(int u,int n){ if((u>0)&&(u<=n)){ return true; } return false; } }
Java
["5 6 1\n....*.\n...***\n....*.\n..*...\n.***..", "5 6 2\n....*.\n...***\n....*.\n..*...\n.***..", "7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*..."]
2 seconds
["2 5\n1 5\n3 5\n2 4\n2 6", "-1", "4 4\n1 4\n7 4\n4 1\n4 7"]
null
Java 7
standard input
[ "implementation" ]
f13be8bcb3291ffcc555a268f421bf3a
The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty.
1,600
If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right.
standard output
PASSED
98b17231b8777e048d4ba5e4ec7d88bd
train_002.jsonl
1286002800
A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: the 2nd is on the same vertical line as the 1st, but x squares up the 3rd is on the same vertical line as the 1st, but x squares down the 4th is on the same horizontal line as the 1st, but x squares left the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one.Your task is to find the constellation with index k by the given Berland's star map.
256 megabytes
import java.io.*; import java.util.*; public class Main { static boolean[][] map; static int n,m,k; public static boolean check ( int x, int y ) { return x>=0 && x<n && y>=0 && y<m && map[x][y]; } public static void main ( String[] args ) throws IOException { Scanner in=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); n=in.nextInt();m=in.nextInt();k=in.nextInt(); map=new boolean[n][m]; for (int i=0;i<n;++i) { String row=in.next(); for (int j=0;j<m;++j) map[i][j]=row.charAt(j)=='*'; } int cnt=0; for (int r=1;r<=Math.min(n, m);++r) for (int i=0;i<n;++i) for (int j=0;j<m;++j) if (check(i,j) && check(i+r,j) && check(i-r,j) && check(i,j+r) && check(i,j-r)) { ++cnt; if (cnt==k) { out.print(i+1);out.print(" ");out.println(j+1); out.print(i-r+1);out.print(" ");out.println(j+1); out.print(i+r+1);out.print(" ");out.println(j+1); out.print(i+1);out.print(" ");out.println(j-r+1); out.print(i+1);out.print(" ");out.println(j+r+1); out.close(); return; } } out.print(-1); out.close(); } }
Java
["5 6 1\n....*.\n...***\n....*.\n..*...\n.***..", "5 6 2\n....*.\n...***\n....*.\n..*...\n.***..", "7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*..."]
2 seconds
["2 5\n1 5\n3 5\n2 4\n2 6", "-1", "4 4\n1 4\n7 4\n4 1\n4 7"]
null
Java 7
standard input
[ "implementation" ]
f13be8bcb3291ffcc555a268f421bf3a
The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty.
1,600
If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right.
standard output
PASSED
f6a1e6375681196b8f7be1dea13d0c81
train_002.jsonl
1577198100
Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types: easy problems β€” Petya takes exactly $$$a$$$ minutes to solve any easy problem; hard problems β€” Petya takes exactly $$$b$$$ minutes ($$$b &gt; a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then: if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$); if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class d { public static void main(String[] args) throws IOException { // Scanner s = new Scanner(System.in); BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); // String[] st=s.readLine().trim().split("\\s+"); // a[i]=Integer.parseInt(st[i]); // Integer.parseInt(s.readLine().trim().split("\\s+"); StringBuilder sb = new StringBuilder(); StringBuilder sbf = new StringBuilder(); // int n=Integer.parseInt(s.readLine().trim().split("\\s+")[0]); /* String[] st=s.readLine().trim().split("\\s+"); int n=Integer.parseInt(st[0]);*/ int m=Integer.parseInt(s.readLine().trim().split("\\s+")[0]); while(m-->0){ String[] st=s.readLine().trim().split("\\s+"); int n=Integer.parseInt(st[0]);int T=Integer.parseInt(st[1]);long a=Integer.parseInt(st[2]);long b=Integer.parseInt(st[3]); int[] eh=new int[n]; String[] ss=s.readLine().trim().split("\\s+"); long easy=0;long hard=0; for(int i=0;i<n;i++){ eh[i]=Integer.parseInt(ss[i]);if(eh[i]==0) easy++;else hard++; }String[] s1=s.readLine().trim().split("\\s+"); Student[] sst=new Student[n]; for(int i=0;i<n;i++){ sst[i]=new Student(i,Long.parseLong(s1[i])); }long tt=0;long max=0; Arrays.sort(sst,new Sortbyroll()); for(int i=0;i<n;i++){ if(sst[i].r-1<tt) {if(eh[sst[i].l]==0) {easy--;tt+=a;} else {hard--;tt+=b;}continue;} long et=sst[i].r-1-tt; long val=0; if(et/a*a<a*easy) val= i+et/a;else val=i+easy; et-=Math.min(et/a*a,a*easy); if(et/b*b<b*hard) val+=et/b;else val+=hard; max=Math.max(val,max); if(eh[sst[i].l]==0) {easy--;tt+=a;} else {hard--;tt+=b;} } if(tt<=T){ max=n; } sb.append(max+"\n"); } System.out.println(sb.toString()); } static void swap(int[] a,int j){ int temp=a[j]; a[j]=a[j-1]; a[j-1]=temp; } static String lexographicallysmallest(String s) { if (s.length() % 2 == 1) return s; String s1 =lexographicallysmallest(s.substring(0, s.length()/2)); String s2 = lexographicallysmallest(s.substring(s.length()/2, s.length())); if (s1.compareTo(s2)<0) return s1 + s2; else return s2 + s1; } public static int countSetBits(int n) { return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]); } static int[] BitsSetTable256 ; public static void initialize(int n) { BitsSetTable256[0] = 0; for (int i = 0; i <=Math.pow(2,n); i++) { BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2]; } } static void dfs(int i,int val,ArrayList<Integer>[] adj){ } static void computeLPSArray(String pat, int M, int lps[]) { int len = 0; int i = 1; lps[0] = 0; while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = len; i++; } } } } 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 powerwithmod(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long powerwithoutmod(long x, int y) { long temp; if( y == 0) return 1; temp = powerwithoutmod(x, y/2); if (y%2 == 0) return temp*temp; else { if(y > 0) return x * temp * temp; else return (temp * temp) / x; } } static void fracion(double x) { String a = "" + x; String spilts[] = a.split("\\."); // split using decimal int b = spilts[1].length(); // find the decimal length int denominator = (int) Math.pow(10, b); // calculate the denominator int numerator = (int) (x * denominator); // calculate the nerumrator Ex // 1.2*10 = 12 int gcd = (int) gcd((long) numerator, denominator); // Find the greatest common // divisor bw them String fraction = "" + numerator / gcd + "/" + denominator / gcd; // System.out.println((denominator/gcd)); long x1 = modInverse(denominator / gcd, 998244353); // System.out.println(x1); System.out.println((((numerator / gcd) % 998244353 * (x1 % 998244353)) % 998244353)); } static int bfs(int i1, ArrayList<Integer>[] h, int[] vis, int n,int val1) { Queue<Integer> q = new LinkedList<Integer>(); q.add(i1);Queue<Integer> aq=new LinkedList<Integer>(); aq.add(0); while(!q.isEmpty()){ int i=q.poll(); int val=aq.poll(); if(i==n){ return val; } if(h[i]!=null){ for(Integer j:h[i]){ if(vis[j]==0){ q.add(j);vis[j]=1; aq.add(val+1);} } } }return -1; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long modInverse(long a, long m) { return (powerwithmod(a, m - 2, m)); } static int MAXN; static int[] spf; static void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) spf[i] = i; for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { if (spf[i] == i) { for (int j=i*i; j<MAXN; j+=i) if (spf[j]==j) spf[j] = i; } } } static ArrayList<Integer> getFactorizationUsingSeive(int x) { ArrayList<Integer> ret = new ArrayList<Integer>(); while (x != 1) { ret.add(spf[x]); if(spf[x]!=0) x = x / spf[x]; else break; } return ret; } static long[] fac ; static void calculatefac(long mod){ fac[0]=1; for (int i = 1 ;i <= MAXN; i++) fac[i] = fac[i-1] * i % mod; } static long nCrModPFermat(int n, int r, long mod) { if (r == 0) return 1; fac[0] = 1; return (fac[n]* modInverse(fac[r], mod) % mod * modInverse(fac[n-r], mod) % mod) % mod; } } class Student { int l;long r; public Student(int l, long r) { this.l = l; this.r = r; } public String toString() { return this.l+" "; } } class Sortbyroll implements Comparator<Student> { public int compare(Student a, Student b){ if(a.r<b.r) return -1; else if(a.r==b.r){ if(a.r==b.r){ return 0; } if(a.r<b.r) return -1; return 1;} return 1; } } class Sortbyroll2 implements Comparator<Student> { public int compare(Student a, Student b){ try{ if(a.l*b.r<b.l*a.r) return 1; return -1;} catch (IllegalArgumentException e){ System.out.println("HI"); } return 9;} }
Java
["10\n3 5 1 3\n0 0 1\n2 1 4\n2 5 2 3\n1 0\n3 2\n1 20 2 4\n0\n16\n6 20 2 5\n1 1 0 1 0 0\n0 8 2 9 11 6\n4 16 3 6\n1 0 1 1\n8 3 5 6\n6 20 3 6\n0 1 0 0 1 0\n20 11 3 20 16 17\n7 17 1 6\n1 1 0 1 0 0 0\n1 7 0 11 10 15 10\n6 17 2 6\n0 0 1 0 0 1\n7 6 3 7 10 12\n5 17 2 5\n1 1 1 1 0\n17 11 10 6 4\n1 1 1 2\n0\n1"]
2 seconds
["3\n2\n1\n0\n1\n4\n0\n1\n2\n1"]
null
Java 11
standard input
[ "two pointers", "sortings", "greedy" ]
6c165390c7f9fee059ef197ef40ae64f
The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$)Β β€” the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases. The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a &lt; b \le 10^9$$$)Β β€” the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$.
1,800
Print the answers to $$$m$$$ test cases. For each set, print a single integerΒ β€” maximal number of points that he can receive, before leaving the exam.
standard output
PASSED
3b483b0d606acd38bd1a14c516e7c80a
train_002.jsonl
1577198100
Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types: easy problems β€” Petya takes exactly $$$a$$$ minutes to solve any easy problem; hard problems β€” Petya takes exactly $$$b$$$ minutes ($$$b &gt; a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then: if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$); if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam.
256 megabytes
import java.io.*; import java.util.*; public class Solution { static class problem implements Comparable<problem>{ int mandatoryAfter; boolean easy; public problem(boolean easy, int mandatoryAfter) { this.easy = easy; this.mandatoryAfter = mandatoryAfter; } public problem() {} @Override public int compareTo(problem o) { return Integer.compare(this.mandatoryAfter, o.mandatoryAfter); } } public static void main(String[] args){ new Thread(null, null, "Anshum Gupta", 99999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static final long mxx = (long)(1e18+5); static final int mxN = (int)(1e6); static final int mxV = (int)(5e5+1), log = 18; static long mod = (long)(1e9+7); //998244353;//Μ‡ static final int INF = (int)1e9; static boolean[][]vis; static ArrayList<ArrayList<Integer>> adj; static int n, m, k, q, T, a, b; static char[]str; static problem[]arr; static int[]prefixEasy; public static void solve() throws Exception { // solve the problem here s = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out), true); // out = new PrintWriter("output.txt"); int tc = s.nextInt(); while(tc-- > 0){ n = s.nextInt(); T = s.nextInt(); a = s.nextInt(); b = s.nextInt(); problem[]arr = new problem[n]; for(int i=0; i<n; i++) { arr[i] = new problem(); arr[i].easy = (s.nextInt() == 0); } for(int i=0; i<n; i++) { arr[i].mandatoryAfter = s.nextInt(); } Arrays.parallelSort(arr); prefixEasy = new int[n+1]; for(int i=0; i<n; i++) { prefixEasy[i] = (i > 0 ? prefixEasy[i-1] : 0) + (arr[i].easy ? 1 : 0); } prefixEasy[n] = prefixEasy[n-1]; int ans = 0; for(int i=0; i<=n; i++) { ans = Math.max(ans, getMax((i < n ? arr[i].mandatoryAfter-1 : T), i)); // out.println("i = " + i + " getMax = " + getMax((i < n ? arr[i].mandatoryAfter-1 : T), i)); } out.println(ans); } out.flush(); out.close(); } private static int getMax(int time, int j) { // leaving the test at time // mandatory are all problems till j-1 int easyMandatory = (j > 0 ? prefixEasy[j-1] : 0); int hardMandatory = (j > 0 ? j - easyMandatory : 0); // out.println("easyMand = " + easyMandatory + " hardMand = " + hardMandatory); long timeForMandatory = 1L * a * easyMandatory + 1L * b * hardMandatory; long timeLeft = time - timeForMandatory; if(timeLeft < 0)return -INF; if(timeLeft == 0)return easyMandatory + hardMandatory; int solveMax = solveMaxPossible(j, timeLeft); return easyMandatory + hardMandatory + solveMax; } private static int solveMaxPossible(int j, long timeLeft) { int availableProblems = n - j; int maxEasy = prefixEasy[n] - (j > 0 ? prefixEasy[j-1] : 0); long timeRequiredForAllEasy = 1L * a * maxEasy; if(timeRequiredForAllEasy > timeLeft) { return (int)timeLeft / a; } int ans = maxEasy; timeLeft -= timeRequiredForAllEasy; int maxHard = availableProblems - maxEasy; long timeRequiredForAllHard = 1L * b * maxHard; if(timeRequiredForAllHard > timeLeft) { return ans + (int)timeLeft / b; } return ans + maxHard; } public static PrintWriter out; public static MyScanner s; static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public MyScanner(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] nextIntArray(int n){ int[]a = new int[n]; for(int i=0; i<n; i++) { a[i] = this.nextInt(); } return a; } long[] nextlongArray(int n) { long[]a = new long[n]; for(int i=0; i<n; i++) { a[i] = this.nextLong(); } return a; } Integer[] nextIntegerArray(int n){ Integer[]a = new Integer[n]; for(int i=0; i<n; i++) { a[i] = this.nextInt(); } return a; } Long[] nextLongArray(int n) { Long[]a = new Long[n]; for(int i=0; i<n; i++) { a[i] = this.nextLong(); } return a; } char[][] next2DCharArray(int n, int m){ char[][]arr = new char[n][m]; for(int i=0; i<n; i++) { arr[i] = this.next().toCharArray(); } return arr; } ArrayList<ArrayList<Integer>> readUndirectedUnweightedGraph(int n, int m) { ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>()); for(int i=0; i<m; i++) { int u = s.nextInt(); int v = s.nextInt(); adj.get(u).add(v); adj.get(v).add(u); } return adj; } ArrayList<ArrayList<Integer>> readDirectedUnweightedGraph(int n, int m) { ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>()); for(int i=0; i<m; i++) { int u = s.nextInt(); int v = s.nextInt(); adj.get(u).add(v); } return adj; } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["10\n3 5 1 3\n0 0 1\n2 1 4\n2 5 2 3\n1 0\n3 2\n1 20 2 4\n0\n16\n6 20 2 5\n1 1 0 1 0 0\n0 8 2 9 11 6\n4 16 3 6\n1 0 1 1\n8 3 5 6\n6 20 3 6\n0 1 0 0 1 0\n20 11 3 20 16 17\n7 17 1 6\n1 1 0 1 0 0 0\n1 7 0 11 10 15 10\n6 17 2 6\n0 0 1 0 0 1\n7 6 3 7 10 12\n5 17 2 5\n1 1 1 1 0\n17 11 10 6 4\n1 1 1 2\n0\n1"]
2 seconds
["3\n2\n1\n0\n1\n4\n0\n1\n2\n1"]
null
Java 11
standard input
[ "two pointers", "sortings", "greedy" ]
6c165390c7f9fee059ef197ef40ae64f
The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$)Β β€” the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases. The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a &lt; b \le 10^9$$$)Β β€” the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$.
1,800
Print the answers to $$$m$$$ test cases. For each set, print a single integerΒ β€” maximal number of points that he can receive, before leaving the exam.
standard output
PASSED
2059fbaa9495d75ee1b8919ea7f1d9b5
train_002.jsonl
1577198100
Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types: easy problems β€” Petya takes exactly $$$a$$$ minutes to solve any easy problem; hard problems β€” Petya takes exactly $$$b$$$ minutes ($$$b &gt; a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then: if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$); if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import static java.lang.Math.*; public class Main { int[] parent; void run() throws IOException { int q = nextInt(); while (q-- > 0) { int n = nextInt(); long t = nextLong(); long a = nextInt(); long b = nextInt(); int[] type = new int[n]; long easy = 0; long hard = 0; for (int i = 0; i < n; i++) { type[i] = nextInt(); if (type[i] == 1) hard++; else easy++; } point[] event = new point[n]; for (int i = 0; i < n; i++) { event[i] = new point(nextInt(), type[i]); } Arrays.sort(event); long ans = 0; long cnt_easy = 0; long cnt_hard = 0; for (int i = 0; i < event.length; i++) { if (i > 0) { if (event[i - 1].y == 1) cnt_hard++; else cnt_easy++; } long time = cnt_hard * b + cnt_easy * a; if (time >= event[i].x) continue; long have = event[i].x - time - 1; long x = min(have / a, easy - cnt_easy); ans = max(ans, (long) i + x + min(hard - cnt_hard, (have - a * x) / b)); } if (hard * b + easy * a <= t) ans = n; pw.println(ans); } pw.close(); } class point implements Comparable<point> { long x, y; public point(long a, long b) { x = a; y = b; } @Override public int compareTo(point o) { return -Long.compare(o.x, this.x); } } long mod = (long) 1e9 + 7; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader br = new BufferedReader(new FileReader("qual.in")); StringTokenizer st = new StringTokenizer(""); PrintWriter pw = new PrintWriter(System.out); //PrintWriter pw = new PrintWriter("qual.out"); int nextInt() throws IOException { return Integer.parseInt(next()); } String next() throws IOException { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public Main() throws FileNotFoundException { } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["10\n3 5 1 3\n0 0 1\n2 1 4\n2 5 2 3\n1 0\n3 2\n1 20 2 4\n0\n16\n6 20 2 5\n1 1 0 1 0 0\n0 8 2 9 11 6\n4 16 3 6\n1 0 1 1\n8 3 5 6\n6 20 3 6\n0 1 0 0 1 0\n20 11 3 20 16 17\n7 17 1 6\n1 1 0 1 0 0 0\n1 7 0 11 10 15 10\n6 17 2 6\n0 0 1 0 0 1\n7 6 3 7 10 12\n5 17 2 5\n1 1 1 1 0\n17 11 10 6 4\n1 1 1 2\n0\n1"]
2 seconds
["3\n2\n1\n0\n1\n4\n0\n1\n2\n1"]
null
Java 11
standard input
[ "two pointers", "sortings", "greedy" ]
6c165390c7f9fee059ef197ef40ae64f
The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$)Β β€” the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases. The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a &lt; b \le 10^9$$$)Β β€” the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$.
1,800
Print the answers to $$$m$$$ test cases. For each set, print a single integerΒ β€” maximal number of points that he can receive, before leaving the exam.
standard output
PASSED
6d640eceb2ee58595f29f28797b2cf2f
train_002.jsonl
1557671700
$$$n$$$ boys and $$$m$$$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $$$1$$$ to $$$n$$$ and all girls are numbered with integers from $$$1$$$ to $$$m$$$. For all $$$1 \leq i \leq n$$$ the minimal number of sweets, which $$$i$$$-th boy presented to some girl is equal to $$$b_i$$$ and for all $$$1 \leq j \leq m$$$ the maximal number of sweets, which $$$j$$$-th girl received from some boy is equal to $$$g_j$$$.More formally, let $$$a_{i,j}$$$ be the number of sweets which the $$$i$$$-th boy give to the $$$j$$$-th girl. Then $$$b_i$$$ is equal exactly to the minimum among values $$$a_{i,1}, a_{i,2}, \ldots, a_{i,m}$$$ and $$$g_j$$$ is equal exactly to the maximum among values $$$b_{1,j}, b_{2,j}, \ldots, b_{n,j}$$$.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $$$a_{i,j}$$$ for all $$$(i,j)$$$ such that $$$1 \leq i \leq n$$$ and $$$1 \leq j \leq m$$$. You are given the numbers $$$b_1, \ldots, b_n$$$ and $$$g_1, \ldots, g_m$$$, determine this number.
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.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.StringTokenizer; import java.util.stream.Collectors; public class Codeforces { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); int n = in.nextInt(); int m = in.nextInt(); int[] bMin = in.nextIntArr(n); int[] gMax = in.nextIntArr(m); List<Integer> boysMin = Arrays.stream(bMin).boxed().collect(Collectors.toList()); List<Integer> girlsMax = Arrays.stream(gMax).boxed().collect(Collectors.toList()); Collections.sort(boysMin); Collections.sort(girlsMax); if (boysMin.get(boysMin.size() - 1) > girlsMax.get(0)) { out.println(-1); out.close(); return; } Integer maxBoy = boysMin.get(boysMin.size() - 1); Integer minGirl = girlsMax.get(0); if (maxBoy.equals(minGirl)) { long res = 0; for (Integer girl : girlsMax) { res += girl; } for (int i = 0; i < boysMin.size() - 1; i++) { res += (long) boysMin.get(i) * (long) m; } out.println(res); } else { long res = 0; for (int i = 1; i < girlsMax.size(); i++) { res += (long) girlsMax.get(i); } res += (long) maxBoy; Integer boySecondMax = boysMin.get(boysMin.size() - 2); res += (long) minGirl; res += (long) boySecondMax * (long) (m - 1); for (int i = 0; i < boysMin.size() - 2; i++) { res += (long) boysMin.get(i) * (long) m; } out.println(res); } out.close(); } public static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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 String nextLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public int[] nextIntArr(int n) { int[] arr = new int[n]; for (int j = 0; j < arr.length; j++) { arr[j] = nextInt(); } return arr; } public long[] nextLongArr(int n) { long[] arr = new long[n]; for (int j = 0; j < arr.length; j++) { arr[j] = nextLong(); } return arr; } } }
Java
["3 2\n1 2 1\n3 4", "2 2\n0 1\n1 0", "2 3\n1 0\n1 1 2"]
1 second
["12", "-1", "4"]
NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to $$$12$$$. This can be possible, for example, if the first boy presented $$$1$$$ and $$$4$$$ sweets, the second boy presented $$$3$$$ and $$$2$$$ sweets and the third boy presented $$$1$$$ and $$$1$$$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$12$$$.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to $$$4$$$. This can be possible, for example, if the first boy presented $$$1$$$, $$$1$$$, $$$2$$$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$4$$$.
Java 8
standard input
[ "implementation", "greedy", "math" ]
4b4c7e7d9d5c45c8635b403bae997891
The first line contains two integers $$$n$$$ and $$$m$$$, separated with spaceΒ β€” the number of boys and girls, respectively ($$$2 \leq n, m \leq 100\,000$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$, separated by spacesΒ β€” $$$b_i$$$ is equal to the minimal number of sweets, which $$$i$$$-th boy presented to some girl ($$$0 \leq b_i \leq 10^8$$$). The third line contains $$$m$$$ integers $$$g_1, \ldots, g_m$$$, separated by spacesΒ β€” $$$g_j$$$ is equal to the maximal number of sweets, which $$$j$$$-th girl received from some boy ($$$0 \leq g_j \leq 10^8$$$).
1,500
If the described situation is impossible, print $$$-1$$$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.
standard output
PASSED
0eea504548f9f859d4454eed98517cce
train_002.jsonl
1557671700
$$$n$$$ boys and $$$m$$$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $$$1$$$ to $$$n$$$ and all girls are numbered with integers from $$$1$$$ to $$$m$$$. For all $$$1 \leq i \leq n$$$ the minimal number of sweets, which $$$i$$$-th boy presented to some girl is equal to $$$b_i$$$ and for all $$$1 \leq j \leq m$$$ the maximal number of sweets, which $$$j$$$-th girl received from some boy is equal to $$$g_j$$$.More formally, let $$$a_{i,j}$$$ be the number of sweets which the $$$i$$$-th boy give to the $$$j$$$-th girl. Then $$$b_i$$$ is equal exactly to the minimum among values $$$a_{i,1}, a_{i,2}, \ldots, a_{i,m}$$$ and $$$g_j$$$ is equal exactly to the maximum among values $$$b_{1,j}, b_{2,j}, \ldots, b_{n,j}$$$.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $$$a_{i,j}$$$ for all $$$(i,j)$$$ such that $$$1 \leq i \leq n$$$ and $$$1 \leq j \leq m$$$. You are given the numbers $$$b_1, \ldots, b_n$$$ and $$$g_1, \ldots, g_m$$$, determine this number.
256 megabytes
import javafx.scene.layout.Priority; import java.io.*; import java.lang.reflect.Array; import java.net.Inet4Address; import java.util.*; import java.lang.*; import java.util.HashMap; import java.util.PriorityQueue; public class templ implements Runnable { static class pair implements Comparable { int f; int s; pair(int fi,int se) { f=fi; s=se; } public int compareTo(Object o) { pair pr=(pair)o; if(s>pr.s) return 1; if(s==pr.s) { if(f<pr.f) return 1; else return -1; } else return -1; } public boolean equals(Object o) { pair ob=(pair)o; int ff; int ss; if(o!=null) { ff=ob.f; ss=ob.s; if((ff==this.f)&&(ss==this.s)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s).hashCode(); } } public class triplet implements Comparable { int f,t; int s; triplet(int f,int s,int t) { this.f=f; this.s=s; this.t=t; } public boolean equals(Object o) { triplet ob=(triplet)o; int ff; int ss; int tt; if(o!=null) { ff=ob.f; ss=ob.s; tt=ob.t; if((ff==this.f)&&(ss==this.s)&&(tt==this.t)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s+" "+this.t).hashCode(); } public int compareTo(Object o) { triplet tr=(triplet)o; if(t>tr.t) return 1; else return -1; } } void merge1(long arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; long L[] = new long [n1]; long R[] = new long [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i]<=R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void sort1(long arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort1(arr, l, m); sort1(arr , m+1, r); merge1(arr, l, m, r); } } public static void main(String args[])throws Exception { new Thread(null,new templ(),"templ",1<<27).start(); } public void run() { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n=in.ni(); int m=in.ni(); long a[]=new long[n+1]; long b[]=new long[m+1]; long max=0,ans=0; for(int i=1;i<=n;i++) { a[i] = in.nl(); max=Math.max(max,a[i]); ans+=a[i]*m; } long k=0; for(int i=1;i<=m;i++) { b[i] = in.nl(); if(b[i]<max) { ans=-1; break; } ans+=(b[i]-max); if(b[i]>max) k++; } if(ans==-1) out.println(ans); else { sort1(a,1,n); for(int i=n;i>=1;i--) { if(k<=m-1) { ans+=k*(max-a[i]); k=0; break; } else { ans+=(m-1)*(max-a[i]); k-=(m-1); } } if(k==0) out.println(ans); else out.println("-1"); } out.close(); } catch(Exception e){ return; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["3 2\n1 2 1\n3 4", "2 2\n0 1\n1 0", "2 3\n1 0\n1 1 2"]
1 second
["12", "-1", "4"]
NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to $$$12$$$. This can be possible, for example, if the first boy presented $$$1$$$ and $$$4$$$ sweets, the second boy presented $$$3$$$ and $$$2$$$ sweets and the third boy presented $$$1$$$ and $$$1$$$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$12$$$.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to $$$4$$$. This can be possible, for example, if the first boy presented $$$1$$$, $$$1$$$, $$$2$$$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$4$$$.
Java 8
standard input
[ "implementation", "greedy", "math" ]
4b4c7e7d9d5c45c8635b403bae997891
The first line contains two integers $$$n$$$ and $$$m$$$, separated with spaceΒ β€” the number of boys and girls, respectively ($$$2 \leq n, m \leq 100\,000$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$, separated by spacesΒ β€” $$$b_i$$$ is equal to the minimal number of sweets, which $$$i$$$-th boy presented to some girl ($$$0 \leq b_i \leq 10^8$$$). The third line contains $$$m$$$ integers $$$g_1, \ldots, g_m$$$, separated by spacesΒ β€” $$$g_j$$$ is equal to the maximal number of sweets, which $$$j$$$-th girl received from some boy ($$$0 \leq g_j \leq 10^8$$$).
1,500
If the described situation is impossible, print $$$-1$$$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.
standard output
PASSED
76651804c81f87267b198898e37e9988
train_002.jsonl
1557671700
$$$n$$$ boys and $$$m$$$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $$$1$$$ to $$$n$$$ and all girls are numbered with integers from $$$1$$$ to $$$m$$$. For all $$$1 \leq i \leq n$$$ the minimal number of sweets, which $$$i$$$-th boy presented to some girl is equal to $$$b_i$$$ and for all $$$1 \leq j \leq m$$$ the maximal number of sweets, which $$$j$$$-th girl received from some boy is equal to $$$g_j$$$.More formally, let $$$a_{i,j}$$$ be the number of sweets which the $$$i$$$-th boy give to the $$$j$$$-th girl. Then $$$b_i$$$ is equal exactly to the minimum among values $$$a_{i,1}, a_{i,2}, \ldots, a_{i,m}$$$ and $$$g_j$$$ is equal exactly to the maximum among values $$$b_{1,j}, b_{2,j}, \ldots, b_{n,j}$$$.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $$$a_{i,j}$$$ for all $$$(i,j)$$$ such that $$$1 \leq i \leq n$$$ and $$$1 \leq j \leq m$$$. You are given the numbers $$$b_1, \ldots, b_n$$$ and $$$g_1, \ldots, g_m$$$, determine this number.
256 megabytes
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class template { public static void main(String[] args) throws Exception { new template().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = f.nextInt(), m = f.nextInt(); ArrayList<Long> a = new ArrayList<>(); ArrayList<Long> b = new ArrayList<>(); for(int i = 0; i < n; i++) a.add(f.nextLong()); for(int i = 0; i < m; i++) b.add(f.nextLong()); Collections.sort(a); Collections.sort(b); long tot = 0; long max = a.get(a.size()-1); for(long c : a) tot += c * m; for(long c : b) tot += c - max; if(b.get(0) != max) tot += a.get(a.size()-1) - a.get(a.size()-2); if(b.get(0) < max) tot = -1; out.println(tot); out.flush(); } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["3 2\n1 2 1\n3 4", "2 2\n0 1\n1 0", "2 3\n1 0\n1 1 2"]
1 second
["12", "-1", "4"]
NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to $$$12$$$. This can be possible, for example, if the first boy presented $$$1$$$ and $$$4$$$ sweets, the second boy presented $$$3$$$ and $$$2$$$ sweets and the third boy presented $$$1$$$ and $$$1$$$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$12$$$.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to $$$4$$$. This can be possible, for example, if the first boy presented $$$1$$$, $$$1$$$, $$$2$$$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$4$$$.
Java 8
standard input
[ "implementation", "greedy", "math" ]
4b4c7e7d9d5c45c8635b403bae997891
The first line contains two integers $$$n$$$ and $$$m$$$, separated with spaceΒ β€” the number of boys and girls, respectively ($$$2 \leq n, m \leq 100\,000$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$, separated by spacesΒ β€” $$$b_i$$$ is equal to the minimal number of sweets, which $$$i$$$-th boy presented to some girl ($$$0 \leq b_i \leq 10^8$$$). The third line contains $$$m$$$ integers $$$g_1, \ldots, g_m$$$, separated by spacesΒ β€” $$$g_j$$$ is equal to the maximal number of sweets, which $$$j$$$-th girl received from some boy ($$$0 \leq g_j \leq 10^8$$$).
1,500
If the described situation is impossible, print $$$-1$$$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.
standard output
PASSED
d727a88371ea1614c4032d2489c21cf9
train_002.jsonl
1557671700
$$$n$$$ boys and $$$m$$$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $$$1$$$ to $$$n$$$ and all girls are numbered with integers from $$$1$$$ to $$$m$$$. For all $$$1 \leq i \leq n$$$ the minimal number of sweets, which $$$i$$$-th boy presented to some girl is equal to $$$b_i$$$ and for all $$$1 \leq j \leq m$$$ the maximal number of sweets, which $$$j$$$-th girl received from some boy is equal to $$$g_j$$$.More formally, let $$$a_{i,j}$$$ be the number of sweets which the $$$i$$$-th boy give to the $$$j$$$-th girl. Then $$$b_i$$$ is equal exactly to the minimum among values $$$a_{i,1}, a_{i,2}, \ldots, a_{i,m}$$$ and $$$g_j$$$ is equal exactly to the maximum among values $$$b_{1,j}, b_{2,j}, \ldots, b_{n,j}$$$.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $$$a_{i,j}$$$ for all $$$(i,j)$$$ such that $$$1 \leq i \leq n$$$ and $$$1 \leq j \leq m$$$. You are given the numbers $$$b_1, \ldots, b_n$$$ and $$$g_1, \ldots, g_m$$$, determine this number.
256 megabytes
import java.io.*; import java.nio.CharBuffer; import java.util.NoSuchElementException; public class P1159C { public static void main(String[] args) { SimpleScanner scanner = new SimpleScanner(System.in); PrintWriter writer = new PrintWriter(System.out); int n = scanner.nextInt(); int m = scanner.nextInt(); long maxX = Integer.MIN_VALUE, secondX = Integer.MIN_VALUE, minY = Integer.MAX_VALUE; long sumX = 0, sumY = 0; for (int i = 0; i < n; ++i) { long x = scanner.nextLong(); if (x >= maxX) { secondX = maxX; maxX = x; } else if (x > secondX) secondX = x; sumX += x; } for (int i = 0; i < m; ++i) { long y = scanner.nextLong(); minY = Math.min(minY, y); sumY += y; } if (maxX > minY) { writer.println(-1); writer.close(); return; } long ans = 0; if (minY == maxX) { ans = (sumX - maxX) * m + sumY; } else { ans = (sumX - maxX - secondX) * m + maxX + secondX * (m - 1) + sumY; } writer.println(ans); writer.close(); } private static class SimpleScanner { private static final int BUFFER_SIZE = 10240; private Readable in; private CharBuffer buffer; private boolean eof; SimpleScanner(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); buffer = CharBuffer.allocate(BUFFER_SIZE); buffer.limit(0); eof = false; } private char read() { if (!buffer.hasRemaining()) { buffer.clear(); int n; try { n = in.read(buffer); } catch (IOException e) { n = -1; } if (n <= 0) { eof = true; return '\0'; } buffer.flip(); } return buffer.get(); } void checkEof() { if (eof) throw new NoSuchElementException(); } char nextChar() { checkEof(); char b = read(); checkEof(); return b; } String next() { char b; do { b = read(); checkEof(); } while (Character.isWhitespace(b)); StringBuilder sb = new StringBuilder(); do { sb.append(b); b = read(); } while (!eof && !Character.isWhitespace(b)); return sb.toString(); } int nextInt() { return Integer.valueOf(next()); } long nextLong() { return Long.valueOf(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3 2\n1 2 1\n3 4", "2 2\n0 1\n1 0", "2 3\n1 0\n1 1 2"]
1 second
["12", "-1", "4"]
NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to $$$12$$$. This can be possible, for example, if the first boy presented $$$1$$$ and $$$4$$$ sweets, the second boy presented $$$3$$$ and $$$2$$$ sweets and the third boy presented $$$1$$$ and $$$1$$$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$12$$$.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to $$$4$$$. This can be possible, for example, if the first boy presented $$$1$$$, $$$1$$$, $$$2$$$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$4$$$.
Java 8
standard input
[ "implementation", "greedy", "math" ]
4b4c7e7d9d5c45c8635b403bae997891
The first line contains two integers $$$n$$$ and $$$m$$$, separated with spaceΒ β€” the number of boys and girls, respectively ($$$2 \leq n, m \leq 100\,000$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$, separated by spacesΒ β€” $$$b_i$$$ is equal to the minimal number of sweets, which $$$i$$$-th boy presented to some girl ($$$0 \leq b_i \leq 10^8$$$). The third line contains $$$m$$$ integers $$$g_1, \ldots, g_m$$$, separated by spacesΒ β€” $$$g_j$$$ is equal to the maximal number of sweets, which $$$j$$$-th girl received from some boy ($$$0 \leq g_j \leq 10^8$$$).
1,500
If the described situation is impossible, print $$$-1$$$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.
standard output
PASSED
853586af82e9b6d58721b1757a45b306
train_002.jsonl
1557671700
$$$n$$$ boys and $$$m$$$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $$$1$$$ to $$$n$$$ and all girls are numbered with integers from $$$1$$$ to $$$m$$$. For all $$$1 \leq i \leq n$$$ the minimal number of sweets, which $$$i$$$-th boy presented to some girl is equal to $$$b_i$$$ and for all $$$1 \leq j \leq m$$$ the maximal number of sweets, which $$$j$$$-th girl received from some boy is equal to $$$g_j$$$.More formally, let $$$a_{i,j}$$$ be the number of sweets which the $$$i$$$-th boy give to the $$$j$$$-th girl. Then $$$b_i$$$ is equal exactly to the minimum among values $$$a_{i,1}, a_{i,2}, \ldots, a_{i,m}$$$ and $$$g_j$$$ is equal exactly to the maximum among values $$$b_{1,j}, b_{2,j}, \ldots, b_{n,j}$$$.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $$$a_{i,j}$$$ for all $$$(i,j)$$$ such that $$$1 \leq i \leq n$$$ and $$$1 \leq j \leq m$$$. You are given the numbers $$$b_1, \ldots, b_n$$$ and $$$g_1, \ldots, g_m$$$, determine this number.
256 megabytes
import java.io.*; import java.nio.CharBuffer; import java.util.NoSuchElementException; public class P1159C { public static void main(String[] args) { SimpleScanner scanner = new SimpleScanner(System.in); PrintWriter writer = new PrintWriter(System.out); int n = scanner.nextInt(); int m = scanner.nextInt(); long maxX = Integer.MIN_VALUE, secondX = Integer.MIN_VALUE, minY = Integer.MAX_VALUE; long sumX = 0, sumY = 0; for (int i = 0; i < n; ++i) { long x = scanner.nextLong(); if (x >= maxX) { secondX = maxX; maxX = x; } else if (x > secondX) secondX = x; sumX += x; } for (int i = 0; i < m; ++i) { long y = scanner.nextLong(); minY = Math.min(minY, y); sumY += y; } long ans = 0; if (maxX > minY) { ans = -1; } else if (minY == maxX) { ans = (sumX - maxX) * m + sumY; } else { ans = (sumX - maxX) * m + maxX - secondX + sumY; } writer.println(ans); writer.close(); } private static class SimpleScanner { private static final int BUFFER_SIZE = 10240; private Readable in; private CharBuffer buffer; private boolean eof; SimpleScanner(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); buffer = CharBuffer.allocate(BUFFER_SIZE); buffer.limit(0); eof = false; } private char read() { if (!buffer.hasRemaining()) { buffer.clear(); int n; try { n = in.read(buffer); } catch (IOException e) { n = -1; } if (n <= 0) { eof = true; return '\0'; } buffer.flip(); } return buffer.get(); } void checkEof() { if (eof) throw new NoSuchElementException(); } char nextChar() { checkEof(); char b = read(); checkEof(); return b; } String next() { char b; do { b = read(); checkEof(); } while (Character.isWhitespace(b)); StringBuilder sb = new StringBuilder(); do { sb.append(b); b = read(); } while (!eof && !Character.isWhitespace(b)); return sb.toString(); } int nextInt() { return Integer.valueOf(next()); } long nextLong() { return Long.valueOf(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3 2\n1 2 1\n3 4", "2 2\n0 1\n1 0", "2 3\n1 0\n1 1 2"]
1 second
["12", "-1", "4"]
NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to $$$12$$$. This can be possible, for example, if the first boy presented $$$1$$$ and $$$4$$$ sweets, the second boy presented $$$3$$$ and $$$2$$$ sweets and the third boy presented $$$1$$$ and $$$1$$$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$12$$$.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to $$$4$$$. This can be possible, for example, if the first boy presented $$$1$$$, $$$1$$$, $$$2$$$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$4$$$.
Java 8
standard input
[ "implementation", "greedy", "math" ]
4b4c7e7d9d5c45c8635b403bae997891
The first line contains two integers $$$n$$$ and $$$m$$$, separated with spaceΒ β€” the number of boys and girls, respectively ($$$2 \leq n, m \leq 100\,000$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$, separated by spacesΒ β€” $$$b_i$$$ is equal to the minimal number of sweets, which $$$i$$$-th boy presented to some girl ($$$0 \leq b_i \leq 10^8$$$). The third line contains $$$m$$$ integers $$$g_1, \ldots, g_m$$$, separated by spacesΒ β€” $$$g_j$$$ is equal to the maximal number of sweets, which $$$j$$$-th girl received from some boy ($$$0 \leq g_j \leq 10^8$$$).
1,500
If the described situation is impossible, print $$$-1$$$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.
standard output
PASSED
30d89447c2be00be493d57062874ee7a
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static PrintStream out = new PrintStream(System.out);; public static void main(String[] args){ FastScanner sc = new FastScanner(); int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); //# in stack int m = sc.nextInt(); //# to be sent int[] A = new int[Math.max(m,n) + 1]; //original order int[] visited = new int[Math.max(m,n) + 1]; Arrays.fill(visited, 0); for(int i = 0; i < n; i++){ int next = sc.nextInt(); A[i] = next; } int[] B = new int[n + 1]; //order that needs to be sent in for(int i = 0; i < m; i++) B[i] = sc.nextInt(); long ans = 0; int i = 0; int j = 0; while(i < n && j < m){ if(visited[B[j]] == 0){ while(A[i] != B[j]){ visited[A[i]] = 1; i++; } long dist = Math.abs(i - j); ans += (2 * dist) + 1; } else ans++; j++; } out.println(ans); } } private static int BSearch(int elem, ArrayList<Integer> firsts){ int index = -1; int l = 0; int r = firsts.size() - 1; while(l <= r){ int mid = (l + r) / 2; if(firsts.get(mid) <= elem){ index = mid; l = mid + 1; } else{ r = mid - 1; } } return index; } private static int factorial(int n){ int fac = 1; for(int i=2;i<=n;i++){ fac *= i; } return fac; } private static boolean isPrime(int n){ if(n == 0 || n == 1){ return false; }else if(n%2 == 0){ return false; }else{ int x = (int)(Math.sqrt(n)) + 1; for(int i=3;i<=x;i+=2){ if(n % i == 0){ return false; } } return true; } } private static long pow(int base,int exp){ if(exp == 0){ return 1; }else if(exp == 1){ return base; }else{ long a = pow(base,exp/2); if(exp%2 == 0){ return a * a; }else{ return a * a * base; } } } private static int gcd(int a,int b){ if(a == 0){ return b; } return gcd(b%a,a); } private static int lcm(int a,int b){ return (a * b)/gcd(a,b); } private static ArrayList<Integer> SieveOfEratosthenes(int n){ boolean b[] = new boolean[n+1]; b[0] = true; b[1] = true; for(int i=2;i<=5;i++){ int j = 2; while(i * j <= n && !b[i]){ b[i * j] = true; j++; } } ArrayList<Integer> arr = new ArrayList<>(); for(int i=2;i<n+1;i++){ if(!b[i]){ arr.add(i); } } return arr; } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int length) { int[] arr = new int[length]; for (int i = 0; i < length; i++) arr[i] = nextInt(); return arr; } } //class Node //{ // public int V; // public Node(int v) // { // this.V=v; // } //} //class Node implements Comparable<Node> //{ // public int V,E; // public Node(int v, int e) // { // this.V=v; // this.E=e; // } // public int compareTo( Node N ){ // return E - N.E; // } //}
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
c22a2c56c32bef3064544e6793499150
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static PrintStream out = new PrintStream(System.out);; public static void main(String[] args){ FastScanner sc = new FastScanner(); int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); //# in stack int m = sc.nextInt(); //# to be sent int[] stackOrder = new int[Math.max(m,n) + 1]; //original order int[] indices = new int[Math.max(m,n) + 1]; for(int i = 0; i < n; i++){ int next = sc.nextInt(); stackOrder[i] = next; indices[next] = i; } int[] sendOrder = new int[n + 1]; //order that needs to be sent in for(int i = 0; i < m; i++) sendOrder[i] = sc.nextInt(); int x = -1; long ans = m; for(int i = 0; i < m; i++){ if(indices[sendOrder[i]] > x){ ans += 2 * (indices[sendOrder[i]] - i); x = indices[sendOrder[i]]; } } out.println(ans); } } private static int BSearch(int elem, ArrayList<Integer> firsts){ int index = -1; int l = 0; int r = firsts.size() - 1; while(l <= r){ int mid = (l + r) / 2; if(firsts.get(mid) <= elem){ index = mid; l = mid + 1; } else{ r = mid - 1; } } return index; } private static int factorial(int n){ int fac = 1; for(int i=2;i<=n;i++){ fac *= i; } return fac; } private static boolean isPrime(int n){ if(n == 0 || n == 1){ return false; }else if(n%2 == 0){ return false; }else{ int x = (int)(Math.sqrt(n)) + 1; for(int i=3;i<=x;i+=2){ if(n % i == 0){ return false; } } return true; } } private static long pow(int base,int exp){ if(exp == 0){ return 1; }else if(exp == 1){ return base; }else{ long a = pow(base,exp/2); if(exp%2 == 0){ return a * a; }else{ return a * a * base; } } } private static int gcd(int a,int b){ if(a == 0){ return b; } return gcd(b%a,a); } private static int lcm(int a,int b){ return (a * b)/gcd(a,b); } private static ArrayList<Integer> SieveOfEratosthenes(int n){ boolean b[] = new boolean[n+1]; b[0] = true; b[1] = true; for(int i=2;i<=5;i++){ int j = 2; while(i * j <= n && !b[i]){ b[i * j] = true; j++; } } ArrayList<Integer> arr = new ArrayList<>(); for(int i=2;i<n+1;i++){ if(!b[i]){ arr.add(i); } } return arr; } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int length) { int[] arr = new int[length]; for (int i = 0; i < length; i++) arr[i] = nextInt(); return arr; } } //class Node //{ // public int V; // public Node(int v) // { // this.V=v; // } //} //class Node implements Comparable<Node> //{ // public int V,E; // public Node(int v, int e) // { // this.V=v; // this.E=e; // } // public int compareTo( Node N ){ // return E - N.E; // } //}
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
aa652fcc57b43e23c67ebb05a730b7e1
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args)throws IOException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); int n,m; int depth[]; int val,maxdepth; int minval; long ans; long ct; for(int i=0;i<t;i++) { n=in.nextInt(); m=in.nextInt(); depth = new int[n]; for(int j=0;j<n;j++) { val=in.nextInt()-1; depth[val]=j; } ans=0; maxdepth=-1; for(int j=0;j<m;j++) { ans++; val=in.nextInt()-1; if(depth[val]>maxdepth) { maxdepth=depth[val]; ans+=(2*(depth[val]-j)); } } out.println(ans); } out.close(); } 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
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
00ce858e3b258c2657648000073d88e8
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args)throws IOException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); int n,m; int depth[]; int val,maxdepth; int minval; long ans; long ct; for(int i=0;i<t;i++) { n=in.nextInt(); m=in.nextInt(); depth = new int[n]; for(int j=0;j<n;j++) { val=in.nextInt()-1; depth[val]=j; } ans=0; maxdepth=-1; for(int j=0;j<m;j++) { val=in.nextInt()-1; if(maxdepth!=-1 && depth[val]<maxdepth) { ans++; } else { maxdepth=depth[val]; ans+=(2*(depth[val]-j)); ans++; } } out.println(ans); } out.close(); } 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
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
5c1e982dfc1930971876abd681619277
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
// Don't place your source in a package import java.util.*; import java.lang.*; import java.io.*; // Please name your class Main public class Main { public static void main (String[] args) throws java.lang.Exception { Scanner in = new Scanner(System.in); int T =in.nextInt(); for(int t=0;t<T;t++){ int n=in.nextInt();int m=in.nextInt(); int A[]=new int[n];int B[]=new int[m]; for(int i=0;i<n;i++){ A[i]=in.nextInt(); } for(int i=0;i<m;i++){ B[i]=in.nextInt(); } Solution s=new Solution(); s.solution(A,B); } } } class Solution{ public void solution(int A[],int B[]){ //2k+1 long res=0; Stack<Integer>stack=new Stack<>(); Map<Integer,Integer>map=new HashMap<>(); for(int i=A.length-1;i>=0;i--)stack.push(A[i]); for(int i=0;i<B.length;i++){ if(map.containsKey(B[i])){ map.put(B[i],map.get(B[i])-1); if(map.get(B[i])==0)map.remove(B[i]); res++; }else{ int cnt=0; while(stack.peek()!=B[i]){ cnt++; int top=stack.pop(); if(!map.containsKey(top))map.put(top,0); map.put(top,map.get(top)+1); } stack.pop(); res++; res+=map.size()*2; } } System.out.println(res); } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
138f14c952bde8aa59945d39f20ca2d2
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.util.*; import java.text.DecimalFormat; import java.io.*; public class FedorNewGame { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while (t>0) { String inp[]=br.readLine().split(" "); int n=Integer.parseInt(inp[0]); int m=Integer.parseInt(inp[1]); String line1[]=br.readLine().split(" "); String line2[]=br.readLine().split(" "); HashMap<Integer, Integer> map=new HashMap<>(); for (int i=0;i<n;i++) { int x=Integer.parseInt(line1[i]); map.put(x, i); } int presentsinstack=n; int takenout=0; int tillsorted=-1; long ans=0; for (int i=0;i<m;i++) { int x=Integer.parseInt(line2[i]); int posinstack=map.get(x); if ((posinstack)>tillsorted) { ans+=((2*(long)(posinstack-takenout))+1); tillsorted=posinstack; } else ans++; presentsinstack--; takenout++; } System.out.println(ans); t--; } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
b9577875431668d2a3b85655563205ad
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.io.*; import java.util.*; public class Sol { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int[] stack = new int[n]; HashMap<Integer, Integer> presents = new HashMap<>(); for (int i = 0; i < n; i++) { stack[i] = sc.nextInt() - 1; } for (int i = 0; i < m; i++) { presents.put(sc.nextInt() - 1, i); } boolean[] got = new boolean[n]; int turn = 0; long sum = 0; long k = 0; for (int i = 0; i < n; i++) { while (got[turn]) { k--; turn++; } if (presents.containsKey(stack[i])) { Integer integer = presents.get(stack[i]); if (integer == turn) { sum += k * 2 + 1; got[integer] = true; } else { got[integer] = true; sum++; } } k++; } System.out.println(sum); } } private static String goString(String s) { return s + " blab"; } static class Pair implements Comparable<Pair> { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Pair o) { return this.a - o.a; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream System) throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(System)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() { for (long i = 0; i < 3e9; i++) ; } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
084e4972dfdc2961c8c4b2569dcef6da
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.util.*; public class StackofPresents { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { int n = in.nextInt(); int m = in.nextInt(); int[] pos = new int[n + 1]; int[] arr = new int[n]; for (int j = 0; j < n; j++) { arr[j] = in.nextInt(); pos[arr[j]] = j; } int arr2[] = new int[m]; for (int j = 0; j < m; j++) { arr2[j] = in.nextInt(); } long ans = pos[arr2[0]] * 2 + 1; Set<Integer> out = new HashSet<Integer>(); int at = pos[arr2[0]]; int taken = 1; for (int j = 0; j < at; j++) { out.add(arr[j]); } for (int j = 1; j < m; j++) { if (out.contains(arr2[j])) { ans++; taken++; continue; } ans += pos[arr2[j]] * 2 + 1 - (taken * 2); for (int k = at + 1; k < pos[arr2[j]]; k++) { out.add(arr[k]); } at = pos[arr2[j]]; taken++; } System.out.println(ans); } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
af4fc12d8658f39f06daae8da6af72af
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.io.*; import java.util.*; /** * Only By Abhi_Valani */ 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); Unstoppable solver = new Unstoppable(); int t=in.nextInt(); while(t-->0) solver.solve(in, out); out.close(); } static class Unstoppable { public void solve(InputReader in, PrintWriter out) { int n=in.nextInt(); int m=in.nextInt(); int a[]=new int[n]; int b[]=new int[m]; long cost=0; int flag=0; for(int i=0;i<n;i++) a[i]=in.nextInt(); for(int i=0;i<m;i++) b[i]=in.nextInt(); HashSet<Integer> hs=new HashSet<Integer>(); for(int i=0;i<m;i++) { if(hs.contains(b[i])){ cost++; hs.remove(b[i]); continue; } for(int j=flag;j<n;j++){ if(b[i]!=a[j]) hs.add(a[j]); else {cost+=(j-i)*2 + 1; flag=j+1; break; } } } out.println(cost); } } 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 long nextLong(){ return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
dc6c508cbcd9c93392ea988aed4def02
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.io.*; import java.util.*; import java.util.regex.*; public class vk18 { public static void main(String[]stp) throws Exception { Scanner scan=new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String []s; long q=Integer.parseInt(br.readLine()); while(q!=0) { s=br.readLine().split(" "); int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]),i; int a[]=new int[n]; int b[]=new int[n]; int c[]=new int[m]; s=br.readLine().split(" "); for(i=0;i<n;i++) { a[i]=Integer.parseInt(s[i])-1; b[a[i]]=i;} s=br.readLine().split(" "); for(i=0;i<m;i++) c[i]=Integer.parseInt(s[i])-1; int max=-1,count=0,index=0; long ans=0; for(i=0;i<m;i++) { index=b[c[i]]; if(index > max) {ans+=2*(index-count) +1; count++; max=index;} else {ans++; count++; } } System.out.println(ans); q--; } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
496377a70fd2398b665ee4b15bd5590e
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class Solution { public static void main(String[] args) throws Exception { try(InputUtil input = new InputUtil()) { int t = input.readLineAsInt(); for(int i = 0; i < t; i++) process(input); } } private static void process(InputUtil input) throws Exception { int nm[] = input.readInts(); int n = nm[0], m = nm[1]; LinkedList<Integer> stackOfGiftes = Arrays.stream(input.readInts()).boxed().collect(Collectors.toCollection(LinkedList::new)); int[] deliveryOrder = input.readInts(); HashSet<Integer> movedGifts = new HashSet<>(); long totalTime = 0; for(int gift: deliveryOrder) { if(movedGifts.contains(gift)) { totalTime += 1; movedGifts.remove(gift); } else { long count = 0; Iterator<Integer> iterator = stackOfGiftes.iterator(); while(iterator.hasNext()) { int nextGift = iterator.next(); if(nextGift == gift) { totalTime += (2 * movedGifts.size()) + 1; iterator.remove(); break; } else { movedGifts.add(nextGift); count++; iterator.remove(); } } } } System.out.println(totalTime); } public static class InputUtil implements Closeable { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public int readLineAsInt() throws Exception { return Integer.parseInt(reader.readLine()); } public long readLineAsLong() throws Exception { return Long.parseLong(reader.readLine()); } public String getSpaceSeperatedInts(int[] ints) { return Stream.of(ints) .map(String::valueOf) .collect(Collectors.joining(" ")); } public String getSpaceSeperatedBigInteger(BigInteger[] nums) { return Stream.of(nums) .map(BigInteger::toString) .collect(Collectors.joining(" ")); } public boolean isEven(long number) { return number % 2 == 0; } public boolean isOdd(long number) { return !isEven(number); } public boolean isEven(BigInteger number) { return !number.testBit(1); } public boolean isOdd(BigInteger number) { return !isEven(number); } public int[] readInts() throws IOException { return toIntArray(reader.readLine()); } public int[] toIntArray(String s) { return Stream.of(s.split("\\s")) .mapToInt(Integer::parseInt) .toArray(); } public long[] readLongs() throws IOException { return toLongArray(reader.readLine()); } public long[] toLongArray(String s) { return Stream.of(s.split("\\s")) .mapToLong(Long::parseLong) .toArray(); } public BigInteger[] readBigInts() throws IOException { return toBigIntArray(reader.readLine()); } public BigInteger[] toBigIntArray(String s) { String[] nums = s.split("\\s"); return IntStream.range(0, nums.length) .boxed() .map(index -> new BigInteger(nums[index])) .toArray(size -> new BigInteger[size]); } public char[] readChars() throws IOException { return reader.readLine().toCharArray(); } public BufferedReader getReader() { return reader; } @Override public void close() throws IOException { reader.close(); } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
6420ff063cdb8f8779bf086e3dfb6459
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class StackPresent { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t-->0){ String[] in = br.readLine().split(" "); int n = Integer.parseInt(in[0]); int m = Integer.parseInt(in[1]); in = br.readLine().split(" "); int arr[] = new int[n]; for(int i=0;i<n;i++){ arr[i]=Integer.parseInt(in[i]); } in = br.readLine().split(" "); int b[] = new int[n]; for(int i=0;i<m;i++){ b[i]=Integer.parseInt(in[i]); } long count=0L; Set<Integer> visited = new HashSet<Integer>(); int j=0; for(int i=0;i<m;i++){ if(visited.contains(b[i])){ visited.remove(b[i]); count++; continue; } while(arr[j]!=b[i]){ visited.add(arr[j]); j++; } count+=(visited.size())*2+1; j++; } System.out.println(count); } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
317be615aa968a67eaad05a41347658f
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int m=sc.nextInt(); int[] arr=new int[n]; int[] brr=new int[m]; HashSet<Integer> set=new HashSet(); for(int i=0;i<n;i++) arr[i]=sc.nextInt(); for(int i=0;i<m;i++) brr[i]=sc.nextInt(); long p=0; int j=0; for(int i=0;i<m;i++) { if(set.contains(brr[i])) {p+=1L;set.remove(brr[i]);} else { long tmp=0; for(;j<n;j++) { set.add(arr[j]);tmp++; if(arr[j]==brr[i]) { set.remove(brr[i]); j++; p+=(1L+set.size()*2L); // System.out.println(p+" "+tmp); break; } } } } System.out.println(p); } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
53e76371685b169e7c93676fd5e31ae3
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) throws Exception{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer stt; int t=Integer.parseInt(br.readLine()); for(int i=0; i<t; i++){ stt=new StringTokenizer(br.readLine()); int n=Integer.parseInt(stt.nextToken()), m=Integer.parseInt(stt.nextToken()); int all_presents[]=new int[n], pos_presents[]=new int[n+1], presents[]=new int[m]; stt=new StringTokenizer(br.readLine()); for(int j=0; j<n; j++){ all_presents[j]=Integer.parseInt(stt.nextToken()); pos_presents[all_presents[j]]=j; } stt=new StringTokenizer(br.readLine()); for(int j=0; j<m; j++) presents[j]=Integer.parseInt(stt.nextToken()); int index_limit=-1; long total_time=0; for(int j=0; j<m; j++){ if(pos_presents[presents[j]]>index_limit){ total_time+=2*(pos_presents[presents[j]]-j)+1; index_limit=pos_presents[presents[j]]; } else total_time++; } System.out.println(total_time); } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
d33c13ac71b80312e761e76439367a87
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) throws Exception{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer stt; int t=Integer.parseInt(br.readLine()); for(int i=0; i<t; i++){ HashMap<Integer, Integer> mapOfUpperStack=new HashMap<>(); stt=new StringTokenizer(br.readLine()); int n=Integer.parseInt(stt.nextToken()), m=Integer.parseInt(stt.nextToken()); int all_presents[]=new int[n], presents[]=new int[m]; stt=new StringTokenizer(br.readLine()); for(int j=0; j<n; j++) all_presents[j]=Integer.parseInt(stt.nextToken()); stt=new StringTokenizer(br.readLine()); for(int j=0; j<m; j++) presents[j]=Integer.parseInt(stt.nextToken()); int k=0, removed_presents=0; long total_time=0; for(int j=0; j<m; j++){ if(mapOfUpperStack.containsKey(presents[j])){ total_time++; } else{ int temp_k=0; boolean is_present=false; while(!is_present && k+temp_k<n){ mapOfUpperStack.put(all_presents[k+temp_k], 1); if(all_presents[k+temp_k]==presents[j]){ total_time+=2*(k+temp_k-removed_presents)+1; k+=temp_k+1; is_present=true; } temp_k++; } } removed_presents++; } System.out.println(total_time); } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
4ea0c950756aeb325cc74fb3cb8c62ef
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class MakingString 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; } static int mat(String a,String b) { int count=0; for(int i=0;i<a.length();i++) { if(a.charAt(i)!=b.charAt(i)) count++; } return count; } public static void main(String args[]) throws Exception { new Thread(null, new MakingString(),"MakingString",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 l=sc.nextInt(); for(int j=0;j<l;j++) { int n = sc.nextInt(); int m = sc.nextInt(); int res[]=new int[n]; int ord[]=new int[m]; HashMap <Integer,Integer> map =new HashMap(); for(int i=0;i<n;i++) { res[i]=sc.nextInt(); map.put(res[i],i); } int t=0; int k=0; long sum=0l; for(int i=0;i<m;i++) ord[i]=sc.nextInt(); for(int i=0;i<m;i++) { if(map.get(ord[i])>t) { sum=sum + 1 + 2*(map.get(ord[i])-k); t=map.get(ord[i]); k++; } else { sum=sum+1; k++; } } System.out.println(sum); } System.out.flush(); w.close(); } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
91e9f171116c7f4436ce4e5adea64451
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class MakingString 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; } static int mat(String a,String b) { int count=0; for(int i=0;i<a.length();i++) { if(a.charAt(i)!=b.charAt(i)) count++; } return count; } public static void main(String args[]) throws Exception { new Thread(null, new MakingString(),"MakingString",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 l=sc.nextInt(); for(int j=0;j<l;j++) { int n = sc.nextInt(); int m = sc.nextInt(); int res[]=new int[n]; int ord[]=new int[m]; HashMap <Integer,Integer> map =new HashMap(); for(int i=0;i<n;i++) { res[i]=sc.nextInt(); map.put(res[i],i); } int t=0; int k=0; long sum=0l; for(int i=0;i<m;i++) ord[i]=sc.nextInt(); for(int i=0;i<m;i++) { if(map.get(ord[i])>t) { sum=sum + 1 + 2*(map.get(ord[i])-k); t=map.get(ord[i]); k++; } else { sum=sum+1; k++; } } w.println(sum); } System.out.flush(); w.close(); } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
49ddce20aa3920f711a11808a0042b00
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main{ public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static void main(String sp[])throws IOException{ FastReader sc = new FastReader(); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int m = sc.nextInt(); ArrayList<Long> al = new ArrayList<>(); for(int i=0;i<n;i++) al.add(sc.nextLong()); TreeMap<Long,Integer> hm = new TreeMap<>(); for(int i=0;i<n;i++){ hm.put(al.get(i),i); } ArrayList<Long> queries = new ArrayList<>(); for(int i=0;i<m;i++) queries.add(sc.nextLong()); long ans = 0; int decider = 0 ; long val = queries.get(0); int removed = 0; int index = hm.get(val); decider = index; ans += ((2*(index))+1); removed += 1; for(int i=1;i<m;i++){ long v = queries.get(i); int ind = hm.get(v); if(ind<decider){ ans += 1; removed+=1; }else{ ans += (((ind-removed)*2)+1); removed += 1; decider = ind; } } System.out.println(ans); } } public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
7d99675228b9afd3b5e10d575b06548e
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
//package com.company; import java.io.*; import java.util.*; import java.lang.*; public class Main{ public static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private 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 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 char nextChar() { int c = read(); while (isSpaceChar(c)) c = read(); return (char)c; } 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); } } public static void main(String args[]){ InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter w = new PrintWriter(outputStream); int t,i,j; t=in.nextInt(); while(t-->0){ int n,m; n=in.nextInt(); m=in.nextInt(); int marr[]=new int[m]; int narr[]=new int[n]; int arr[]=new int[n]; for(i=0;i<n;i++){ narr[i]=in.nextInt(); arr[narr[i]-1]=i; } for(i=0;i<m;i++){ marr[i]=in.nextInt(); } int max=-1; long count=0; for(i=0;i<m;i++){ if(arr[marr[i]-1]>max){ max=arr[marr[i]-1]; count+=(2*(max-i))+1; }else{ count++; } } w.println(count); } w.close(); } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
cdf1e53bf15a198544f6d5e2d47f0478
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; /** * Pick questions that you love and solve them with love, try to get AC in one * go with cleanest code Just one thing to keep in mind these questions should * be out of your reach, which make you step out of comfort zone Try to pick * them from different topics CP is a sport, enjoy it. Don't make it pressure * cooker or job ****Use pen and paper************* check few examples analyze * them, some not given in sample also analyze then code Use pen and paper. * Solve on paper then code. If there is some reasoning e.g. sequence/paths, try * printing first 100 elements or 100 answers using brute and observe. * *********Read question with extreme caution. Mistake is happening here which * costs time, WA and easy problem not getting solved.********* Sometimes we * make question complex due to misunderstanding. Prefix sum and suffix sum is * highly usable concept, look for it. Think of cleanest approach. If too many * if else are coming then its indication of WA. Solve 1-2 more questions than * you solved during contest. */ public class Codeforces { public static void main(String args[]) throws IOException { // FastReader in = new FastReader(); use in case of millions of strings Reader in = new Reader(); int t = in.nextInt(); while (t-->0) { int n = in.nextInt(), m = in.nextInt(); int a[] = new int[n]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0;i<n;i++) { a[i] = in.nextInt(); map.put(a[i], i); } int b[] = new int[m]; for (int i=0;i<m;i++) { b[i] = in.nextInt(); } long sum = m; int max = 0; for (int i=0;i<m;i++) { int ind = map.get(b[i]); if (ind>max) { max = ind; sum = sum + 2*(ind-i); } } System.out.println(sum); } in.close(); } static class Pair { Integer x; Integer y; private Pair(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (o == null || !(o instanceof Pair)) return false; Pair cor = (Pair) o; return x.equals(cor.x) && y.equals(cor.y); } @Override public int hashCode() { int result = 17; return result; } static class PairComparatorX implements Comparator<Pair> { @Override public int compare(Pair o1, Pair o2) { return o1.x.compareTo(o2.x); } } static class PairComparatorY implements Comparator<Pair> { @Override public int compare(Pair o1, Pair o2) { return o1.y.compareTo(o2.y); } } } static class Reader { /** * When reading millions of strings try using FastReader if getting tle */ final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; Scanner in = new Scanner(System.in); 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; } String next() { return in.next(); } 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(); if (in == null) return; in.close(); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
e3621690911a4f4a449029e3f986097f
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class A { static FastReader sc=new FastReader(); public static void main(String[] args) { //StringBuffer sb=new StringBuffer(""); int ttt=1; ttt =i(); outer :while (ttt-- > 0) { int n=i(); int m=i(); long A[]=inputL(n); long B[]=inputL(m); HashMap<Long,Long> map=new HashMap<>(); Stack<Long> s=new Stack<>(); for(int i=n-1;i>=0;i--) s.push(A[i]); int c=0; long res=0; while(!s.isEmpty() && c<m) { if(s.peek()==B[c]) { res+=(long)map.size()*2+1;; c++; s.pop(); } else { int t=-1; if(map.containsKey(B[c])) { map.remove(B[c]); c++; res++; continue; } while(!s.isEmpty()) { t++; long f=s.pop(); if(f==B[c]) { res+=(long)map.size()*2+1; c++; break; } else { map.put(f, (long)1); } } } } res+=(long)m-c; System.out.println(res); } // System.out.println(sb.toString()); } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static void input(int A[],int B[]) { for(int i=0;i<A.length;i++) { A[i]=sc.nextInt(); B[i]=sc.nextInt(); } } static int max(int A[]) { int max=Integer.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static int min(int A[]) { int min=Integer.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long max(long A[]) { long max=Long.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static long min(long A[]) { long min=Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long mod(long x) { int mod=1000000007; return ((x%mod + mod)%mod); } static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } 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
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
8a84e1b7b5afae27260e356c38facdba
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.util.*; import java.io.*; public class C { public static void main(String[] args) { FastScanner sc = new FastScanner(); int T = sc.nextInt(); for(int t = 0; t < T; t++) { int n = sc.nextInt(); int m = sc.nextInt(); int[] arr = new int[n]; long[] pos = new long[n]; for(int i = 0; i < n; i++) { arr[i] = sc.nextInt()-1; pos[arr[i]] = i; } long res = 0; long furth = -1; for(long i = 0; i < m; i++) { int b = sc.nextInt()-1; if(pos[b] > furth) { res += 2*(pos[b]-i)+1; } else { res += 1; } furth = Long.max(furth, pos[b]); } System.out.println(res); } } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
d1c9cff48c7c8d490402e69f96fe923b
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; import java.lang.*; import java.math.*; import java.text.DecimalFormat; import java.lang.reflect.Array; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; public class Codeforces{ public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static int MOD = (int)(1e9+7); //static long MOD = 998244353; static FastReader sc = new FastReader(); static int pInf = Integer.MAX_VALUE; static int nInf = Integer.MIN_VALUE; public static void main(String[] args){ int test = 1; test = sc.nextInt(); while(test-->0){ int n = sc.nextInt(); int m = sc.nextInt(); int[] a = new int[n+1]; int[] pos = new int[n+1]; for(int i = 1; i <= n; i++) { a[i] = sc.nextInt(); pos[a[i]] = i; } int[] b = new int[m]; for(int i = 0; i < m; i++) { b[i] = sc.nextInt(); } int[] bpos = new int[m]; bpos[0] = pos[b[0]]; for(int i = 1; i < m; i++) { bpos[i] = Math.max(bpos[i-1], pos[b[i]]); } long ans = 0; for(int i = 0; i < m; i++) { if(bpos[i]== pos[b[i]]) { ans += 2*(bpos[i]-1-(i))+1; } else { ans += 1; } } out.println(ans); //print1d(pos); //print1d(a); } out.close(); } public static long mul(long a, long b){ return ((a%MOD)*(b%MOD))%MOD; } public static int add(int a, int b){ return ((a%MOD)+(b%MOD))%MOD; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Integer.lowestOneBit(i) Equals k where k is the position of the first one in the binary //Integer.highestOneBit(i) Equals k where k is the position of the last one in the binary //Integer.bitCount(i) returns the number of one-bits //Collections.sort(A,(p1,p2)->(int)(p2.x-p1.x)) To sort ArrayList in descending order wrt values of x. // Arrays.parallelSort(a,new Comparator<TPair>() { // public int compare(TPair a,TPair b) { // if(a.y==b.y) return a.x-b.x; // return b.y-a.y; // } // }); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //PrimeFactors public static ArrayList<Long> primeFactors(long n) { ArrayList<Long> arr = new ArrayList<>(); if (n % 2 == 0) arr.add((long) 2); while (n % 2 == 0) n /= 2; for (long i = 3; i <= Math.sqrt(n); i += 2) { int flag = 0; while (n % i == 0) { n /= i; flag = 1; } if (flag == 1) arr.add(i); } if (n > 2) arr.add(n); return arr; } //Pair Class static class Pair implements Comparable<Pair>{ int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if(this.x==o.x){ return (this.y-o.y); } return (this.x-o.x); } } static class TPair implements Comparable<TPair>{ int two; int three; int prime; public TPair(int two, int three, int prime) { this.two = two; this.three = three; this.prime = prime; } @Override public int compareTo(TPair o) { if(this.three==o.three){ return (this.two-o.two); } return -1*(this.three-o.three); } } //nCr static long ncr(long n, long k) { long ret = 1; for (long x = n; x > n - k; x--) { ret *= x; ret /= (n - x + 1); } return ret; } static long finextDoubleMMI_fermat(long n,int M) { return fastExpo(n,M-2); } static long nCrModPFermat(int n, int r, int p) { if (r == 0) return 1; long[] fac = new long[n+1]; fac[0] = 1; for (int i = 1 ;i <= n; i++) fac[i] = fac[i-1] * i % p; return (fac[n]* finextDoubleMMI_fermat(fac[r], p)% p * finextDoubleMMI_fermat(fac[n-r], p) % p) % p; } //Kadane's Algorithm static long maxSubArraySum(ArrayList<Long> a) { if(a.size()==0) { return 0; } long max_so_far = a.get(0); long curr_max = a.get(0); for (int i = 1; i < a.size(); i++) { curr_max = Math.max(a.get(i), curr_max+a.get(i)); max_so_far = Math.max(max_so_far, curr_max); } return max_so_far; } //Merge Sort static void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long [n1]; long R[] = new long [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() static void sort(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); } } //Brian Kernighans Algorithm static long countSetBits(long n){ if(n==0) return 0; return 1+countSetBits(n&(n-1)); } //Factorial static long factorial(long n){ if(n==1) return 1; if(n==2) return 2; if(n==3) return 6; return n*factorial(n-1); } //Euclidean Algorithm static long gcd(long A,long B){ if(B==0) return A; return gcd(B,A%B); } //Modular Exponentiation static long fastExpo(long x,long n){ if(n==0) return 1; if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD; return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD; } //AKS Algorithm static boolean isPrime(long 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<=Math.sqrt(n);i+=6) if(n%i==0 || n%(i+2)==0) return false; return true; } //Reverse an array static <T> void reverse(T arr[],int l,int r){ Collections.reverse(Arrays.asList(arr).subList(l, r)); } //Print array static void print1d(int arr[]) { out.println(Arrays.toString(arr)); } static void print2d(int arr[][]) { for(int a[]: arr) out.println(Arrays.toString(a)); } //Sieve of eratosthenes static int[] findPrimes(int n){ boolean isPrime[]=new boolean[n+1]; ArrayList<Integer> a=new ArrayList<>(); int result[]; Arrays.fill(isPrime,true); isPrime[0]=false; isPrime[1]=false; for(int i=2;i*i<=n;++i){ if(isPrime[i]==true){ for(int j=i*i;j<=n;j+=i) isPrime[j]=false; } } for(int i=0;i<=n;i++) if(isPrime[i]==true) a.add(i); result=new int[a.size()]; for(int i=0;i<a.size();i++) result[i]=a.get(i); return result; } //Indivisual factors of all nos till n static ArrayList<Integer>[] indiFactors(int n){ ArrayList<Integer>[] A = new ArrayList[n+1]; for(int i = 0; i <= n; i++) { A[i] = new ArrayList<>(); } int[] sieve = new int[n+1]; for(int i=2;i<=n;i++) { if(sieve[i]==0) { for(int j=i;j<=n;j+=i) if(sieve[j]==0) { //sieve[j]=i; A[j].add(i); } } } return A; } //Segmented Sieve static boolean[] segmentedSieve(long l, long r){ boolean[] segSieve = new boolean[(int)(r-l+1)]; Arrays.fill(segSieve, true); int[] prePrimes = findPrimes((int)Math.sqrt(r)); for(int p:prePrimes) { long low = (l/p)*p; if(low < l) { low += p; } if(low == p) { low += p; } for(long j = low; j<= r; j += p) { segSieve[(int) (j-l)] = false; } } if(l==1) { segSieve[0] = false; } return segSieve; } //Euler Totent function static long countCoprimes(long n){ ArrayList<Long> prime_factors=new ArrayList<>(); long x=n,flag=0; while(x%2==0){ if(flag==0) prime_factors.add(2L); flag=1; x/=2; } for(long i=3;i*i<=x;i+=2){ flag=0; while(x%i==0){ if(flag==0) prime_factors.add(i); flag=1; x/=i; } } if(x>2) prime_factors.add(x); double ans=(double)n; for(Long p:prime_factors){ ans*=(1.0-(Double)1.0/p); } return (long)ans; } static long modulo = (long)1e9+7; public static long modinv(long x){ return modpow(x, modulo-2); } public static long modpow(long a, long b){ if(b==0){ return 1; } long x = modpow(a, b/2); x = (x*x)%modulo; if(b%2==1){ return (x*a)%modulo; } return x; } public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
66bb803418885ceb9200c758085ed850
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.util.*; public class CodeForces { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long t = scanner.nextLong(); while ((t-- != 0)) { long n = scanner.nextLong(); long m = scanner.nextLong(); Map<Long, Long> map = new HashMap<>(); for (long i = 0; i < n; i++) { long ai = scanner.nextLong(); map.put(ai, i); } long ans = 0; long prevPresentIndex = 0; for (long i = 0; i < m; i++) { long bi = scanner.nextLong(); if (i != 0 && map.get(bi) < prevPresentIndex) { ans++; } else { ans += 2 * (map.get(bi)-i) + 1; } prevPresentIndex = Math.max(map.get(bi), prevPresentIndex); } /** * 7 => 2 * 2 => 0 * 5 => 5 - 2 * 4 => 4 2 1 7 3 4 5 6 6 2 5 4 3 1 7 * * 6 2 5 4 3 1 7 * 5 1 7 1 1 1 1 */ System.out.println(ans); } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
4a31d5cbdb5d32f3dd77b16bb73ecf93
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; public class A implements Runnable { public void run() { InputReader sc = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t=sc.nextInt(); while(t--!=0) { int n=sc.nextInt(); int m=sc.nextInt(); int a[]=new int[n]; int b[]=new int[m]; HashMap<Integer,Integer> map=new HashMap<>(); for(int i=0;i<n;i++) { a[i]=sc.nextInt(); map.put(a[i],i); } sa(b,sc); long time=0; int processedtill=0; int in=0; boolean set[]=new boolean[100005]; for(int i=0;i<m;i++) { if(set[b[i]]) { time++; in++; continue; } int j=map.get(b[i]); if(j>=processedtill) { while(processedtill<j) { set[a[processedtill++]]=true; } } time++; time+=2*(j-in); in++; } out.println(time); } out.close(); } //======================================================== static class Pair { int a,b; Pair(int aa,int bb) { a=aa; b=bb; } } static void sa(int a[],InputReader sc) { for(int i=0;i<a.length;i++) { a[i]=sc.nextInt(); } } 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 A(),"Main",1<<27).start(); } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
915db44d8d7a578b805bf461ced153a2
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.InputMismatchException; public class A { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub InputReader s = new InputReader(System.in); PrintWriter p = new PrintWriter(System.out); int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); int m = s.nextInt(); int[] arr = new int[n]; int[] cal = new int[100001]; for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); } HashMap<Integer, Integer> map = new HashMap<>(); int[] marr = new int[m]; for (int i = 0; i < m; i++) { int val = s.nextInt(); marr[i] = val; map.put(val, 1); } long above = -1; long ans = 0; int curr = 0; long removed = 0; for (int i = 0; i < n; i++) { int flag = 0; for (int j = curr; j < m; j++) { if (cal[marr[j]] == 0) { curr = j; flag = 1; break; }else { above--; } } above++; if (flag == 0) { break; } int val = arr[i]; int find = marr[curr]; if (val == find) { ans += 2 * above + 1; cal[val] = 1; removed = 0; } else if (map.containsKey(val) && cal[val] == 0) { ans++; cal[val] = 1; removed++; } } System.out.println(ans); } p.flush(); p.close(); } static class pair implements Comparable<pair> { Integer x, y; pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if (result == 0) result = y.compareTo(o.y); return result; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x - x == 0 && p.y - y == 0; } return false; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); } } public static ArrayList Divisors(long n) { ArrayList<Long> div = new ArrayList<>(); for (long i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { div.add(i); if (n / i != i) div.add(n / i); } } return div; } public static int BinarySearch(long[] a, long k) { int n = a.length; int i = 0, j = n - 1; int mid = 0; if (k < a[0]) return 0; else if (k >= a[n - 1]) return n; else { while (j - i > 1) { mid = (i + j) / 2; if (k >= a[mid]) i = mid; else j = mid; } } return i + 1; } public static long GCD(long a, long b) { if (b == 0) return a; else return GCD(b, a % b); } public static long LCM(long a, long b) { return (a * b) / GCD(a, b); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class CodeX { public static void sort(long arr[]) { merge_sort(arr, 0, arr.length - 1); } private static void merge_sort(long A[], long start, long end) { if (start < end) { long mid = (start + end) / 2; merge_sort(A, start, mid); merge_sort(A, mid + 1, end); merge(A, start, mid, end); } } private static void merge(long A[], long start, long mid, long end) { long p = start, q = mid + 1; long Arr[] = new long[(int) (end - start + 1)]; long k = 0; for (int i = (int) start; i <= end; i++) { if (p > mid) Arr[(int) k++] = A[(int) q++]; else if (q > end) Arr[(int) k++] = A[(int) p++]; else if (A[(int) p] < A[(int) q]) Arr[(int) k++] = A[(int) p++]; else Arr[(int) k++] = A[(int) q++]; } for (int i = 0; i < k; i++) { A[(int) start++] = Arr[i]; } } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
78e260170716570628792963034afe99
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.util.*; import java.io.*;; public class E { static ArrayList<Integer> primes; // generated by sieve /* * 1. Generating a list of prime factors of N */ static ArrayList<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N)) { ArrayList<Long> factors = new ArrayList<Long>(); // take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while (p * 1l * p <= N) { if (N % p == 0) factors.add((long) p); while (N % p == 0) { N /= p; } p = primes.get(++idx); } if (N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static int[] isComposite; static void sieve(int N) // O(N log log N) { isComposite = new int[N + 1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); for (int i = 2; i <= N; ++i) // can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) // can loop in 2 and odd integers for slightly better performance { primes.add(i); if (1l * i * i <= N) for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in // modified sieve isComposite[j] = 1; } } static ArrayList<Integer>[] adjList; static int V, counter, SCC, dfs_num[], dfs_low[]; static boolean[] inSCC; static Stack<Integer> stack; static int[] cost; static long ans; static long r; static void tarjanSCC() // O(V + E) { for (int i = 0; i < V; ++i) if (dfs_num[i] == 0) tarjanSCC(i); } static void tarjanSCC(int u) { dfs_num[u] = dfs_low[u] = ++counter; stack.push(u); for (int v : adjList[u]) { if (dfs_num[v] == 0) tarjanSCC(v); if (!inSCC[v]) dfs_low[u] = Math.min(dfs_low[u], dfs_low[v]); } if (dfs_num[u] == dfs_low[u]) { // SCC found SCC++; int c = 0; int min = 1000000000; while (true) { int v = stack.pop(); if (min > cost[v]) { c = 1; min = cost[v]; } else if (min == cost[v]) c++; inSCC[v] = true; if (v == u) break; } r = r + min; ans = (ans * 1l * c) % 1000000007; } } static int[] a; static ArrayList<Integer> arr; static int n; static int m; static int k1; static int k2; static long[][][][] memo; static long dp(int idx, int t, int c, int l) { if (idx == n + m) { return 1; } if (t == n) { if (n + m - idx > k2) return 0; else return 1; } if (idx - t == m) { if (n - t > k1) return 0; else return 1; } if (memo[idx][t][c][l] != -1) return memo[idx][t][c][l]; long max = 0; if (l == 0) { if (c == k1) max += dp(idx + 1, t, 1, 1); else { max += (dp(idx + 1, t + 1, c + 1, l) + dp(idx + 1, t, 1, 1)) % 100000000; } } else { if (c == k2) max += dp(idx + 1, t + 1, 1, 0); else { max += (dp(idx + 1, t, c + 1, l) + dp(idx + 1, t + 1, 1, 0)) % 100000000; } } return memo[idx][t][c][l] = max; } static long[] cum; static int bin(long x) { int s = 0; int e = cum.length - 1; int ans = -1; while (s <= e) { int mid = (s + e) / 2; if (cum[mid] <= x) { ans = mid; s = mid + 1; } else e = mid - 1; } return ans; } public static void main(String[] args) throws NumberFormatException, IOException, InterruptedException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); while (n-- > 0) { StringTokenizer st = new StringTokenizer(br.readLine()); int l = Integer.parseInt(st.nextToken()); int s = Integer.parseInt(st.nextToken()); Queue<Integer> q = new LinkedList<Integer>(); Queue<Integer> q2 = new LinkedList<Integer>(); int[] a = new int[l]; int[] b = new int[s]; HashSet<Integer> h1 = new HashSet<>(); HashSet<Integer> h2 = new HashSet<>(); st = new StringTokenizer(br.readLine()); for (int i = 0; i < l; i++) { // q.add(Integer.parseInt(st.nextToken())); a[i] = Integer.parseInt(st.nextToken()); } st = new StringTokenizer(br.readLine()); for (int i = 0; i < s; i++) { int x = Integer.parseInt(st.nextToken()); // q2.add(x); b[i] = x; h1.add(x); } long t = 0; long c = 0; int id1 = 0; int id2 = 0; while (a[id1] != b[id2]) { if (h1.contains(a[id1])) h2.add(a[id1]); c++; id1++; } t += 2 * c + 1; id1++; id2++; for (int i = 0; i < s - 1; i++) { if (h2.contains(b[id2])) { t++; c--; } else { while (a[id1] != b[id2]) { if (h1.contains(a[id1])) h2.add(a[id1]); c++; id1++; } t += 2 * c + 1; id1++; } id2++; } pw.println(t); } pw.flush(); pw.close(); } static long dis(int x, int y, int z, int w) { return (x - z) * (x - z) + (y - w) * (y - w); } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static class pair implements Comparable<pair> { int x; int y; public pair(int d, int u) { x = d; y = u; } @Override public int compareTo(pair o) { // TODO Auto-generated method stub if (x == o.x) return y - o.y; return x - o.x; } } static class triple implements Comparable<triple> { int x; int y; int z; public triple(int a, int b, int c) { x = a; y = b; z = c; } @Override public int compareTo(triple o) { // TODO Auto-generated method stub return y - o.y; } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
09e9d8128ce7ac477891abfee8535220
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.util.*; public class CF_1279_C { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int m=sc.nextInt(); int arr[]=new int[n]; int brr[]=new int[m]; HashMap<Integer,Integer> hm=new HashMap<>(); for(int i=0;i<n;++i) { arr[i]=sc.nextInt(); hm.put(arr[i],i); } for(int i=0;i<m;++i) { brr[i]=sc.nextInt(); } int count=1; int max=hm.get(brr[0]); long k=2*max+1; for(int i=1;i<m;++i) { int c=hm.get(brr[i]); if(c>max) { k+=2*(c-count)+1; max=c; } else { k+=1; } count++; } System.out.println(k); } } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
4d8a9a0dc0409f2851b0194bc31be426
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
//package com.company; import java.util.*; public class Main { static long solve(int[] a, int[] b) { HashMap<Integer, Integer> positions = new HashMap<>(); for (int i = 0; i < a.length; i++) { positions.put(a[i], i); } long result = 0; int sent = 0; int max = 0; for (int i = 0; i < b.length; i++) { int pos = positions.get(b[i]); if (pos < max) { result += 1; } else { result += (pos - sent) * 2 + 1; max = pos; } sent++; } return result; } // static void test(int[] a, int[] b, int expected) { // int res = solve(a, b); // if (res != expected) { // throw new Error(Integer.toString(res)); // } // } static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int t = scanner.nextInt(); for (int i = 0; i < t; i++) { int n = scanner.nextInt(); int m = scanner.nextInt(); int[] a = new int[n]; for (int j = 0; j < n; j++) { a[j] = scanner.nextInt(); } int[] b = new int[m]; for (int j = 0; j < m; j++) { b[j] = scanner.nextInt(); } System.out.println(solve(a, b)); } // test(new int[] { 3, 1, 2 }, new int[] { 3, 2, 1 }, 5); // test(new int[] { 2, 1, 7, 3, 4, 5, 6 }, new int[] { 3, 1 }, 8); } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
75d147c60b20abb2eba7cc44f5eb172f
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; /** * @author madi.sagimbekov */ public class C1279C { private static BufferedReader in; private static BufferedWriter out; private static List<Integer>[] list; private static int[] arr; private static int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; private static boolean[] used; public static void main(String[] args) throws IOException { open(); int t = readInt(); while (t-- > 0) { int[] nm = readInts(); int n = nm[0]; int m = nm[1]; int[] a = readInts(); int[] b = readInts(); Set<Integer> set = new HashSet<>(); int i = 0; int j = 0; long res = 0; while (j < m) { int pod = b[j]; if (set.contains(pod)) { res++; } else { while (!set.contains(pod)) { set.add(a[i++]); } res += 2 * (long) set.size() - 1; } set.remove(pod); j++; } out.write(res + " \n"); } close(); } private static int[] readInts() throws IOException { return Stream.of(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } private static int readInt() throws IOException { return Integer.parseInt(in.readLine()); } private static long[] readLongs() throws IOException { return Stream.of(in.readLine().split(" ")).mapToLong(Long::parseLong).toArray(); } private static long readLong() throws IOException { return Long.parseLong(in.readLine()); } private static double[] readDoubles() throws IOException { return Stream.of(in.readLine().split(" ")).mapToDouble(Double::parseDouble).toArray(); } private static double readDouble() throws IOException { return Double.parseDouble(in.readLine()); } private static String readString() throws IOException { return in.readLine(); } private static List<Integer>[] buildAdjacencyList(int n, int m) throws IOException { List<Integer>[] list = new ArrayList[n + 1]; for (int i = 0; i <= n; i++) { list[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int[] e = readInts(); list[e[0]].add(e[1]); list[e[1]].add(e[0]); } return list; } private static void open() { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter((System.out))); } private static void close() throws IOException { out.flush(); out.close(); in.close(); } }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
cc70a58a998845580b004f697cab0cd9
train_002.jsonl
1577457600
Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up β€” when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.
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.Comparator; import java.util.Objects; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.function.BiFunction; import java.util.function.Function; public class Main { static BiFunction<Integer, Integer, Integer> ADD = (x, y) -> (x + y); static Function<Pair<Integer, Integer>, Integer> GET_FIRST = (x) -> (x.first); static Function<Pair<Integer, Integer>, Integer> GET_SECOND = (x) -> (x.second); static Comparator<Pair<Integer, Integer>> C = Comparator.comparing(GET_FIRST).thenComparing(GET_SECOND); public static void main(String[] args) throws Exception { long startTime = System.nanoTime(); int t = in.nextInt(); while (t-- > 0) { solve(); } long endTime = System.nanoTime(); err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms"); exit(0); } static void solve() { int n = in.nextInt(); int m = in.nextInt(); TreeSet<Pair<Integer, Integer>> S = new TreeSet<>(Comparator.comparing(Pair::getFirst)); int[] a = in.readAllInts(n); int[] b = in.readAllInts(m); long ans = m; int[] pos = new int[100010]; for (int i = 0; i < n; i++) { pos[a[i]] = i; } int l = -1; for (int i = 0; i < m; i++) { if (pos[b[i]] > l) { ans += 2 * (pos[b[i]] - i); l = pos[b[i]]; } } out.println(ans); } static int find(int[] data, int start, int val) { for (int i = start; i < data.length; i++) { if (data[i] == val) { return i; } } return -1; } static void debug(Object... args) { for (Object a : args) { out.println(a); } } static void y() { out.println("YES"); } static void n() { out.println("NO"); } static void fail() { out.println("-1"); exit(0); } static class Pair<T, R> { public T first; public R second; public Pair(T first, R second) { this.first = first; this.second = second; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(first, pair.first) && Objects.equals(second, pair.second); } @Override public int hashCode() { return Objects.hash(first, second); } @Override public String toString() { return "Pair{" + "a=" + first + ", b=" + second + '}'; } public T getFirst() { return first; } public R getSecond() { return second; } } static <T, R> Pair<T, R> make_pair(T a, R b) { return new Pair<>(a, b); } static class ArrayUtils { static int[] reverse(int[] data) { int[] p = new int[data.length]; for (int i = 0, j = data.length - 1; i < data.length; i++, j--) { p[i] = data[j]; } return p; } static void prefixSum(long[] data) { for (int i = 1; i < data.length; i++) { data[i] += data[i - 1]; } } static void prefixSum(int[] data) { for (int i = 1; i < data.length; i++) { data[i] += data[i - 1]; } } static long[] reverse(long[] data) { long[] p = new long[data.length]; for (int i = 0, j = data.length - 1; i < data.length; i++, j--) { p[i] = data[j]; } return p; } static char[] reverse(char[] data) { char[] p = new char[data.length]; for (int i = 0, j = data.length - 1; i < data.length; i++, j--) { p[i] = data[j]; } return p; } static int[] MergeSort(int[] A) { if (A.length > 1) { int q = A.length / 2; int[] left = new int[q]; int[] right = new int[A.length - q]; System.arraycopy(A, 0, left, 0, q); System.arraycopy(A, q, right, 0, A.length - q); int[] left_sorted = MergeSort(left); int[] right_sorted = MergeSort(right); return Merge(left_sorted, right_sorted); } else { return A; } } static int[] Merge(int[] left, int[] right) { int[] A = new int[left.length + right.length]; int i = 0; int j = 0; for (int k = 0; k < A.length; k++) { // To handle left becoming empty if (i == left.length && j < right.length) { A[k] = right[j]; j++; continue; } // To handle right becoming empty if (j == right.length && i < left.length) { A[k] = left[i]; i++; continue; } if (left[i] <= right[j]) { A[k] = left[i]; i++; } else { A[k] = right[j]; j++; } } return A; } static long[] MergeSort(long[] A) { if (A.length > 1) { int q = A.length / 2; long[] left = new long[q]; long[] right = new long[A.length - q]; System.arraycopy(A, 0, left, 0, q); System.arraycopy(A, q, right, 0, A.length - q); long[] left_sorted = MergeSort(left); long[] right_sorted = MergeSort(right); return Merge(left_sorted, right_sorted); } else { return A; } } static long[] Merge(long[] left, long[] right) { long[] A = new long[left.length + right.length]; int i = 0; int j = 0; for (int k = 0; k < A.length; k++) { // To handle left becoming empty if (i == left.length && j < right.length) { A[k] = right[j]; j++; continue; } // To handle right becoming empty if (j == right.length && i < left.length) { A[k] = left[i]; i++; continue; } if (left[i] <= right[j]) { A[k] = left[i]; i++; } else { A[k] = right[j]; j++; } } return A; } } 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 long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public int[] readAllInts(int n) { int[] p = new int[n]; for (int i = 0; i < n; i++) { p[i] = in.nextInt(); } return p; } public int[] readAllInts(int n, int s) { int[] p = new int[n + s]; for (int i = s; i < n + s; i++) { p[i] = in.nextInt(); } return p; } public long[] readAllLongs(int n) { long[] p = new long[n]; for (int i = 0; i < n; i++) { p[i] = in.nextLong(); } return p; } public long[] readAllLongs(int n, int s) { long[] p = new long[n + s]; for (int i = s; i < n + s; i++) { p[i] = in.nextLong(); } return p; } public double nextDouble() { return Double.parseDouble(next()); } } static void exit(int a) { out.close(); err.close(); System.exit(a); } static InputStream inputStream = System.in; static OutputStream outputStream = System.out; static OutputStream errStream = System.err; static InputReader in = new InputReader(inputStream); static PrintWriter out = new PrintWriter(outputStream); static PrintWriter err = new PrintWriter(errStream); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); }
Java
["2\n3 3\n3 1 2\n3 2 1\n7 2\n2 1 7 3 4 5 6\n3 1"]
1 second
["5\n8"]
null
Java 8
standard input
[ "data structures", "implementation" ]
ad434880e047992d2c77e0fe0ce0976f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) β€” the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) β€” the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) β€” the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case print one integer β€” the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
standard output
PASSED
f32d8edca030ba7075773bce7c9a36b4
train_002.jsonl
1453388400
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; /** * Created by alex on 2/1/16. * problem found at: http://codeforces.com/contest/620/problem/C */ public class PearlsInARow { public static void main(String[] args){ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ String n = br.readLine(); String numbers = br.readLine(); String[] temp = numbers.split(" "); int[] nums = new int[temp.length]; for(int i=0; i<temp.length; i++){ nums[i] = Integer.parseInt(temp[i]); } int newStart = -1; HashMap<Integer, Integer> seen = new HashMap<>(); ArrayList<Segment> segments = new ArrayList<>(); for(int i=0; i<nums.length; i++){ if(seen.containsKey(nums[i])){ segments.add(new Segment(newStart, i+1)); seen.clear(); newStart = -1; } else{ if(newStart == -1){ newStart = i+1; } seen.put(nums[i], i); } } if(segments.size() == 0){ System.out.println(-1); return; } System.out.println(segments.size()); for(int i=0; i<segments.size(); i++){ if(i != segments.size()-1){ System.out.println(segments.get(i).start + " " + segments.get(i).end); } else{ System.out.println(segments.get(i).start + " " + nums.length); } } } catch(IOException io){ io.printStackTrace(); } } public static class Segment{ int start; int end; public Segment(int a, int b){ this.start = a; this.end = b; } } }
Java
["5\n1 2 3 4 1", "5\n1 2 3 4 5", "7\n1 2 1 3 1 2 1"]
2 seconds
["1\n1 5", "-1", "2\n1 3\n4 7"]
null
Java 8
standard input
[ "greedy" ]
4cacec219e4577b255ddf6d39d308e10
The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of pearls in a row. The second line contains n integers ai (1 ≀ ai ≀ 109) – the type of the i-th pearl.
1,500
On the first line print integer k β€” the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".
standard output
PASSED
06a78defbcde150f9cc2b772f0c17d7f
train_002.jsonl
1453388400
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
256 megabytes
import javafx.util.Pair; import java.io.*; import java.util.*; import java.math.*; import java.lang.*; public class Main { static Scanner in = new Scanner(System.in); public static void main(String[] args) { Set<Integer> st=null; List<Pair<Integer, Integer>> ans = new ArrayList<>(); int n = in.nextInt(); int left=0; for(int i=1; i<=n; i++) { int temp = in.nextInt(); if(st==null) { left=i; st = new HashSet<>(); st.add(temp); } else if(st.contains(temp)) { st=null; ans.add(new Pair<>(left, i)); } else { st.add(temp); } } if(ans.isEmpty()) System.out.println(-1); else { System.out.println(ans.size()); for(int i=0; i<ans.size()-1; i++) { System.out.println(ans.get(i).getKey() + " " + ans.get(i).getValue()); } System.out.println(ans.get(ans.size()-1).getKey() + " " + n); } } }
Java
["5\n1 2 3 4 1", "5\n1 2 3 4 5", "7\n1 2 1 3 1 2 1"]
2 seconds
["1\n1 5", "-1", "2\n1 3\n4 7"]
null
Java 8
standard input
[ "greedy" ]
4cacec219e4577b255ddf6d39d308e10
The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of pearls in a row. The second line contains n integers ai (1 ≀ ai ≀ 109) – the type of the i-th pearl.
1,500
On the first line print integer k β€” the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".
standard output
PASSED
f01fb6fe739535407f844cacc07d72d5
train_002.jsonl
1453388400
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
256 megabytes
import java.util.*; import java.io.*; public class test { public static void main(String [] args)throws IOException {InputStreamReader iy=new InputStreamReader(System.in);PrintWriter pw=new PrintWriter(System.out); BufferedReader br=new BufferedReader(iy); int n=Integer.parseInt(br.readLine()); String s[]=br.readLine().split(" "); int ar[]=new int[n]; for(int i=0;i<n;i++) { ar[i]=Integer.parseInt(s[i]);} ArrayList<int[]> res=new ArrayList<int[]>(); HashSet<Integer> h=new HashSet<Integer>(); int split=0;int st=1; for(int i=0;i<n;i++) { if(h.contains(ar[i])) { split+=1; res.add(new int[]{st,i+1}); h.clear(); st=i+2;} else h.add(ar[i]); } if(split==0){ pw.println(-1); pw.flush();} else{pw.println(split); for(int i=0;i<res.size();i++) { if(i==res.size()-1) { int ff[]=res.get(i); int one=ff[0];int two=ff[1]; if(two!=n) pw.println(one+" "+n); else pw.println(one+" "+two); } else{ int ff[]=res.get(i); int one=ff[0];int two=ff[1]; pw.println(one+" "+two);}} pw.flush();}}}
Java
["5\n1 2 3 4 1", "5\n1 2 3 4 5", "7\n1 2 1 3 1 2 1"]
2 seconds
["1\n1 5", "-1", "2\n1 3\n4 7"]
null
Java 8
standard input
[ "greedy" ]
4cacec219e4577b255ddf6d39d308e10
The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of pearls in a row. The second line contains n integers ai (1 ≀ ai ≀ 109) – the type of the i-th pearl.
1,500
On the first line print integer k β€” the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".
standard output
PASSED
e33ce0b4a933c6fe6d1d2ce6f3a814e7
train_002.jsonl
1453388400
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class Main { int[] a; Set<Integer> set; int[] ansl; int[] ansr; public void solve() { FastScanner scan = new FastScanner(); int n = scan.nextInt(); a = new int[n + 1]; ansl = new int[n + 1]; ansr = new int[n + 1]; set = new HashSet<Integer>(); for (int i = 1; i <= n; i++) { a[i] = scan.nextInt(); } int ans = 0; int left = 1; for (int i = 1; i <= n; i++) { if (set.contains(a[i])) { // System.out.println(left + " " + i); ansl[ans] = left; ansr[ans] = i; left = i + 1; set.clear(); ans++; }else{ set.add(a[i]); } } if(ans>0){ System.out.println(ans); for(int i=0;i<ans;i++){ if(i==ans-1){ ansr[i] = n; } System.out.println(ansl[i]+" "+ansr[i]); } }else{ System.out.println(-1); } } public static void main(String[] args) { new Main().solve(); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public boolean EOF() { if (st != null && st.hasMoreTokens()) { return false; } else { String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (line == null) return true; st = new StringTokenizer(line); return false; } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["5\n1 2 3 4 1", "5\n1 2 3 4 5", "7\n1 2 1 3 1 2 1"]
2 seconds
["1\n1 5", "-1", "2\n1 3\n4 7"]
null
Java 8
standard input
[ "greedy" ]
4cacec219e4577b255ddf6d39d308e10
The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of pearls in a row. The second line contains n integers ai (1 ≀ ai ≀ 109) – the type of the i-th pearl.
1,500
On the first line print integer k β€” the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".
standard output
PASSED
20c9399ba103a2131fd38d8cfd6e5b18
train_002.jsonl
1453388400
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
256 megabytes
import java.util.*; public class C620 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[][] indexes = new int [n][3]; int k = 0; int indBegin = 0; HashSet<Long> set = new HashSet<>(); for (int i = 0; i < n; i++) { long a = scan.nextLong(); if (!set.contains(a)) { set.add(a); } else { indexes[k][1] = indBegin; indexes[k++][2] = i; indBegin = i + 1; set.clear(); } } if (k > 0) { indexes[--k][2] = n - 1; k++; System.out.println(k); for (int i = 0; i < k; i++) { System.out.println( (indexes[i][1] + 1) + " " + (indexes[i][2] + 1)); } } else { System.out.println(-1); } } }
Java
["5\n1 2 3 4 1", "5\n1 2 3 4 5", "7\n1 2 1 3 1 2 1"]
2 seconds
["1\n1 5", "-1", "2\n1 3\n4 7"]
null
Java 8
standard input
[ "greedy" ]
4cacec219e4577b255ddf6d39d308e10
The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of pearls in a row. The second line contains n integers ai (1 ≀ ai ≀ 109) – the type of the i-th pearl.
1,500
On the first line print integer k β€” the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".
standard output
PASSED
648b9bb560826d588feefc9b9b228c50
train_002.jsonl
1453388400
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
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.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.Stack; public class test { private static int[] SEG = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6}; private static int segments(int v) { if(v == 0) return 6; int res = 0; while(v > 0) { res += SEG[v%10]; v /= 10; } return res; } public static void main(String[] args) throws InterruptedException { //new careercup().run(); //new CC().run(); try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[] s = br.readLine().split(" "); int[] pearl = new int[n]; for(int i=0; i<n; i++) pearl[i] = Integer.parseInt(s[i]); Set<Integer> v2p = new HashSet<>(); List<String> res = new ArrayList<>(); int start = 0; for(int i=0; i<pearl.length; i++) { if(v2p.contains(pearl[i])) { res.add((start+1)+" "+(i+1)); v2p.clear(); start = i+1; } else { v2p.add(pearl[i]); } } if(res.isEmpty()) { System.out.println(-1); } else { System.out.println(res.size()); String ts = res.get(res.size()-1).split(" ")[0] + " " + pearl.length; res.set(res.size()-1, ts); for(String ss : res) System.out.println(ss); } }catch(IOException io){ io.printStackTrace(); } } }
Java
["5\n1 2 3 4 1", "5\n1 2 3 4 5", "7\n1 2 1 3 1 2 1"]
2 seconds
["1\n1 5", "-1", "2\n1 3\n4 7"]
null
Java 8
standard input
[ "greedy" ]
4cacec219e4577b255ddf6d39d308e10
The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of pearls in a row. The second line contains n integers ai (1 ≀ ai ≀ 109) – the type of the i-th pearl.
1,500
On the first line print integer k β€” the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".
standard output
PASSED
ca8ff6a6d513e6ec0b96738e2ae67961
train_002.jsonl
1453388400
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.lang.Integer; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author toghru */ public class Main { public static void main(String[] args) throws InterruptedException, IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); InputReader in = new InputReader(inputStream); int n = in.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) { a[i] = in.nextInt(); } int l = 0; Set<Integer> s = new HashSet<Integer>(); int[][] ans = new int[n][2]; int k = 0; for(int i = 0; i < n; i++) { if(s.contains(a[i])) { ans[k][0] = l; ans[k][1] = i; k++; s.clear(); l = i + 1; }else s.add(a[i]); } if(k == 0) { out.println(-1); out.close(); return; } out.println(k); for(int i = 0; i < k; i++) { if(i == k - 1) { out.println((ans[i][0] + 1) + " " + (n)); }else { out.println((ans[i][0] + 1) + " " + (ans[i][1] + 1)); } } out.close(); } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream), 32624); tokenizer = null; } // suigns dasndasdas public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } private long nextLong() { return Long.parseLong(next()); } private BigInteger nextBigInteger() { return new BigInteger(next()); } } }
Java
["5\n1 2 3 4 1", "5\n1 2 3 4 5", "7\n1 2 1 3 1 2 1"]
2 seconds
["1\n1 5", "-1", "2\n1 3\n4 7"]
null
Java 8
standard input
[ "greedy" ]
4cacec219e4577b255ddf6d39d308e10
The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of pearls in a row. The second line contains n integers ai (1 ≀ ai ≀ 109) – the type of the i-th pearl.
1,500
On the first line print integer k β€” the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".
standard output
PASSED
0fb1048bcd555330b4e206375897865a
train_002.jsonl
1453388400
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.lang.Integer; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author toghru */ public class Main { public static void main(String[] args) throws InterruptedException, IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); InputReader in = new InputReader(inputStream); int n = in.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) { a[i] = in.nextInt(); } int l = 0; Set<Integer> s = new HashSet<Integer>(); int[][] ans = new int[n][2]; int k = 0; for(int i = 0; i < n; i++) { if(s.contains(a[i])) { ans[k][0] = l; ans[k][1] = i; k++; s.clear(); l = i + 1; }else s.add(a[i]); } if(k == 0) { out.println(-1); out.close(); return; } out.println(k); for(int i = 0; i < k; i++) { if(i == k - 1) { out.println((ans[i][0] + 1) + " " + (n)); }else { out.println((ans[i][0] + 1) + " " + (ans[i][1] + 1)); } } out.close(); } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream), 32624); tokenizer = null; } // suigns dasndasdas public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } private long nextLong() { return Long.parseLong(next()); } private BigInteger nextBigInteger() { return new BigInteger(next()); } } }
Java
["5\n1 2 3 4 1", "5\n1 2 3 4 5", "7\n1 2 1 3 1 2 1"]
2 seconds
["1\n1 5", "-1", "2\n1 3\n4 7"]
null
Java 8
standard input
[ "greedy" ]
4cacec219e4577b255ddf6d39d308e10
The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of pearls in a row. The second line contains n integers ai (1 ≀ ai ≀ 109) – the type of the i-th pearl.
1,500
On the first line print integer k β€” the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".
standard output
PASSED
70464f21f5125e2333878e830965aeee
train_002.jsonl
1453388400
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
256 megabytes
import java.io.*; import java.util.*; public class Educational6B { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer=new PrintWriter(new OutputStreamWriter(System.out)); Set s=new HashSet(); int n=Integer.parseInt(reader.readLine()); int []num=new int[n]; int ans=0; int len=s.size(); int [][]lr=new int[300001][2]; for(int i=0;i<300001;i++) Arrays.fill(lr[i], 0); lr[ans][0]=0; String ss=reader.readLine(); char []c=ss.toCharArray(); int j=0; int k=0; while(j<ss.length()){ if(c[j]==' ') k++; else{ num[k]=num[k]*10+c[j]-'0'; } j++; } for(int i=0;i<n;i++){ s.add(num[i]); if(s.size()>len){ len=s.size(); } else{ s.clear(); len=s.size(); lr[ans][1]=i; ans++; lr[ans][0]=i+1; } } if(lr[ans][1]==0&&ans!=0) lr[ans-1][1]=n-1; if(ans==0) writer.println(-1); else{ writer.println(ans); for(int i=0;i<ans;i++){ writer.println((lr[i][0]+1)+" "+(lr[i][1]+1)); } } writer.close(); } }
Java
["5\n1 2 3 4 1", "5\n1 2 3 4 5", "7\n1 2 1 3 1 2 1"]
2 seconds
["1\n1 5", "-1", "2\n1 3\n4 7"]
null
Java 8
standard input
[ "greedy" ]
4cacec219e4577b255ddf6d39d308e10
The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of pearls in a row. The second line contains n integers ai (1 ≀ ai ≀ 109) – the type of the i-th pearl.
1,500
On the first line print integer k β€” the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".
standard output
PASSED
c27b6398be964b48b696a3aa98f9f5a3
train_002.jsonl
1453388400
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
256 megabytes
import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Educational6B { public static void main(String[] args){ Scanner sc = new Scanner(System.in); Set s=new HashSet(); int n=sc.nextInt(); int []num=new int[n]; int ans=0; int len=s.size(); int [][]lr=new int[300001][2]; for(int i=0;i<300001;i++) Arrays.fill(lr[i], 0); lr[ans][0]=0; for(int i=0;i<n;i++){ num[i]=sc.nextInt(); s.add(num[i]); if(s.size()>len){ len=s.size(); } else{ s.clear(); len=s.size(); lr[ans][1]=i; ans++; lr[ans][0]=i+1; } } if(lr[ans][1]==0&&ans!=0) lr[ans-1][1]=n-1; if(ans==0) System.out.println(-1); else{ System.out.println(ans); for(int i=0;i<ans;i++){ System.out.println((lr[i][0]+1)+" "+(lr[i][1]+1)); } } } }
Java
["5\n1 2 3 4 1", "5\n1 2 3 4 5", "7\n1 2 1 3 1 2 1"]
2 seconds
["1\n1 5", "-1", "2\n1 3\n4 7"]
null
Java 8
standard input
[ "greedy" ]
4cacec219e4577b255ddf6d39d308e10
The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of pearls in a row. The second line contains n integers ai (1 ≀ ai ≀ 109) – the type of the i-th pearl.
1,500
On the first line print integer k β€” the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".
standard output
PASSED
042409a15430f601e206b9a2af0f213c
train_002.jsonl
1453388400
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
256 megabytes
import java.io.*; import java.util.*; public class Solution { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; static final int Mod = 1000000007; static class Pair { int x, y; Pair(int _x, int _y) { x = _x; y = _y; } } void solve() throws IOException { int n = nextInt(); int a[] = new int[n]; Pair p[] = new Pair[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); p[i] = new Pair(a[i], i); } Arrays.sort(p, 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); } }); int t = 0; for (int i = 0; i < n; i++) { if (i == 0 || p[i].x != p[i - 1].x) t++; a[p[i].y] = t; } int cnt[] = new int[350010]; int i, j; Pair last = new Pair(-1, -1); List<Pair> ans = new ArrayList<Pair>(); for (i = 0, j = 0; i < n; i = j + 1) { boolean ok = false; for (j = i; j < n; j++) { if (cnt[a[j]] == 1) { ok = true; break; } cnt[a[j]] = 1; } if (ok) ans.add(last = new Pair(i, j)); for (int k = i; k < n && k <= j; k++) cnt[a[k]] = 0; } if (ans.size() == 0) { out.println(-1); return; } out.println(ans.size()); if (i != n) { ans.remove(last); last.y = n - 1; ans.add(last); } for (Pair o : ans) { out.println((o.x + 1) + " " + (o.y + 1)); } } Solution() 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 Solution(); } 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
["5\n1 2 3 4 1", "5\n1 2 3 4 5", "7\n1 2 1 3 1 2 1"]
2 seconds
["1\n1 5", "-1", "2\n1 3\n4 7"]
null
Java 8
standard input
[ "greedy" ]
4cacec219e4577b255ddf6d39d308e10
The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of pearls in a row. The second line contains n integers ai (1 ≀ ai ≀ 109) – the type of the i-th pearl.
1,500
On the first line print integer k β€” the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".
standard output
PASSED
7eeb561a7b22cdc49653be709bc31184
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
/** * @author derrick20 */ import java.io.*; import java.util.*; public class KGarland { public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int T = sc.nextInt(); while (T-->0) { int N = sc.nextInt(); int K = sc.nextInt(); ArrayList<Character> s = new ArrayList<>(); s.add('_'); for (char c : sc.next().toCharArray()) { s.add(c); } int[] pre = new int[s.size()]; for (int i = 1; i < s.size(); i++) { pre[i] = pre[i - 1] + (s.get(i) == '1' ? 1 : 0); } int[] dp = new int[s.size()]; for (int i = 1; i < s.size(); i++) { int last = Math.max(0, i - K); // either cleanse all before, or build on an old one dp[i] = Math.min(pre[i - 1] - pre[last] + dp[last], pre[i - 1]); if (s.get(i) == '0') { dp[i]++; } } // System.out.println(Arrays.toString(pre)); // System.out.println(Arrays.toString(dp)); int cost = pre[N]; // remove all for (int i = 1; i <= N; i++) { // works till here, cleanse rest cost = Math.min(cost, dp[i] + pre[N] - pre[i]); } out.println(cost); } out.close(); } static class FastScanner { private int BS = 1<<16; private char NC = (char)0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt=1; boolean neg = false; if(c==NC)c=getChar(); for(;(c<'0' || c>'9'); c = getChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=getChar()) { res = (res<<3)+(res<<1)+c-'0'; cnt*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/cnt; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c>32) { res.append(c); c=getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c!='\n') { res.append(c); c=getChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=getChar(); if(c==NC)return false; else if(c>32)return true; } } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
0dae19fd052852807f0febd63a291349
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class CF1353E extends PrintWriter { CF1353E() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1353E o = new CF1353E(); o.main(); o.flush(); } void main() { int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); byte[] cc = sc.next().getBytes(); int cnt1 = 0; for (int i = 0; i < n; i++) if (cc[i] == '1') cnt1++; int ans = cnt1; for (int i = 0; i < k; i++) { int x = 0, y = 0, z = 0; for (int j = i; j < n; j += k) { if (cc[j] == '0') x++; else y++; ans = Math.min(ans, x + z + cnt1 - y); z = Math.min(z, y - x); } } println(ans); } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
e7a75546e7febee1ce17f2a753df7708
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main{ static long MOD = 998244353L; static long [] fac; static int[][] dir = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; static long lMax = 0x3f3f3f3f3f3f3f3fL; static int iMax = 0x3f3f3f3f; public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); // Start writing your solution here. ------------------------------------- int t = sc.nextInt(); //int t = 1; while(t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); String s = sc.nextLine(); int [] left = new int[n]; int [] right = new int[n]; int [] pre = new int[n]; char [] c = s.toCharArray(); pre[0] = c[0] - '0'; left[0] = '1' - c[0]; right[n - 1] = '1' - c[n - 1]; for(int i = 1; i < n; i++) pre[i] = pre[i - 1] + c[i] - '0'; int min = pre[n - 1]; for(int i = 1; i < n; i++) { left[i] = pre[i - 1] + '1' - c[i]; if(i >= k) left[i] = Math.min(left[i], left[i - k] + pre[i - 1] - pre[i - k] + '1' - c[i]); } for(int i = n - 2; i >= 0; i--) { right[i] = pre[n - 1] - pre[i] + '1' - c[i]; if(i + k < n) right[i] = Math.min(right[i], right[i + k] + pre[i + k - 1] - pre[i] + '1' - c[i]); } //System.out.println(Arrays.toString(left)); // System.out.println(Arrays.toString(right)); for(int i = 0; i < n; i++) min = Math.min(min, left[i] + right[i] - '1' + c[i]); out.println(min); } out.close(); } public static long C(int n, int m) { if(m == 0 || m == n) return 1l; if(m > n || m < 0) return 0l; long res = fac[n] * quickPOW((fac[m] * fac[n - m]) % MOD, MOD - 2) % MOD; return res; } public static long quickPOW(long n, long m) { long ans = 1l; while(m > 0) { if(m % 2 == 1) ans = (ans * n) % MOD; n = (n * n) % MOD; m >>= 1; } return ans; } public static int gcd(int a, int b) { if(a % b == 0) return b; return gcd(b, a % b); } public static long gcd(long a, long b) { if(a % b == 0) return b; return gcd(b, a % b); } public static long solve(long x, long[] res){ int n = res.length; long a = x / n; int b = (int)(x % n); return res[n - 1] * a + res[b]; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
f4e40de4b2e678b31b9d02a6d6a49361
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class K_Periodic_Garlands { 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) { // TODO Auto-generated method stub FastReader t = new FastReader(); PrintWriter o = new PrintWriter(System.out); int test = t.nextInt(); while (test-- > 0) { int n = t.nextInt(); int k = t.nextInt(); int[] a = new int[n + 1]; int[] b = new int[n]; String s = t.next(); int sum = 0; a[0] = s.charAt(0) - '0'; for (int i = 1; i < n; ++i) a[i] = a[i - 1] + s.charAt(i) - '0'; for (int i = n - 1; i >= 0; --i) { int ch = Integer.parseInt(s.charAt(i) + ""); int v1, v2; if (i + k < n) { v1 = ((ch) ^ 1) + a[i + k - 1] - a[i] + b[i + k]; v2 = (ch & 1) + a[n - 1] - a[i]; b[i] = Math.min(v1, v2); } else { v1 = a[n - 1] - a[i]; b[i] = v1; } } // for (int i = 0; i < n; ++i) // System.out.print(b[i] + " "); for (int i = 1; i < n; ++i) { b[i] += a[i - 1]; } int min = Integer.MAX_VALUE; for (int i = 0; i < n; ++i) min = Math.min(b[i], min); // o.println(min); } o.flush(); o.close(); } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
7c3e438c992d69b789f3016af296c362
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static void main() throws Exception{ int n=sc.nextInt(),k=sc.nextInt(); int zeros=0,ones=0; char[]in=sc.nextLine().toCharArray(); for(char c:in) { if(c=='0') { zeros++; } else { ones++; } } int ans=ones; int[]pref=new int[n]; for(int i=0;i<k;i++) { int others0=zeros,others1=ones; for(int j=i;j<n;j+=k) { if(in[j]=='0') { others0--; } else { others1--; } } int cnt0=0,cnt1=0; int curans=0; int lastj=-1; for(int j=i;j<n;j+=k) { if(in[j]=='0') { curans=Math.min(curans, cnt1)+1; cnt0++; } else { curans=Math.min(curans, cnt1); cnt1++; } lastj=j; pref[j]=curans; } curans=cnt1; cnt0=0;cnt1=0; for(int j=lastj;j>=0;j-=k) { curans=Math.min(curans, pref[j]+cnt1); if(in[j]=='0') { cnt0++; } else { cnt1++; } } curans+=others1; ans=Math.min(ans, curans); } pw.println(ans); } public static void main(String[] args) throws Exception{ pw=new PrintWriter(System.out); sc = new MScanner(System.in); int tc=sc.nextInt(); while(tc-->0)main(); pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
866d494de16845d44cc34328db3d5a12
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
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.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; 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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); EKPeriodicGarland solver = new EKPeriodicGarland(); solver.solve(1, in, out); out.close(); } static class EKPeriodicGarland { int n; int k; int[] arr; int[] prefix; int[] memo; public void solve(int testNumber, Scanner sc, PrintWriter pw) { int q = sc.nextInt(); while (q-- > 0) { n = sc.nextInt(); k = sc.nextInt(); arr = new int[n]; String s = sc.next(); for (int i = 0; i < n; i++) arr[i] = s.charAt(i) - '0'; prefix = new int[n + k]; prefix[0] = arr[0]; for (int i = 1; i < n + k; i++) prefix[i] = prefix[i - 1] + (i < n ? arr[i] : 0); memo = new int[n + k]; Arrays.fill(memo, -1); int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { min = Math.min(min, (i > 0 ? prefix[i - 1] : 0) + dp(i + k) + (arr[i] == 1 ? 0 : 1)); } pw.println(Math.min(min, prefix[n - 1])); } } private int dp(int i) { if (i >= n) return prefix[i] - prefix[i - k]; if (memo[i] != -1) return memo[i]; int sub = prefix[i - 1] - prefix[i - k]; int temp = dp(i + k); return memo[i] = Math.min(sub + temp + (arr[i] == 1 ? 0 : 1), prefix[n - 1] - prefix[i - k]); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
75f7a03bcc16fdf209a598d3dcb1edb6
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
/** * @author egaeus * @mail sebegaeusprogram@gmail.com * @veredict * @url * @category * @date **/ import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import static java.lang.Integer.parseInt; public class CFE { static char[] arr; static int[] Q; static int N, K; public static void main(String args[]) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int T = parseInt(in.readLine()); for (int t = 0; t < T; t++) { StringTokenizer st = new StringTokenizer(in.readLine()); N = parseInt(st.nextToken()); K = parseInt(st.nextToken()); arr = in.readLine().toCharArray(); Q = new int[N]; for (int i = 0; i < N; i++) { Q[i] = (i > 0 ? Q[i - 1] : 0) + (arr[i] - '0'); mem[i][0] = -1; mem[i][1] = -1; } for(int i=N-1;i>=0;i--) { f(i, true); f(i, false); } System.out.println(f(0, false)); } } static int[][] mem = new int[1000000][2]; static int f(int p, boolean obligatory) { if (p >= N) return 0; if (mem[p][obligatory ? 0 : 1] >= 0) return mem[p][obligatory ? 0 : 1]; int min = N; if (!obligatory) min = f(p + 1, false) + (arr[p] == '1' ? 1 : 0); int s = 0, s1 = 0; if (arr[p] == '0') { s++; s1++; } s1 += Q[N - 1] - Q[p]; s += f(p + K, true) + Q[Math.min(p + K - 1, N - 1)] - Q[p]; return mem[p][obligatory ? 0 : 1] = Math.min(min, Math.min(s1, s)); } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
cb57b059c1b309ea9def46934782382f
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; /** * @author Tran Anh Tai * ProbE div 3 #642; */ public class KPeriodicGarland { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ int[] pref = new int[1000001]; int[] cnt = new int[1000001]; public void solve(InputReader in, PrintWriter out) { int test = Integer.parseInt(in.nextToken()); int i, j, total, mini; for (i = 0; i < test; i++) { int n = in.nextInt(); int k = in.nextInt(); mini = Integer.MAX_VALUE; total = 0; String p = in.nextToken(); Arrays.fill(cnt, 0, k, 0); // reset count array for (j = 0; j < n; j++){ cnt[j % k] += (p.charAt(j) - '0'); // count in the array how many lamp is already set with (each position mod k) total += (p.charAt(j) - '0'); // total set lamps at first; } for (j = 0; j < k; j++){ // for each position mod k == 0 to k - 1; pref[0] = 0; int cur = 1; int t = j; while (t < n){ pref[cur] = pref[cur - 1] + (p.charAt(t) - '0'); t += k; cur++; } int dp[] = new int[cur]; // dp[j] = minimum set steps to transform the array into GOOD array and the last set bit is at position j; for (t = 1; t < cur; t++){ dp[t] = Math.min(dp[t - 1], pref[t - 1] - pref[0]) + // the i - 1 bit is set| clear all before bit j; (p.charAt((t - 1) * k + j) == '1' ? 0 : 1); // if bit j is set -> no need additional swap; mini = Math.min(mini, dp[t] + (pref[cur - 1] - pref[t]) - cnt[j]); } } out.println(total + Math.min(mini, 0)); // consider the case when all lamps are off also; } } } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
58dec083d1d25815b970b82a5e2e35da
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
// Problem: E. K-periodic Garland // Contest: Codeforces - Codeforces Round #642 (Div. 3) // URL: http://codeforces.com/problemset/problem/1353/E // Memory Limit: 256 MB // Time Limit: 1000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) import java.io.*; import java.util.*; public class Main { private static PrintWriter pw = new PrintWriter(System.out); private static InputReader sc = new InputReader(); private static final int intmax = Integer.MAX_VALUE, intmin = Integer.MIN_VALUE; static class Pair{ int first, second; Pair(int first, int second){ this.first = first; this.second = second; } } static class InputReader{ private static BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tk; private void next()throws IOException{ if(tk == null || !tk.hasMoreTokens()) tk = new StringTokenizer(r.readLine()); } private int nextInt()throws IOException{ next(); return Integer.parseInt(tk.nextToken()); } private String readString()throws IOException{ next(); return tk.nextToken(); } } public static void main(String args[])throws IOException{ int t = sc.nextInt(); while(t-->0) solve(); pw.flush(); pw.close(); } private static int range(int arr[], int l, int r){ if(r < l) return 0; if(l == 0) return arr[r]; else return arr[r] - arr[l-1]; } private static int calculate(int arr[]){ int n = arr.length, pre[] = new int[n], dp[] = new int[n]; for(int i=0; i<n; i++) pre[i] = ((i>0)?pre[i-1]:0) + arr[i]; for(int i=0; i<n; i++){ if(arr[i] == 0) dp[i] = 1; int temp = range(pre, 0, i-1); if(i > 0) temp = Math.min(temp, dp[i-1]); dp[i] += temp; } int ans = range(pre, 0, n-1); for(int i=n-1; i>=0; i--) ans = Math.min(ans, range(pre, i+1, n-1) + dp[i]); return ans; } private static void solve()throws IOException{ int n = sc.nextInt(), k = sc.nextInt(); char s[] = sc.readString().toCharArray(); int arr[][] = new int[k][], cnt[] = new int[k], totalCnt = 0; for(int i=0; i<k; i++){ ArrayList<Integer> list = new ArrayList<>(); for(int j=i; j<n; j+=k){ list.add(s[j]-'0'); if(s[j] == '1') cnt[i]++; } arr[i] = list.stream().mapToInt(Integer::intValue).toArray(); totalCnt += cnt[i]; } int ans = intmax; for(int i=0; i<k; i++) ans = Math.min(ans, totalCnt-cnt[i]+calculate(arr[i])); pw.println(+ans); } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
5fd611deac4596e07e69e50ade95b0d7
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1353e_2 { static BufferedReader __in; static PrintWriter __out; static StringTokenizer input; public static void main(String[] args) throws IOException { __in = new BufferedReader(new InputStreamReader(System.in)); __out = new PrintWriter(new OutputStreamWriter(System.out)); int t = ri(); while(t --> 0) { int n = rni(), k = ni(), modcnt[] = new int[k], totcnt = 0, cnt[] = new int[n], dp[] = new int[n]; char[] s = rcha(); for(int i = 0; i < n; ++i) { if(s[i] == '1') { ++modcnt[i % k]; ++totcnt; } if(i < k) { dp[i] = 1 - (cnt[i] = s[i] == '1' ? 1 : 0); } else { cnt[i] = cnt[i - k] + (s[i] == '1' ? 1 : 0); dp[i] = min(cnt[i - k], dp[i - k] + (s[i] == '1' ? 0 : 1)); } } int ans = totcnt; for(int i = 0; i < n; ++i) { int last = n / k * k + i % k; if(last >= n) { last -= k; } ans = min(ans, totcnt - modcnt[i % k] + dp[i] + cnt[last] - cnt[i]); } prln(ans); } close(); } // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); __out.println(iter.next());} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
959eccf63451dae1861bf81b7f6f5393
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Scanner; public class code11 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while(t-->0) { int n = scn.nextInt(); int k =scn.nextInt(); String str = scn.next(); int[] dp = new int[n]; Arrays.fill(dp, Integer.MAX_VALUE); //vector<int> dp(n, inf); int[] count = new int[n]; count[0] = str.charAt(0) - '0'; for(int i=1; i<n; i++) { count[i] = count[i - 1]; count[i] += (str.charAt(i) - '0'); } for (int i = n - 1; i >= 0; i--) { if (i + k < n) { dp[i] = 0; dp[i] = dp[i + k]; dp[i] += (count[i + k - 1] - count[i]); } dp[i] = Math.min(dp[i], count[n - 1] - count[i]); dp[i] += (1 - (str.charAt(i) - '0')); } int ans = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int temp = dp[i]; if (i != 0) { temp += count[i - 1]; } ans = Math.min(ans, temp); } ans = Math.min(ans, count[n - 1]); System.out.println(ans); } } public static class Pair implements Comparable<Pair>{ int a; int b; Pair(int x, int y){ a= x; b= y; } public int compareTo(Pair p) { if(this.b-this.a == p.b-p.a) return p.a - this.a; return (this.b-this.a) - (p.b - p.a); } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
79a59f06b3351bdcef8e4c39b5b7f8f0
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class d { static BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); // static Scanner s=new Scanner(System.in); public static void main(String[] args) throws IOException { StringBuilder sb = new StringBuilder(); String[] s1=s(); int t=i(s1[0]); while(t-->0){ String[] s2=s(); int n=i(s2[0]); int k=i(s2[1]); // int[] a=new int[n]; char[] a=s()[0].toCharArray(); int tone=0; for(int i=0;i<n;i++) { if(a[i]=='1') tone++; } int[] onefor=new int[n]; for(int i=0;i<k;i++){ for(int j=i;j<n;j+=k){ if(a[j]=='1') onefor[i]++; } } int one=0;long min=Integer.MAX_VALUE; for(int i=0;i<k;i++){ int flag=0;int count=0;long ans=0;one=0; for(int j=i;j<n;j+=k){ if(a[j]=='1'){ one++; if(flag==0){ flag=1;continue; }else{ ans=Math.min(one-1,ans+count);count=0; min=Math.min(min,ans+onefor[i]-one+tone-(onefor[i])); } }else{ if(flag==1){ count++; } } } min=Math.min(min,Math.min(tone-one+ans,tone)); } System.out.println(min); } } static int MAXN; static int[] spf; static void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) spf[i] = i; for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { if (spf[i] == i) { for (int j=i*i; j<MAXN; j+=i) if (spf[j]==j) spf[j] = i; } } } static String[] s() throws IOException { return s.readLine().trim().split("\\s+"); } static int i(String ss) { return Integer.parseInt(ss); } static long l(String ss) { return Long.parseLong(ss); } } class Student12 { int l;int r; public Student12(int l, int r) { this.l = l; this.r = r; } public String toString() { return this.l+" "; } } class Sortbyroll12 implements Comparator<Student12> { public int compare(Student12 a, Student12 b){ /* if(b.r<a.r) return -1; else if(b.r==a.r) return 0; return 1;*/ if(b.r-b.l>a.r-a.l) return 1; else if(b.r-b.l==a.r-a.l) { return a.l-b.l; }else return -1;/* if(b.l<a.l) return -1; else if(b.l==a.l) { return b.r-a.r; } return 1;*/ // return b.r- a.r; // return (int) a.l-(int) b.l; /* if(a.r<b.r) return -1; else if(a.r==b.r){ if(a.r==b.r){ return 0; } if(a.r<b.r) return -1; return 1;} return 1; */} }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
2dc58915afcabf66a0a77d0bc66e94eb
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static PrintWriter out = new PrintWriter(System.out); static Reader in = new Reader(); public static void main(String[] args) throws IOException { Main solver = new Main(); solver.solve(); out.flush(); out.close(); } static int INF = (int)1e9; static int maxn = (int)1e5+5; static int mod = 998244353; static int n,m,q,k,t; void solve() throws IOException{ t = in.nextInt(); while (t --> 0) { n = in.nextInt(); k = in.nextInt(); String s = in.next(); int[] arr = new int[n]; int[] pre = new int[n]; for (int i = 0; i < n; i++) { arr[i] = s.charAt(i)-'0'; pre[i] = arr[i]; if (i != 0) pre[i] += pre[i-1]; } int ans = pre[n-1], best = 0, cur = 0; for (int i = 0; i < n; i++) if (arr[i] == 0) arr[i] = -1; for (int i = 0; i < k; i++) { cur = 0; for (int j = i; j < n; j+=k) { cur += arr[j]; cur = Math.max(cur, 0); best = Math.max(best, cur); } } out.println(ans - best); } } //<> static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
3601600cf8ff73f87836cd8f9ae2fa4c
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Main { final int inf=(int)(1e9+1); private void solve()throws IOException { int n=nextInt(); int k=nextInt(); String s=nextLine(); int a[]=new int[n+1]; for(int i=1;i<=n;i++) a[i]=s.charAt(i-1)-'0'; int cum[]=new int[n+1]; for(int i=1;i<=n;i++) cum[i]=cum[i-1]+a[i]; //dp[i] is the min no of moves such that there is a garland at i and i..n is k-periodic int dp[]=new int[n+1]; for(int i=n;i>=1;i--) dp[i]=1-a[i]+Math.min(cum[n]-cum[i],i+k<=n?cum[i+k-1]-cum[i]+dp[i+k]:inf); int ans=cum[n]; for(int i=1;i<=n;i++) ans=Math.min(ans,cum[i-1]+dp[i]); out.println(ans); } /////////////////////////////////////////////////////////// public void run()throws IOException { br=new BufferedReader(new InputStreamReader(System.in)); st=null; out=new PrintWriter(System.out); int t=nextInt(); while(t-->0) solve(); br.close(); out.close(); } public static void main(String args[])throws IOException{ new Main().run(); } BufferedReader br; StringTokenizer st; PrintWriter out; String nextToken()throws IOException{ while(st==null || !st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine()throws IOException{ return br.readLine(); } 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
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
beee3f4d1ec8258bb290e308a0db81b7
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.InputMismatchException; import java.util.function.Function; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { long startTime = System.currentTimeMillis(); InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); Output out = new Output(outputStream); EKPeriodicGarland solver = new EKPeriodicGarland(); int testCount = in.nextInt(); for(int i = 1; i<=testCount; i++) solver.solve(i, in, out); out.close(); System.err.println(System.currentTimeMillis()-startTime+"ms"); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28); thread.start(); thread.join(); } static class EKPeriodicGarland { private final int iinf = 1_000_000_000; public EKPeriodicGarland() { } public void solve(int kase, InputReader in, Output pw) { int n = in.nextInt(), k = in.nextInt(); int[] arr = in.nextIntChar(o -> o-'0'); int[][] psum = new int[n+1][2]; for(int i = 0; i<n; i++) { int x = arr[i]; psum[i+1][x] = psum[i][x]+1; psum[i+1][x^1] = psum[i][x^1]; } int[] dp = new int[n]; for(int i = n-1; i>=0; i--) { if(i+k>=n) { dp[i] = (arr[i]^1)+psum[n][1]-psum[i+1][1]; }else { dp[i] = (arr[i]^1)+psum[i+k][1]-psum[i+1][1]+dp[i+k]; } dp[i] = Math.min(dp[i], psum[n][1]-psum[i+1][1]); } //// Utilities.Debug.dbg(dp); int ans = iinf; for(int i = 0; i<n; i++) { ans = Math.min(ans, psum[i][1]+dp[i]); } pw.println(ans); } } static class FastReader implements InputReader { final private int BUFFER_SIZE = 1<<16; private DataInputStream din; private byte[] buffer; private int bufferPointer; private int bytesRead; public FastReader(InputStream is) { din = new DataInputStream(is); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String next() { StringBuilder ret = new StringBuilder(64); byte c = skip(); while(c!=-1&&!isSpaceChar(c)) { ret.appendCodePoint(c); c = read(); } return ret.toString(); } public int nextInt() { int ret = 0; byte c = skipToDigit(); 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; } private boolean isSpaceChar(byte b) { return b==' '||b=='\r'||b=='\n'||b=='\t'||b=='\f'; } private byte skip() { byte ret; while(isSpaceChar((ret = read()))) ; return ret; } private boolean isDigit(byte b) { return b>='0'&&b<='9'; } private byte skipToDigit() { byte ret; while(!isDigit(ret = read())&&ret!='-') ; return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); }catch(IOException e) { e.printStackTrace(); throw new InputMismatchException(); } if(bytesRead==-1) { buffer[0] = -1; } } private byte read() { if(bytesRead==-1) { throw new InputMismatchException(); }else if(bufferPointer==bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public String lineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); lineSeparator = System.lineSeparator(); } public void println(int i) { println(String.valueOf(i)); } public void println(String s) { sb.append(s); println(); } public void println() { sb.append(lineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static interface InputReader { String next(); int nextInt(); default int[] nextIntChar(Function<Character, Integer> f) { String s = next(); int[] ret = new int[s.length()]; for(int i = 0; i<s.length(); i++) { ret[i] = f.apply(s.charAt(i)); } return ret; } } static class Utilities { public static class Debug { public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null; private static <T> String ts(T t) { if(t==null) { return "null"; } try { return ts((Iterable) t); }catch(ClassCastException e) { if(t instanceof int[]) { String s = Arrays.toString((int[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof long[]) { String s = Arrays.toString((long[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof char[]) { String s = Arrays.toString((char[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof double[]) { String s = Arrays.toString((double[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof boolean[]) { String s = Arrays.toString((boolean[]) t); return "{"+s.substring(1, s.length()-1)+"}"; } try { return ts((Object[]) t); }catch(ClassCastException e1) { return t.toString(); } } } private static <T> String ts(T[] arr) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: arr) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } private static <T> String ts(Iterable<T> iter) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: iter) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } public static void dbg(Object... o) { if(LOCAL) { System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": ["); for(int i = 0; i<o.length; i++) { if(i!=0) { System.err.print(", "); } System.err.print(ts(o[i])); } System.err.println("]"); } } } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
e627a976f9507a0abbe7a89e2c4526f1
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.math.*; //Mann Shah [ DAIICT ]. //fast io public class Main { static long mod = (long) (1e9+7); static long mm = (long)(1e9+6); static long N = (long)(2*1e5); static InputReader in; static PrintWriter out; static Debugger deb; public static int lower_bound(long[] a,int k) { // no. of elements less than k in array. int first = 0,last = a.length,mid; while (first < last) { mid = first + ((last - first) >> 1); if (a[mid] < k) //lower bound. for upper use <= ( n - first) first = mid + 1; else last = mid; } return first; } public static long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a); } public static long power(long x, long y, long p) { long res = 1; x = x % p; if (x == 0) return 0; while (y > 0) { if((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static void main(String args[] ) throws NumberFormatException, IOException { in = new InputReader(System.in); out = new PrintWriter(System.out); deb = new Debugger(); int T = in.nextInt(); while(T-->0) { int n = in.nextInt(); int k = in.nextInt(); char[] s = in.readString().toCharArray(); int[] pre = new int[n]; pre[0] = s[0]-'0'; for(int i=1;i<n;i++) { pre[i] = pre[i-1]+(s[i]-'0'); } int[] dp = new int[n]; for(int i=n-1;i>=0;i--) { int c =0; if(s[i]=='0') { c+=1; } c+=pre[i+k-1<n ? i+k-1 : n-1]-pre[i]; //taking prev 1 to 0 if(i+k<n) { c+=dp[i+k]; } //making all 0 int cv = pre[n-1]-pre[i]+s[i]-'0'; dp[i] = Math.min(cv, c); } int min = dp[0]; for(int i=1;i<n;i++) { min = Math.min(min, dp[i]+pre[i-1]); } out.println(min); } out.close(); } /* TC space */ static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public ArrayList<Integer> nextArrayList(int n){ ArrayList<Integer> x = new ArrayList<Integer>(); for(int i=0;i<n;i++) { int v = in.nextInt(); x.add(v); } return x; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class Debugger{ public void n(int x) { out.println(x); } public void a(int[] a) { StringBuilder sb = new StringBuilder(); for(int i=0;i<a.length;i++) { sb.append(a[i]+" "); } out.println(sb.toString()); } } } class Pair { int x; int y; // Constructor public Pair(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair p = (Pair) o; return x == p.x && y == p.y; } @Override public int hashCode() { return (""+x+"-"+y).hashCode(); } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
5b552a26a2c901e40090d3799414a97c
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
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.FilterInputStream; import java.io.BufferedInputStream; 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; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); EKPeriodicGarland solver = new EKPeriodicGarland(); solver.solve(1, in, out); out.close(); } static class EKPeriodicGarland { int[] hash; int sum; public void solve(int testNumber, ScanReader in, PrintWriter out) { int t = in.scanInt(); while (t-- > 0) { int n = in.scanInt(); int k = in.scanInt(); int arr[] = new int[n]; hash = new int[k]; sum = 0; for (int i = 0; i < n; i++) arr[i] = in.scanChar() - '0'; for (int i = 0; i < n; i++) sum += arr[i]; for (int i = 0; i < n; i++) if (arr[i] == 1) hash[i % k]++; int ans = sum; for (int mod = 0; mod < k; mod++) { StringBuilder sb = new StringBuilder(); sb.append('#'); for (int i = mod; i < n; i += k) sb.append(arr[i]); ans = Math.min(ans, sum - hash[mod] + makeZOZ(sb.toString().toCharArray())); } out.println(ans); } } int makeZOZ(char[] arr) { int n = arr.length - 1; int dp[] = new int[n + 1]; int pre[] = new int[n + 1]; int suff[] = new int[n + 5]; Arrays.fill(dp, Integer.MAX_VALUE); for (int i = 1; i <= n; i++) pre[i] = pre[i - 1] + (arr[i] - '0'); for (int i = n; i >= 1; i--) suff[i] = suff[i + 1] + (arr[i] - '0'); dp[0] = 0; for (int i = 1; i <= n; i++) { dp[i] = Math.min(dp[i - 1] + (arr[i] == '0' ? 1 : 0), dp[i]); dp[i] = Math.min(dp[i], pre[i - 1] + (arr[i] == '0' ? 1 : 0)); } int ans = Integer.MAX_VALUE / 2; ans = pre[n]; for (int i = 1; i <= n; i++) { ans = Math.min(ans, dp[i] + suff[i + 1]); } return ans; } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int INDEX; private BufferedInputStream in; private int TOTAL; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (INDEX >= TOTAL) { INDEX = 0; try { TOTAL = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (TOTAL <= 0) return -1; } return buf[INDEX++]; } public char scanChar() { int c = scan(); while (isWhiteSpace(c)) c = scan(); return (char) c; } public int scanInt() { int I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
2d507bb117f01a0876395967ae4e80a6
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class E642 { public static void main(String [] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); while (t > 0) { int n = sc.nextInt(); int k = sc.nextInt(); String s = sc.next(); int [] a = new int [n]; for (int i = 0; i < n; i++) a[i] = (s.charAt(i) == '0' ? 0 : 1); int [] pref = new int [n+1]; for (int i = 0; i < n; i++) { pref[i+1] = a[i] + pref[i]; } int [] dp = new int [n]; Arrays.fill(dp, Integer.MAX_VALUE); if (a[0] == 1) dp[0] = 0; else dp[0] = 1; for (int i = 1; i < n; i++) { int thisNum = -1; if (a[i] == 0) thisNum = 1; else thisNum = 0; int before = pref[i]; dp[i] = Math.min(dp[i], before + thisNum); if (i >= k) { int toChange = pref[i] - pref[i - k + 1]; dp[i] = Math.min(dp[i], toChange + thisNum + dp[i - k]); } } int [] res = new int [n]; int ans = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { res[i] = dp[i] + (pref[n] - pref[i + 1]); ans = Math.min(ans, res[i]); } ans = Math.min(ans, pref[n]); out.println(ans); t--; } out.close(); } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
67ef0800d49d76c42c7eace8d3aa767b
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Abc { static int dp[]; static int ii,tot,i1; static ArrayList<Integer> adj[]; static int pre[],suf[]; public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); int t=sc.nextInt(); StringBuilder sb=new StringBuilder(); while (t-->0){ ii=0; tot=0; i1=0; int n=sc.nextInt();int k=sc.nextInt(); String s=sc.next(); adj=new ArrayList[k]; for (int i=0;i<k;i++)adj[i]=new ArrayList<>(); for (int i=0;i<k;i++){ for (int j=i;j<n;j+=k){ adj[i].add(s.charAt(j)-'0'); tot+=s.charAt(j)-'0'; } } int ans=n; for (;ii<k;ii++){ int sz=adj[ii].size(); dp=new int[sz+1]; Arrays.fill(dp,0); pre=new int[sz]; for (int i=0;i<sz;i++){ pre[i]=adj[ii].get(i); if (i>0)pre[i]+=pre[i-1]; } suf=new int[sz]; for (int i=sz-1;i>=0;i--){ suf[i]=adj[ii].get(i); if (i+1<=sz-1)suf[i]+=suf[i+1]; } dp[sz]=tot-pre[sz-1]; for (i1=sz-1;i1>=0;i1--) { // if (i1 == 0) { // ans = Math.min(ans, dp( i1)); // } else { // ans = Math.min(ans, dp( i1) + pre[i1 - 1]); // } int x=suf[i1]+tot-suf[0],y=dp[i1+1]; if (adj[ii].get(i1)==1){ dp[i1]=Math.min(x+1,y); }else { dp[i1]=Math.min(x,y+1); } if (i1==0) { ans = Math.min(ans, dp[i1]); }else ans=Math.min(ans,dp[i1]+pre[i1-1]); } } // System.out.println(ans); sb.append(ans+"\n"); } System.out.print(sb); } // static int dp(int i){ // if (i==adj[ii].size())return tot-pre[i-1]; // if (dp[i]!=-1)return dp[i]; // int x=suf[i]+(tot-suf[0]),y=dp(i+1); // if (adj[ii].get(i)==1){ // dp[i]=Math.min(x+1,y); // }else { // dp[i]=Math.min(x,1+y); // } // return dp[i]; // } 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
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
e5fee14b91459aebfaab2c7a10cc6609
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Q3 { public static void main(String[] args) { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); while(t-->0){ int n =in.nextInt(),k=in.nextInt(),tot=0; char arr[]=in.next().toCharArray(); for(int i=0;i<n;i++) tot+=arr[i]=='1'?1:0; long ans=tot; for(int i=n-1;i>=0 && i>=n-k;i--){ ArrayList<Integer> hut=new ArrayList<>(); for(int j=i;j>=0;j-=k) hut.add(arr[j]=='0'?0:1); int o=0; for(int j=0;j<hut.size();j++){ o+=hut.get(j)==1?1:-1; if(o<0) o=0; ans=Math.min(ans,tot-o); } } out.println(ans); } out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static int[][] packU(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) p[f]++; for (int t : to) p[t]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } public int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
066045f46287716419d22a7a98e280cf
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Q3 { public static void main(String[] args) { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); while(t-->0){ int n =in.nextInt(),k=in.nextInt(),tot=0; char arr[]=in.next().toCharArray(); for(int i=0;i<n;i++) tot+=arr[i]=='1'?1:0; int ans=tot; for(int i=n-1;i>=0 && i>=n-k;i--){ int o=0; for(int j=i;j>=0;j-=k){ o+=arr[j]=='1'?1:-1; if(o<0) o=0; ans=Math.min(ans,tot-o); } } out.println(ans); } out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static int[][] packU(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) p[f]++; for (int t : to) p[t]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } public int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
75b8a78fce1cc6b50a541831c3533985
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); StringBuilder sb=new StringBuilder(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int k=sc.nextInt(); ArrayList<Integer> a[]=new ArrayList[k]; for( int i=0;i<k;i++) { a[i]=new ArrayList<>(); } char s[]=(sc.next()).toCharArray(); long sum=0; for( int i=0;i<n;i++) { if(s[i]=='1') sum+=1; int g=i%k; if(s[i]=='1') a[g].add(1); else a[g].add(-1); } long max=0; for( int i=0;i<k;i++) { long ans=0; for( int p=0;p<a[i].size();p++) { ans+=a[i].get(p); max=Math.max(max,ans); ans=Math.max(ans,0); } } sb.append(sum-max); sb.append("\n"); // sb.append(ans+"\n"); } System.out.print(sb.toString()); } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
74e53143f4b6aca9984c3cb6ebaaecf6
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
//package round642; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class E { InputStream is; PrintWriter out; String INPUT = ""; void solve() { for(int T = ni();T > 0;T--)go(); } void go() { int n = ni(), K = ni(); char[] s = ns(n); int[] ones = new int[n+1]; for(int i = 0;i < n;i++){ ones[i+1] = ones[i] + s[i]-'0'; } int[] dp = new int[n]; for(int i = 0;i < n;i++){ dp[i] = (s[i] == '0' ? 1 : 0) + ones[i]; if(i-K >= 0)dp[i] = Math.min(dp[i], dp[i-K] + (s[i] == '0' ? 1 : 0) + ones[i] - ones[i-K+1]); } int ans = ones[n]; for(int i = 0;i < n;i++){ ans = Math.min(ans, dp[i] + ones[n] - ones[i+1]); } out.println(ans); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new E().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private 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
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
e410fd1b460a7b888716c6da9fc00048
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class Main{ static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } static 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.nextInt(); return array; } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int mod = (int)(1e9+7); public static long pow(long a,long b) { long ans = 1; while(b> 0) { if((b & 1)==1){ ans = (ans*a) % mod; } a = (a*a) % mod; b = b>>1; } return ans; } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); //IOUtils io = new IOUtils(); int t = in.nextInt(); while(t-- >0) { int n = in.nextInt(),k=in.nextInt(); String s = in.nextLine(); int[] arr = new int[n]; int tot = 0; for(int i=0;i<n;i++) { arr[i] = s.charAt(i)=='1'?1:0; tot+=arr[i]; } int res = tot; for(int i=0;i<k;i++) { int dif=0; for(int j=i;j<n;j+=k) { if(arr[j]==1){ ++dif; } else{ --dif; } dif = Math.max(dif,0); res = Math.min(res,tot-dif); } } out.printLine(res); } out.flush(); out.close(); } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
70f8c2c9941dfada16b03ee56a33a436
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args)throws IOException { try{ //BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); Scanner sc = new Scanner(System.in); // int t=Integer.parseInt(br.readLine()); int t=sc.nextInt(); // int t=1; while(t-->0){ //int n=Integer.parseInt(br.readLine()) int n = sc.nextInt(); int k = sc.nextInt(); String s=sc.next(); //long d=Long.parseLong(br.readLine()); //String[] s= br.readLine().trim().split(" "); // Map<Integer,Integer> m = new TreeMap<Integer,Integer>(); //List<Character> f = new ArrayList<Character>(); //List<Integer> s = new ArrayList<Integer>(); //<Integer> v= new Vector<Integer>(); //Set<Integer> s= new HashSet<Integer>(); // char c[] = s.toCharArray(); int ps[] = new int[n]; Arrays.fill(ps,0); ps[0]=s.charAt(0)-'0'; for(int i=1;i<n;i++){ ps[i]=ps[i-1]+(s.charAt(i)-'0'); } int dp[] = new int[n]; Arrays.fill(dp,0); for(int i=n-1;i>=0;i--){ int ci1 = (s.charAt(i)-'0')^1; if(i+k<=n-1) ci1+=ps[i+k-1]-ps[i]; else ci1+=ps[n-1]-ps[i]; if(i+k<=n-1) ci1+=dp[i+k]; int ci0 = (s.charAt(i)-'0')+ps[n-1]-ps[i]; dp[i] = Math.min(ci1,ci0); } int ans= dp[0]; for(int i=1;i<n;i++){ dp[i]+=ps[i-1]; ans=Math.min(ans,dp[i]); } System.out.println(ans); } } catch(Exception e){ } }}
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
3c6140058e43bebb5d50358418db8b39
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Task { public static void main(String[] args) throws Exception { new Task().go(); } PrintWriter out; Reader in; BufferedReader br; Task() throws IOException { try { //br = new BufferedReader( new FileReader("input.txt") ); //in = new Reader("input.txt"); in = new Reader("input.txt"); out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); } catch (Exception e) { //br = new BufferedReader( new InputStreamReader( System.in ) ); in = new Reader(); out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); } } void go() throws Exception { int t = in.nextInt(); //int t = 1; while (t > 0) { solve(); t--; } out.flush(); out.close(); } int inf = 2000000000; int mod = 1000000007; double eps = 0.000000001; int n; int m; ArrayList<Integer>[] g; void solve() throws IOException { int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; int[] cnt = new int[k + 1]; String s = in.next(); int sum = 0; for (int i = 0; i < n; i++) { a[i] = s.charAt(i) - '0'; if (a[i] == 1) { cnt[i % k]++; sum++; } } int min = sum; for (int i = 0; i < k; i++) { int cur = 0; int allSum = sum; int c = 0; for (int j = i; j < n; j += k) { c++; if (a[j] == 0) { cur++; } else { allSum--; } if (c - cur < cur) { allSum += c - cur; cur = 0; c = 0; } min = Math.min(min, cur + allSum); } } out.println(min); } static class Segment implements Comparable<Segment> { public final int a; public final int b; public final int i; Segment(int a, int b, int i) { this.a = a; this.b = b; this.i = i; } public int len() { return b - a + 1; } public int compareTo(Segment p) { if (len() == p.len()) return Integer.compare(i, p.i); else return Integer.compare(p.len(), len()); } } static class Pair<A extends Comparable<A>, B extends Comparable<B>> implements Comparable<Pair<A, B>> { public final A a; public final B b; Pair(A a, B b) { this.a = a; this.b = b; } public int compareTo(Pair<A, B> p) { if (!a.equals(p.a)) return a.compareTo(p.a); else return b.compareTo(p.b); } } class Item { int a; int b; int c; Item(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } } static class InputReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public InputReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public InputReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
3f0c7a3d61a74dd3eaa55f26a0874c29
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
/* Author: Anthony Ngene Created: 07/08/2020 - 07:49 */ import java.io.*; import java.util.*; public class E { // Light travels faster than sound. This is why some people appear bright until you hear them speak. - Alan Dundes public static void main(String[] args) throws IOException { in = new FastScanner(); int cases = in.intNext(); for (int t = 1; t <= cases; t++) { int n = in.intNext(), k = in.intNext(); String seq = in.next(); int[] prefix = new int[n + 1]; for (int i = 0; i < n; i++) { int num = seq.charAt(i) == '1' ? 1 : 0; prefix[i + 1] = prefix[i] + num; } int[] onArr = new int[n + 1]; int[] offArr = new int[n + 1]; for (int i = 1; i < n + 1; i++) { if (seq.charAt(i - 1) == '1') { // turn off int off = min(onArr[i - 1], offArr[i - 1]) + 1; offArr[i] = off; // leave on (set last k to 0) int idx = max(i - k, 0); int on = prefix[i - 1] - prefix[idx] + onArr[idx]; on = min(on, prefix[i - 1] - prefix[0]); onArr[i] = on; } else { // keep off int off = min(onArr[i - 1], offArr[i - 1]); offArr[i] = off; // turn on (set last k to 0) int idx = max(i - k, 0); int on = prefix[i - 1] - prefix[idx] + onArr[idx] + 1; on = min(on, prefix[i - 1] - prefix[0]); onArr[i] = on; } } // u.print(onArr); // u.print(offArr); out.println(min(onArr[n], offArr[n])); } out.close(); } private static final FastWriter out = new FastWriter(); private static FastScanner in; static ArrayList<Integer>[] adj; private static long e97 = (long)1e9 + 7; static class FastWriter { private static final int IO_BUFFERS = 128 * 1024; private final StringBuilder out; public FastWriter() { out = new StringBuilder(IO_BUFFERS); } public FastWriter p(Object object) { out.append(object); return this; } public FastWriter p(String format, Object... args) { out.append(String.format(format, args)); return this; } public FastWriter pp(Object... args) { for (Object ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; } public FastWriter println(Object object) { out.append(object).append("\n"); return this; } public void toFile(String fileName) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(out.toString()); writer.close(); } public void close() throws IOException { System.out.print(out); } } static class FastScanner { private InputStream sin = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; public FastScanner(){} public FastScanner(String filename) throws FileNotFoundException { File file = new File(filename); sin = new FileInputStream(file); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = sin.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long longNext() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b) || b == ':'){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int intNext() { long nl = longNext(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double doubleNext() { return Double.parseDouble(next());} public long[] nextLongArray(final int n){ final long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = longNext(); return a; } public int[] nextIntArray(final int n){ final int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = intNext(); return a; } public ArrayList<Integer>[] getAdj(int n) { ArrayList<Integer>[] adj = new ArrayList[n + 1]; for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>(); return adj; } public ArrayList<Integer>[] adjacencyList(int n, int m) throws IOException { adj = getAdj(n); for (int i = 0; i < m; i++) { int a = intNext(), b = intNext(); adj[a].add(b); adj[b].add(a); } return adj; } } private static int min(int a, int b){ return (a>b) ? b : a; } private static int max(int a, int b){ return (a>b) ? a : b; } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
00d0b360e07b8c6fd2fbdf9c24380150
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { static class node{ int a, b; public node(int x, int y) { a = x; b = y; } } static class Pair implements Comparable<Pair>{ int a; int b; // int ind; // public Pair(int x, long y) {a = x;b=y;} public Pair(int x, int y) {a = x;b=y;} // public Pair(int x,int y, int z){a=x;b=y;ind = z;} public int compareTo(Pair p){ if(a == p.a) return b - p.b; else return a - p.a; } // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + a; // result = prime * result + b; // // return result; // } // @Override // public boolean equals(Object obj) { // Pair cur = (Pair)obj; // if((a==cur.a && b==cur.b))return true; // return false; // } } public static void main(String[] args) throws Exception { new Thread(null, null, "Anshum Gupta", 99999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } public static long gcd(long a,long b) { if(a<b) return gcd(b,a); if(b==0) return a; return gcd(b,a%b); } static long lcm(int a,int b) { return a*b / gcd(a,b); } static long pow(long x,long y){ if(y == 0)return 1; if(y==1)return x; long a = pow(x,y/2); a = (a*a)%mod; if(y%2==0){ return a; } return (a*x)%mod; } static long[]fact,inv_fact; static long my_inv(long a) { return pow(a,mod-2); } static long bin(int a,int b) { if(a < b || a<0 || b<0)return 0; return ((fact[a]*inv_fact[a-b])%mod * inv_fact[b])%mod; } static void make_facts() { fact=new long[mxN]; inv_fact = new long[mxN]; fact[0]=inv_fact[0]=1L; for(int i=1;i<mxN;i++) { fact[i] = (i*fact[i-1])%mod; inv_fact[i] = my_inv(fact[i]); } } static void lazy(int st, int e, int tn) { if(lazy[tn] != INF) { tree[tn] = Math.min(tree[tn], lazy[tn]); if(st != e) { lazy[2*tn] = Math.min(lazy[2*tn], lazy[tn]); lazy[2*tn+1] = Math.min(lazy[2*tn+1], lazy[tn]); } lazy[tn] = INF; } } static void update(int ind, int val, int st, int e, int tn) { if(st == e) { tree[tn] = val; return; } int mid = (st + e) >> 1; if(ind <= mid) update(ind, val, st, mid, 2*tn); else update(ind, val, mid+1, e, 2*tn+1); tree[tn] = Math.min(tree[2*tn], tree[2*tn+1]); } static int query(int l, int r, int st, int e, int tn) { if(st > r || e < l)return INF; if(st >= l && e <= r) { return tree[tn]; } int mid = (st + e) >> 1; int x = query(l, r, st, mid, 2 * tn); int y = query(l, r, mid+1, e, 2 * tn + 1); return Math.min(x, y); } static final long mxx = (long)(3e18+5); static final int mxN = (int)(1e5); static final int mxV = (int)(1e5+5); static long mod = (long)(1e9+7); //998244353;// static int[]tree, lazy; static final int INF = (int)1e9+5; static boolean[]vis; static ArrayList<ArrayList<Integer>> adj; static int n, m, q, t, k, p; static int[]a, fc; static char[]arr; static int rec(int i) { if(i == n-1) { return (arr[i] == '1' ? 1 : 0); } int res = 0; res = fc[i+k] - fc[i]; return res; } public static void solve() throws Exception { // solve the problem here MyScanner s = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out), true); int tc = s.nextInt(); while(tc-->0){ n = s.nextInt(); k = s.nextInt(); arr = s.next().toCharArray(); int[]dp1 = new int[n], dp2 = new int[n]; // dp[i] -> min moves required to turn string 0..i k periodic with ith bit = 1 fc = new int[n]; for(int i=0; i<n; i++) { if(i > 0)fc[i] += fc[i-1]; fc[i] += (arr[i] == '1' ? 1 : 0); } int ans = fc[n-1]; for(int i=0; i<n; i++) { dp1[i] = ((arr[i] - '0') ^ 1) + (i > 0 ? fc[i-1] : 0); if (i >= k){ dp1[i] = Math.min(dp1[i], ((arr[i] - '0') ^ 1) + (fc[i-1] > 0 ? dp1[i-k] + (fc[i-1] - fc[i-k]) : 0)); } } // for(int i=n-1; i>=0; i--) { // if(i + k > n - 1) { // dp2[i] = ((arr[i] - '0') ^ 1) + (fc[n-1] - fc[i]); // } // else { // dp2[i] = ((arr[i] - '0') ^ 1) + (fc[n-1] - fc[i] > 0 ? dp2[i+k] + (fc[i+k-1] - fc[i]) : 0); // } // } // for(int i=0; i<n; i++) { // out.print(dp1[i] + " "); // }out.println(); // for(int i=0; i<n; i++) { // out.print(dp2[i] + " "); // }out.println(); for(int i=0; i<n; i++) { ans = Math.min(ans, dp1[i] + fc[n-1] - fc[i]); } out.println(ans); } out.flush(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
6f809319b9950c753a96ffadedc1d11d
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Garland { public static void main(String[] args) throws IOException { new Garland().solve(); } public void solve() throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(f.readLine()); PrintWriter out = new PrintWriter(System.out); for (int t1 = 0; t1 < t; t1++) { StringTokenizer tokenizer = new StringTokenizer(f.readLine()); int n = Integer.parseInt(tokenizer.nextToken()); int k = Integer.parseInt(tokenizer.nextToken()); char[] seq = f.readLine().toCharArray(); int all = 0; for (int i = 0; i < n; i++) { if (seq[i] == '1') { all++; } } int[] dp = new int[n]; int min = Integer.MAX_VALUE; for (int i = 0; i < k; i++) { int soFar = 0; for (int j = i; j < n; j += k) { if (j - k >= 0) { dp[j] = Math.min(dp[j - k], soFar); } if (seq[j] == '1') { soFar++; } else { dp[j]++; } min = Math.min(min, dp[j] - soFar + all); } } min = Math.min(min, all); out.println(min); } out.close(); } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
810e90d916b192fe2bfb0b89a769c945
train_002.jsonl
1589466900
You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.
256 megabytes
// package com.company.codeforces; import java.util.Arrays; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner input=new Scanner(System.in); int t=input.nextInt(); while (t-->0){ int n=input.nextInt(); int k=input.nextInt(); String s=input.next(); int sum=0; int pre[]=new int[n]; for (int i = 0; i <n ; i++) { sum=sum+(s.charAt(i)-'0'); pre[i]=sum; } // 1 0 0 1 0 1 int dp[]=new int[n]; for (int i = n-1; i >=0 ; i--) { int val=(s.charAt(i)-'0')^1; //putting 1 and checking i+k which is correct and coverting between 1 to 0; if (i+k<n){ val=val+pre[i+k-1]-pre[i]; dp[i]=val+dp[i+k]; }else { val=val+pre[n-1]-pre[i]; dp[i]=val; } dp[i]=Math.min(dp[i],pre[n-1]-pre[i]+(s.charAt(i)-'0')); } int min=dp[0]; // System.out.println(Arrays.toString(dp)); for (int i = 1; i <n ; i++) { min=Math.min(min,pre[i-1]+dp[i]); } System.out.println(min); } } }
Java
["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"]
1 second
["1\n2\n5\n4\n0\n0"]
null
Java 11
standard input
[ "dp", "greedy", "brute force" ]
8b28309055f13837eb1f51422fb91029
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) β€” the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).
1,900
For each test case, print the answer β€” the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.
standard output
PASSED
d92ec94ec0d8a78e57bdc78b6da2410b
train_002.jsonl
1326380700
Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse.He's got problems with some particularly large piece of equipment, which is, of course, turboplows. The problem is that when a turboplow is stored, it takes up not some simply rectangular space. It takes up a T-shaped space like on one of the four pictures below (here character "#" stands for the space occupied by the turboplow and character "." stands for the free space): ### ..# .#. #...#. ### .#. ###.#. ..# ### #.. Simon faced a quite natural challenge: placing in the given n × m cells warehouse the maximum number of turboplows. As one stores the turboplows, he can rotate them in any manner (so that they take up the space like on one of the four pictures above). However, two turboplows cannot "overlap", that is, they cannot share the same cell in the warehouse.Simon feels that he alone cannot find the optimal way of positioning the plugs in the warehouse that would maximize their quantity. Can you help him?
256 megabytes
import java.util.Scanner; public class E { private static int res; private static int n, m; private static int [][] ret; public static void main(String [] args) { Scanner in = new Scanner(System.in); n = in.nextInt(); m = in.nextInt(); ret = new int[n][m]; res = 0; rec(new int[n][m], 0); System.out.println(res); for(int i = 0 ; i < n ; i++) { for(int j = 0 ; j < m ; j++) if(ret[i][j] == 0) System.out.print('.'); else System.out.print((char)(ret[i][j]+'A'-1)); System.out.println(); } } public static void rec(int [][] map, int count) { if((n*m-count)/5 + count <= res) return; if(res == (n*m)/6) return; if(count > res) { res = count; for(int i = 0 ; i < n ; i++) for(int j = 0 ; j < m ; j++) ret[i][j] = map[i][j]; } boolean o1 = false, o2 = false, o3 = false, o4 = false; for(int r = 0 ; r < map.length ; r++) for(int c = 0 ; c < map[0].length ; c++) { if(r >= 2 && c >= 1 && c <= m-2 && map[r-2][c-1] + map[r-2][c] + map[r-2][c+1] + map[r-1][c] + map[r][c] == 0) { o1 = true; map[r-2][c-1] = map[r-2][c] = map[r-2][c+1] = map[r-1][c] = map[r][c] = count+1; rec(map, count+1); map[r-2][c-1] = map[r-2][c] = map[r-2][c+1] = map[r-1][c] = map[r][c] = 0; } if(r >= 2 && c >= 2 && map[r-2][c] + map[r-1][c-2] + map[r-1][c-1] + map[r-1][c] + map[r][c] == 0) { o2 = true; map[r-2][c] = map[r-1][c-2] = map[r-1][c-1] = map[r-1][c] = map[r][c] = count+1; rec(map, count+1); map[r-2][c] = map[r-1][c-2] = map[r-1][c-1] = map[r-1][c] = map[r][c] = 0; } if(r >= 2 && c >= 1 && c <= m-2 && map[r-2][c] + map[r-1][c] + map[r][c-1] + map[r][c] + map[r][c+1] == 0) { o3 = true; map[r-2][c] = map[r-1][c] = map[r][c-1] = map[r][c] = map[r][c+1] = count+1; rec(map, count+1); map[r-2][c] = map[r-1][c] = map[r][c-1] = map[r][c] = map[r][c+1] = 0; } if(r >= 2 && c <= m-3 && map[r-2][c] + map[r-1][c] + map[r-1][c+1] + map[r-1][c+2] + map[r][c] == 0) { o4 = true; map[r-2][c] = map[r-1][c] = map[r-1][c+1] = map[r-1][c+2] = map[r][c] = count+1; rec(map, count+1); map[r-2][c] = map[r-1][c] = map[r-1][c+1] = map[r-1][c+2] = map[r][c] = 0; } if(o1 && o2 && o3 && o4) return; } } }
Java
["3 3", "5 6", "2 2"]
3 seconds
["1\nAAA\n.A.\n.A.", "4\nA..C..\nAAAC..\nABCCCD\n.B.DDD\nBBB..D", "0\n..\n.."]
null
Java 7
standard input
[]
f29eba31c20246686b8427b7aeadd184
The only line contains two space-separated integers n and m β€” the sizes of the warehouse (1 ≀ n, m ≀ 9).
2,300
In the first line print the maximum number of turboplows that can be positioned in the warehouse. In each of the next n lines print m characters. Use "." (dot) to mark empty space and use successive capital Latin letters ("A" for the first turboplow, "B" for the second one and so on until you reach the number of turboplows in your scheme) to mark place for the corresponding turboplows considering that they are positioned in the optimal manner in the warehouse. The order in which you number places for the turboplows does not matter. If there are several optimal solutions for a warehouse of the given size, print any of them.
standard output
PASSED
034a770596568f221b943f24d76b9fce
train_002.jsonl
1326380700
Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse.He's got problems with some particularly large piece of equipment, which is, of course, turboplows. The problem is that when a turboplow is stored, it takes up not some simply rectangular space. It takes up a T-shaped space like on one of the four pictures below (here character "#" stands for the space occupied by the turboplow and character "." stands for the free space): ### ..# .#. #...#. ### .#. ###.#. ..# ### #.. Simon faced a quite natural challenge: placing in the given n × m cells warehouse the maximum number of turboplows. As one stores the turboplows, he can rotate them in any manner (so that they take up the space like on one of the four pictures above). However, two turboplows cannot "overlap", that is, they cannot share the same cell in the warehouse.Simon feels that he alone cannot find the optimal way of positioning the plugs in the warehouse that would maximize their quantity. Can you help him?
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Iterator; import java.util.LinkedList; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { /********************************************** a list of common variables **********************************************/ private MyScanner scan = new MyScanner(); private PrintWriter out = new PrintWriter(System.out); private final double PI = Math.PI; private final int INF = (int)(1e9); private final double EPS = 1e-6; private final int SIZEN = (int)(1e7); private final int MOD = (int)(1e9 + 7); private final long MODH = 10000000007L, BASE = 10007; private final int[] DX = {0, 1, 0, -1}, DY = {-1, 0, 1, 0}; private final int[][] dx = {{0, 1, 1, 1, 2}, {0, 1, 2, 2, 2}, {0, 1, 1, 1, 2}, {0, 0, 1, 2, 0}}; private final int[][] dy = {{0, 0, 1, 2, 0}, {1, 1, 1, 0, 2}, {2, 2, 1, 0, 2}, {0, 1, 1, 1, 2}}; private int n, m, ans; private char[][] map, ret; public boolean isLegal(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } public void dfs(int x, int y, int cnt) { if(cnt + (n * m - x * m - y) / 6 <= ans) return; if(x + 2 == n) { if(cnt > ans) { ans = cnt; for(int i = 0;i < n;++i) System.arraycopy(map[i], 0, ret[i], 0, m); } return; } if(y + 2 == m) dfs(x + 1, 0, cnt); for(int k = 0;k < 4;++k) { boolean canPlace = true; for(int i = 0;i < 5;++i) { if(!isLegal(x + dx[k][i], y + dy[k][i]) || map[x + dx[k][i]][y + dy[k][i]] != '.') { canPlace = false; break; } } if(!canPlace) continue; for(int i = 0;i < 5;++i) map[x + dx[k][i]][y + dy[k][i]] = (char)('A' + cnt); dfs(x, y + 1, cnt + 1); for(int i = 0;i < 5;++i) map[x + dx[k][i]][y + dy[k][i]] = '.'; } dfs(x, y + 1, cnt); } public void foo () { n = scan.nextInt(); m = scan.nextInt(); map = new char[n][m]; for(int i = 0;i < n;++i) Arrays.fill(map[i], '.'); if(n < 3 || m < 3) { out.println(0); for(int i = 0;i < n;++i) out.println(map[i]); return; } ans = 0; ret = new char[n][m]; dfs(0, 0, 0); out.println(ans); for(int i = 0;i < n;++i) out.println(ret[i]); } public static void main(String[] args) { Main m = new Main(); m.foo(); m.out.close(); } /********************************************** a list of common algorithms **********************************************/ /** * 1---Get greatest common divisor * @param a : first number * @param b : second number * @return greatest common divisor */ public long gcd(long a, long b) { return 0 == b ? a : gcd(b, a % b); } /** * 2---Get the distance from a point to a line * @param x1 the x coordinate of one endpoint of the line * @param y1 the y coordinate of one endpoint of the line * @param x2 the x coordinate of the other endpoint of the line * @param y2 the y coordinate of the other endpoint of the line * @param x the x coordinate of the point * @param y the x coordinate of the point * @return the distance from a point to a line */ public double getDist(long x1, long y1, long x2, long y2, long x, long y) { long a = y2 - y1; long b = x1 - x2; long c = y1 * (x2 - x1) - x1 * (y2 - y1); return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b); } /** * 3---Get the distance from one point to a segment (not a line) * @param x1 the x coordinate of one endpoint of the segment * @param y1 the y coordinate of one endpoint of the segment * @param x2 the x coordinate of the other endpoint of the segment * @param y2 the y coordinate of the other endpoint of the segment * @param x the x coordinate of the point * @param y the y coordinate of the point * @return the distance from one point to a segment (not a line) */ public double ptToSeg(long x1, long y1, long x2, long y2, long x, long y) { double cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1); if(cross <= 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } double d = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); if(cross >= d) { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } double r = cross / d; double px = x1 + (x2 - x1) * r; double py = y1 + (y2 - y1) * r; return (x - px) * (x - px) + (y - py) * (y - py); } /** * 4---KMP match, i.e. kmpMatch("abcd", "bcd") = 1, kmpMatch("abcd", "bfcd") = -1. * @param t: String to match. * @param p: String to be matched. * @return if can match, first index; otherwise -1. */ public int kmpMatch(char[] t, char[] p) { int n = t.length; int m = p.length; int[] next = new int[m + 1]; next[0] = -1; int j = -1; for(int i = 1;i < m;++i) { while(j >= 0 && p[i] != p[j + 1]) { j = next[j]; } if(p[i] == p[j + 1]) { ++j; } next[i] = j; } j = -1; for(int i = 0;i < n;++i) { while(j >= 0 && t[i] != p[j + 1]) { j = next[j]; } if(t[i] == p[j + 1]) { ++j; } if(j == m - 1) { return i - m + 1; } } return -1; } /** * 5---Get the hash code of a String * @param s: input string * @return hash code */ public long hash(String s) { long key = 0, t = 1; for(int i = 0;i < s.length();++i) { key = (key + s.charAt(i) * t) % MODH; t = t * BASE % MODH; } return key; } /** * 6---Get x ^ n % MOD quickly. * @param x: base * @param n: times * @return x ^ n % MOD */ public long quickMod(long x, long n) { long ans = 1; while(n > 0) { if(1 == n % 2) { ans = ans * x % MOD; } x = x * x % MOD; n >>= 1; } return ans; } /** * 7---judge if a point is located inside a polygon * @param x0 the x coordinate of the point * @param y0 the y coordinate of the point * @return true if it is inside the polygon, otherwise false */ /*public boolean contains(double x0, double y0) { int cross = 0; for(int i = 0;i < n;++i) { double s = x[i + 1] == x[i] ? 100000000 : (double)(y[i + 1] - y[i]) / (x[i + 1] - x[i]); boolean b1 = x[i] <= x0 && x0 < x[i + 1]; boolean b2 = x[i + 1] <= x0 && x0 < x[i]; boolean b3 = y0 < s * (x0 - x[i]) + y[i]; if((b1 || b2) && b3) ++cross; } return cross % 2 != 0; }*/ /** * 8---judge if a point is located on the segment * @param x1 the x coordinate of one point of the segment * @param y1 the y coordinate of one point of the segment * @param x2 the x coordinate of another point of the segment * @param y2 the y coordinate of another point of the segment * @param x the x coordinate of the point * @param y the y coordinate of the point * @return true if it is located on the segment, otherwise false */ public boolean isOnSeg(long x1, long y1, long x2, long y2, long x, long y) { return (x - x1) * (y2 - y1) == (x2 - x1) * (y - y1) && x >= Math.min(x1, x2) && x <= Math.max(x1, x2) && y >= Math.min(y1, y2) && y <= Math.max(y1, y2); } /** * 9---get the cross product * @param p1 point A * @param p2 point B * @param p point O * @return cross product of OA x OB */ /*public long cross(Point p1, Point p2, Point p) { return (long)(p1.x - p.x) * (p2.y - p.y) - (long)(p2.x - p.x) * (p1.y - p.y); }*/ /** * 10---implement topsort and tell if it is possible * @return true if it is possible to implement topsort, otherwise false */ /*public boolean topsort() { Queue<Integer> q = new LinkedList<Integer>(); StringBuilder ans = new StringBuilder(); int[] in = new int[26]; for(int i = 0;i < 26;++i) { if(0 == in[i]) { ans.append((char)('a' + i)); q.add(i); } } while(!q.isEmpty()) { int u = q.poll(); for(int i = 0;i < 26;++i) { if(map[u][i]) { --in[i]; if(0 == in[i]) { ans.append((char)('a' + i)); q.add(i); } } } } return 26 == ans.length(); }*/ class MyScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; BufferedInputStream bis = new BufferedInputStream(System.in); public int read() { if (-1 == numChars) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = bis.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 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 & 15; 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 & 15) * m; c = read(); } } 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(); } private boolean isSpaceChar(int c) { return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c; } } }
Java
["3 3", "5 6", "2 2"]
3 seconds
["1\nAAA\n.A.\n.A.", "4\nA..C..\nAAAC..\nABCCCD\n.B.DDD\nBBB..D", "0\n..\n.."]
null
Java 7
standard input
[]
f29eba31c20246686b8427b7aeadd184
The only line contains two space-separated integers n and m β€” the sizes of the warehouse (1 ≀ n, m ≀ 9).
2,300
In the first line print the maximum number of turboplows that can be positioned in the warehouse. In each of the next n lines print m characters. Use "." (dot) to mark empty space and use successive capital Latin letters ("A" for the first turboplow, "B" for the second one and so on until you reach the number of turboplows in your scheme) to mark place for the corresponding turboplows considering that they are positioned in the optimal manner in the warehouse. The order in which you number places for the turboplows does not matter. If there are several optimal solutions for a warehouse of the given size, print any of them.
standard output
PASSED
0375c1831a2c9af39b9d08359a064e13
train_002.jsonl
1326380700
Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse.He's got problems with some particularly large piece of equipment, which is, of course, turboplows. The problem is that when a turboplow is stored, it takes up not some simply rectangular space. It takes up a T-shaped space like on one of the four pictures below (here character "#" stands for the space occupied by the turboplow and character "." stands for the free space): ### ..# .#. #...#. ### .#. ###.#. ..# ### #.. Simon faced a quite natural challenge: placing in the given n × m cells warehouse the maximum number of turboplows. As one stores the turboplows, he can rotate them in any manner (so that they take up the space like on one of the four pictures above). However, two turboplows cannot "overlap", that is, they cannot share the same cell in the warehouse.Simon feels that he alone cannot find the optimal way of positioning the plugs in the warehouse that would maximize their quantity. Can you help him?
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Iterator; import java.util.LinkedList; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class studyDemo { /********************************************** a list of common variables **********************************************/ private MyScanner scan = new MyScanner(); private PrintWriter out = new PrintWriter(System.out); private final double PI = Math.PI; private final int INF = (int)(1e9); private final double EPS = 1e-6; private final int SIZEN = (int)(1e7); private final int MOD = (int)(1e9 + 7); private final long MODH = 10000000007L, BASE = 10007; private final int[] DX = {0, 1, 0, -1}, DY = {-1, 0, 1, 0}; private final int[][] dx = {{0, 1, 1, 1, 2}, {0, 1, 2, 2, 2}, {0, 1, 1, 1, 2}, {0, 0, 1, 2, 0}}; private final int[][] dy = {{0, 0, 1, 2, 0}, {1, 1, 1, 0, 2}, {2, 2, 1, 0, 2}, {0, 1, 1, 1, 2}}; private int n, m, ans; private char[][] map, ret; public boolean isLegal(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } public void dfs(int x, int y, int cnt) { if(cnt + (n * m - x * m - y) / 6 <= ans) return; if(x + 2 == n) { if(cnt > ans) { ans = cnt; for(int i = 0;i < n;++i) System.arraycopy(map[i], 0, ret[i], 0, m); } return; } if(y + 2 == m) dfs(x + 1, 0, cnt); for(int k = 0;k < 4;++k) { boolean canPlace = true; for(int i = 0;i < 5;++i) { if(!isLegal(x + dx[k][i], y + dy[k][i]) || map[x + dx[k][i]][y + dy[k][i]] != '.') { canPlace = false; break; } } if(!canPlace) continue; for(int i = 0;i < 5;++i) map[x + dx[k][i]][y + dy[k][i]] = (char)('A' + cnt); dfs(x, y + 1, cnt + 1); for(int i = 0;i < 5;++i) map[x + dx[k][i]][y + dy[k][i]] = '.'; } dfs(x, y + 1, cnt); } public void foo () { n = scan.nextInt(); m = scan.nextInt(); map = new char[n][m]; for(int i = 0;i < n;++i) Arrays.fill(map[i], '.'); if(n < 3 || m < 3) { out.println(0); for(int i = 0;i < n;++i) out.println(map[i]); return; } ans = 0; ret = new char[n][m]; dfs(0, 0, 0); out.println(ans); for(int i = 0;i < n;++i) out.println(ret[i]); } public static void main(String[] args) { studyDemo m = new studyDemo(); m.foo(); m.out.close(); } /********************************************** a list of common algorithms **********************************************/ /** * 1---Get greatest common divisor * @param a : first number * @param b : second number * @return greatest common divisor */ public long gcd(long a, long b) { return 0 == b ? a : gcd(b, a % b); } /** * 2---Get the distance from a point to a line * @param x1 the x coordinate of one endpoint of the line * @param y1 the y coordinate of one endpoint of the line * @param x2 the x coordinate of the other endpoint of the line * @param y2 the y coordinate of the other endpoint of the line * @param x the x coordinate of the point * @param y the x coordinate of the point * @return the distance from a point to a line */ public double getDist(long x1, long y1, long x2, long y2, long x, long y) { long a = y2 - y1; long b = x1 - x2; long c = y1 * (x2 - x1) - x1 * (y2 - y1); return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b); } /** * 3---Get the distance from one point to a segment (not a line) * @param x1 the x coordinate of one endpoint of the segment * @param y1 the y coordinate of one endpoint of the segment * @param x2 the x coordinate of the other endpoint of the segment * @param y2 the y coordinate of the other endpoint of the segment * @param x the x coordinate of the point * @param y the y coordinate of the point * @return the distance from one point to a segment (not a line) */ public double ptToSeg(long x1, long y1, long x2, long y2, long x, long y) { double cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1); if(cross <= 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } double d = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); if(cross >= d) { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } double r = cross / d; double px = x1 + (x2 - x1) * r; double py = y1 + (y2 - y1) * r; return (x - px) * (x - px) + (y - py) * (y - py); } /** * 4---KMP match, i.e. kmpMatch("abcd", "bcd") = 1, kmpMatch("abcd", "bfcd") = -1. * @param t: String to match. * @param p: String to be matched. * @return if can match, first index; otherwise -1. */ public int kmpMatch(char[] t, char[] p) { int n = t.length; int m = p.length; int[] next = new int[m + 1]; next[0] = -1; int j = -1; for(int i = 1;i < m;++i) { while(j >= 0 && p[i] != p[j + 1]) { j = next[j]; } if(p[i] == p[j + 1]) { ++j; } next[i] = j; } j = -1; for(int i = 0;i < n;++i) { while(j >= 0 && t[i] != p[j + 1]) { j = next[j]; } if(t[i] == p[j + 1]) { ++j; } if(j == m - 1) { return i - m + 1; } } return -1; } /** * 5---Get the hash code of a String * @param s: input string * @return hash code */ public long hash(String s) { long key = 0, t = 1; for(int i = 0;i < s.length();++i) { key = (key + s.charAt(i) * t) % MODH; t = t * BASE % MODH; } return key; } /** * 6---Get x ^ n % MOD quickly. * @param x: base * @param n: times * @return x ^ n % MOD */ public long quickMod(long x, long n) { long ans = 1; while(n > 0) { if(1 == n % 2) { ans = ans * x % MOD; } x = x * x % MOD; n >>= 1; } return ans; } /** * 7---judge if a point is located inside a polygon * @param x0 the x coordinate of the point * @param y0 the y coordinate of the point * @return true if it is inside the polygon, otherwise false */ /*public boolean contains(double x0, double y0) { int cross = 0; for(int i = 0;i < n;++i) { double s = x[i + 1] == x[i] ? 100000000 : (double)(y[i + 1] - y[i]) / (x[i + 1] - x[i]); boolean b1 = x[i] <= x0 && x0 < x[i + 1]; boolean b2 = x[i + 1] <= x0 && x0 < x[i]; boolean b3 = y0 < s * (x0 - x[i]) + y[i]; if((b1 || b2) && b3) ++cross; } return cross % 2 != 0; }*/ /** * 8---judge if a point is located on the segment * @param x1 the x coordinate of one point of the segment * @param y1 the y coordinate of one point of the segment * @param x2 the x coordinate of another point of the segment * @param y2 the y coordinate of another point of the segment * @param x the x coordinate of the point * @param y the y coordinate of the point * @return true if it is located on the segment, otherwise false */ public boolean isOnSeg(long x1, long y1, long x2, long y2, long x, long y) { return (x - x1) * (y2 - y1) == (x2 - x1) * (y - y1) && x >= Math.min(x1, x2) && x <= Math.max(x1, x2) && y >= Math.min(y1, y2) && y <= Math.max(y1, y2); } /** * 9---get the cross product * @param p1 point A * @param p2 point B * @param p point O * @return cross product of OA x OB */ /*public long cross(Point p1, Point p2, Point p) { return (long)(p1.x - p.x) * (p2.y - p.y) - (long)(p2.x - p.x) * (p1.y - p.y); }*/ /** * 10---implement topsort and tell if it is possible * @return true if it is possible to implement topsort, otherwise false */ /*public boolean topsort() { Queue<Integer> q = new LinkedList<Integer>(); StringBuilder ans = new StringBuilder(); int[] in = new int[26]; for(int i = 0;i < 26;++i) { if(0 == in[i]) { ans.append((char)('a' + i)); q.add(i); } } while(!q.isEmpty()) { int u = q.poll(); for(int i = 0;i < 26;++i) { if(map[u][i]) { --in[i]; if(0 == in[i]) { ans.append((char)('a' + i)); q.add(i); } } } } return 26 == ans.length(); }*/ class MyScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; BufferedInputStream bis = new BufferedInputStream(System.in); public int read() { if (-1 == numChars) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = bis.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 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 & 15; 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 & 15) * m; c = read(); } } 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(); } private boolean isSpaceChar(int c) { return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c; } } }
Java
["3 3", "5 6", "2 2"]
3 seconds
["1\nAAA\n.A.\n.A.", "4\nA..C..\nAAAC..\nABCCCD\n.B.DDD\nBBB..D", "0\n..\n.."]
null
Java 7
standard input
[]
f29eba31c20246686b8427b7aeadd184
The only line contains two space-separated integers n and m β€” the sizes of the warehouse (1 ≀ n, m ≀ 9).
2,300
In the first line print the maximum number of turboplows that can be positioned in the warehouse. In each of the next n lines print m characters. Use "." (dot) to mark empty space and use successive capital Latin letters ("A" for the first turboplow, "B" for the second one and so on until you reach the number of turboplows in your scheme) to mark place for the corresponding turboplows considering that they are positioned in the optimal manner in the warehouse. The order in which you number places for the turboplows does not matter. If there are several optimal solutions for a warehouse of the given size, print any of them.
standard output
PASSED
58d38f4c1293d6fae36d4ed8dd3e5fe2
train_002.jsonl
1504702500
Ilya is sitting in a waiting area of Metropolis airport and is bored of looking at time table that shows again and again that his plane is delayed. So he took out a sheet of paper and decided to solve some problems.First Ilya has drawn a grid of size n × n and marked n squares on it, such that no two marked squares share the same row or the same column. He calls a rectangle on a grid with sides parallel to grid sides beautiful if exactly two of its corner squares are marked. There are exactly nΒ·(n - 1) / 2 beautiful rectangles.Ilya has chosen q query rectangles on a grid with sides parallel to grid sides (not necessarily beautiful ones), and for each of those rectangles he wants to find its beauty degree. Beauty degree of a rectangle is the number of beautiful rectangles that share at least one square with the given one.Now Ilya thinks that he might not have enough time to solve the problem till the departure of his flight. You are given the description of marked cells and the query rectangles, help Ilya find the beauty degree of each of the query rectangles.
512 megabytes
import java.io.*; import java.util.*; import java.util.function.IntConsumer; public class Solution { static MyScanner sc; private static PrintWriter out; static long M = 1000000007; public static void main(String[] s) throws Exception { StringBuilder stringBuilder = new StringBuilder(); // stringBuilder.append("200000 200000 "); // int[] tt = new int[200000]; // for (int p = 0; p < tt.length; p++) { // tt[p] = p + 1; // } // Random rnd = new Random(); // for (int i = tt.length - 1; i > 1; i--) { // int nn = rnd.nextInt(i); // int k = tt[i]; // tt[i] = tt[nn]; // tt[nn] = k; // } // for (int k : tt) { // stringBuilder.append(k + " "); // } // // for (int i = 0; i < tt.length; i++) { // int l = rnd.nextInt(100000) + 1; // int r = rnd.nextInt(100000) + 1; // stringBuilder.append(l + " " + r + " "); // l += rnd.nextInt(50000); // r += rnd.nextInt(50000); // stringBuilder.append(l + " " + r + " "); // } if (stringBuilder.length() == 0) { sc = new MyScanner(System.in); } else { sc = new MyScanner(new BufferedReader(new StringReader(stringBuilder.toString()))); } out = new PrintWriter(new OutputStreamWriter(System.out)); long t = System.currentTimeMillis(); solve(); out.flush(); } private static void solve() { int n = sc.nextInt(); int q = sc.nextInt(); SparseMatrix p = new SparseMatrix(n); int[][] data = new int[n][2]; for (int l = 0; l < n; l++) { data[l][0] = l + 1; data[l][1] = sc.nextInt(); } Arrays.sort(data, Comparator.comparingInt(t -> t[1])); for (int [] k : data) { p.add(k[0], k[1]); } for (int i = 0; i < q; i++) { int l = sc.nextInt(); int d = sc.nextInt(); int r = sc.nextInt(); int u = sc.nextInt(); int[] k11 = new int[]{l - 1, r, n}; int[] k22 = new int[]{d - 1, u, n}; long[][] longs = new long[3][3]; for (int k1 = 0; k1 < 3; k1++) { for (int k2 = 0; k2 < 3; k2++) { longs[k1][k2] = p.sum(k11[k1], k22[k2]); } } long res = 0; res += t(longs[2][2]); res -= t(longs[2][0]); res -= t(longs[2][2] - longs[2][1]); res -= t(longs[0][2]); res -= t(longs[2][2] - longs[1][2]) ; res += t(longs[0][0]); res += t(longs[2][0] - longs[1][0]); res += t(longs[0][2] - longs[0][1]); res += t(longs[2][2] - longs[2][1]-longs[1][2] + longs[1][1]); out.println(res); // out.flush( ); } } private static long t(long l) { return l * (l - 1) / 2; } private static void solveT() { int t = sc.nextInt(); while (t-- > 0) { solve(); } } private static long gcd(long l, long l1) { if (l > l1) return gcd(l1, l); if (l == 0) return l1; return gcd(l1 % l, l); } private static long pow(long a, long b, long m) { if (b == 0) return 1; if (b == 1) return a; long pp = pow(a, b / 2, m); pp *= pp; pp %= m; return (pp * (b % 2 == 0 ? 1 : a)) % m; } private static final class AList { int[] data; int c = 0; public AList(int n) { this.data = new int[Math.max(Integer.highestOneBit(n - 1) << 1, 4)]; } public AList() { this(4); } public AList(int[] data) { this(data.length); System.arraycopy(data, 0, this.data, 0, data.length); } public void sort() { Arrays.sort(data, 0, c); } public void work(IntConsumer intConsumer) { for (int i = 0; i < c; i++) { intConsumer.accept(data[i]); } } public void add(int k) { if (c == data.length) { data = Arrays.copyOf(data, data.length << 1); } data[c++] = k; } } private static final class SparseMatrix { AList[] init; public SparseMatrix(int n) { init = new AList[n + 1]; for (int i = 1; i <= n; i++) { init[i] = new AList(); } } public void add(int row, int column) { while (row < init.length) { init[row].add(column); row += row & (-row); } } private long sum(int x, int y) { if (x >= init.length) x = init.length - 1; if (y >= init.length) y = init.length - 1; if (y <= 0) return 0; long sum = 0; while (x > 0) { sum += r(x, y); x -= x & (-x); } return sum; } private long r(int x, int y) { return biSearch(init[x].data, 0, init[x].c, y); } } static int biSearch(int[] k, int from, int to, int val) { int r = Arrays.binarySearch(k, from, to, val + 1); if (r < 0) r = -r - 1; return r; } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner(BufferedReader br) { this.br = br; } public MyScanner(InputStream in) { this(new BufferedReader(new InputStreamReader(in))); } void findToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } } String next() { findToken(); return st.nextToken(); } int[] na(int n) { int[] k = new int[n]; for (int i = 0; i < n; i++) { k[i] = sc.nextInt(); } return k; } long[] nl(int n) { long[] k = new long[n]; for (int i = 0; i < n; i++) { k[i] = sc.nextLong(); } return k; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["2 3\n1 2\n1 1 1 1\n1 1 1 2\n1 1 2 2", "4 2\n1 3 2 4\n4 1 4 4\n1 1 2 3"]
2 seconds
["1\n1\n1", "3\n5"]
NoteThe first sample test has one beautiful rectangle that occupies the whole grid, therefore the answer to any query is 1.In the second sample test the first query rectangle intersects 3 beautiful rectangles, as shown on the picture below: There are 5 beautiful rectangles that intersect the second query rectangle, as shown on the following picture:
Java 8
standard input
[ "data structures" ]
bc834c0aa602a8ba789b676affb0b33a
The first line of input contains two integers n and q (2 ≀ n ≀ 200 000, 1 ≀ q ≀ 200 000)Β β€” the size of the grid and the number of query rectangles. The second line contains n integers p1, p2, ..., pn, separated by spaces (1 ≀ pi ≀ n, all pi are different), they specify grid squares marked by Ilya: in column i he has marked a square at row pi, rows are numbered from 1 to n, bottom to top, columns are numbered from 1 to n, left to right. The following q lines describe query rectangles. Each rectangle is described by four integers: l, d, r, u (1 ≀ l ≀ r ≀ n, 1 ≀ d ≀ u ≀ n), here l and r are the leftmost and the rightmost columns of the rectangle, d and u the bottommost and the topmost rows of the rectangle.
2,100
For each query rectangle output its beauty degree on a separate line.
standard output
PASSED
c7376ea9e2561b06cd277db52aace5c0
train_002.jsonl
1504702500
Ilya is sitting in a waiting area of Metropolis airport and is bored of looking at time table that shows again and again that his plane is delayed. So he took out a sheet of paper and decided to solve some problems.First Ilya has drawn a grid of size n × n and marked n squares on it, such that no two marked squares share the same row or the same column. He calls a rectangle on a grid with sides parallel to grid sides beautiful if exactly two of its corner squares are marked. There are exactly nΒ·(n - 1) / 2 beautiful rectangles.Ilya has chosen q query rectangles on a grid with sides parallel to grid sides (not necessarily beautiful ones), and for each of those rectangles he wants to find its beauty degree. Beauty degree of a rectangle is the number of beautiful rectangles that share at least one square with the given one.Now Ilya thinks that he might not have enough time to solve the problem till the departure of his flight. You are given the description of marked cells and the query rectangles, help Ilya find the beauty degree of each of the query rectangles.
512 megabytes
// practice with rainboy import java.io.*; import java.util.*; public class CF853C { static long[] aa; static int n, m; static class V { int i, j, h; V(int i, int j, int h) { this.i = i; this.j = j; this.h = h; } } static V[] vv; static int[] tt; static void update(int i) { while (i < n) { tt[i]++; i |= i + 1; } } static int query(int i) { int a = 0; while (i >= 0) { a += tt[i]; i &= i + 1; i--; } return a; } static void solve(int[] ii, int[] jj, int[] pp) { for (int i = 0; i < n; i++) vv[i] = new V(i, pp[i], -1); for (int h = 0; h < m; h++) vv[n + h] = new V(ii[h] - 1, jj[h] - 1, h); Arrays.sort(vv, (u, v) -> u.i != v.i ? u.i - v.i : u.h - v.h); Arrays.fill(tt, 0); for (int i = 0; i < n + m; i++) { V v = vv[i]; if (v.h == -1) update(v.j); else { int a = query(v.j); aa[v.h] += (long) a * (a - 1) / 2; } } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] pp = new int[n]; int[] pp_ = new int[n]; for (int i = 0; i < n; i++) { pp[i] = Integer.parseInt(st.nextToken()) - 1; pp_[i] = n - 1 - pp[i]; } int[] ll = new int[m]; int[] dd = new int[m]; int[] rr = new int[m]; int[] uu = new int[m]; int[] rr_ = new int[m]; int[] uu_ = new int[m]; for (int h = 0; h < m; h++) { st = new StringTokenizer(br.readLine()); ll[h] = Integer.parseInt(st.nextToken()) - 1; dd[h] = Integer.parseInt(st.nextToken()) - 1; rr[h] = Integer.parseInt(st.nextToken()) - 1; uu[h] = Integer.parseInt(st.nextToken()) - 1; rr_[h] = n - 1 - rr[h]; uu_[h] = n - 1 - uu[h]; } aa = new long[m]; Arrays.fill(aa, (long) n * (n - 1) / 2); for (int h = 0, k; h < m; h++) { k = ll[h]; aa[h] -= (long) k * (k - 1) / 2; k = dd[h]; aa[h] -= (long) k * (k - 1) / 2; k = rr_[h]; aa[h] -= (long) k * (k - 1) / 2; k = uu_[h]; aa[h] -= (long) k * (k - 1) / 2; } vv = new V[n + m]; tt = new int[n]; solve(ll, dd, pp); solve(ll, uu_, pp_); for (int i = 0, j = n - 1, tmp; i < j; i++, j--) { tmp = pp[i]; pp[i] = pp[j]; pp[j] = tmp; tmp = pp_[i]; pp_[i] = pp_[j]; pp_[j] = tmp; } solve(rr_, dd, pp); solve(rr_, uu_, pp_); for (int h = 0; h < m; h++) pw.println(aa[h]); pw.close(); } }
Java
["2 3\n1 2\n1 1 1 1\n1 1 1 2\n1 1 2 2", "4 2\n1 3 2 4\n4 1 4 4\n1 1 2 3"]
2 seconds
["1\n1\n1", "3\n5"]
NoteThe first sample test has one beautiful rectangle that occupies the whole grid, therefore the answer to any query is 1.In the second sample test the first query rectangle intersects 3 beautiful rectangles, as shown on the picture below: There are 5 beautiful rectangles that intersect the second query rectangle, as shown on the following picture:
Java 8
standard input
[ "data structures" ]
bc834c0aa602a8ba789b676affb0b33a
The first line of input contains two integers n and q (2 ≀ n ≀ 200 000, 1 ≀ q ≀ 200 000)Β β€” the size of the grid and the number of query rectangles. The second line contains n integers p1, p2, ..., pn, separated by spaces (1 ≀ pi ≀ n, all pi are different), they specify grid squares marked by Ilya: in column i he has marked a square at row pi, rows are numbered from 1 to n, bottom to top, columns are numbered from 1 to n, left to right. The following q lines describe query rectangles. Each rectangle is described by four integers: l, d, r, u (1 ≀ l ≀ r ≀ n, 1 ≀ d ≀ u ≀ n), here l and r are the leftmost and the rightmost columns of the rectangle, d and u the bottommost and the topmost rows of the rectangle.
2,100
For each query rectangle output its beauty degree on a separate line.
standard output
PASSED
53d67f2ab1a3f547251609ec9d24b149
train_002.jsonl
1504702500
Ilya is sitting in a waiting area of Metropolis airport and is bored of looking at time table that shows again and again that his plane is delayed. So he took out a sheet of paper and decided to solve some problems.First Ilya has drawn a grid of size n × n and marked n squares on it, such that no two marked squares share the same row or the same column. He calls a rectangle on a grid with sides parallel to grid sides beautiful if exactly two of its corner squares are marked. There are exactly nΒ·(n - 1) / 2 beautiful rectangles.Ilya has chosen q query rectangles on a grid with sides parallel to grid sides (not necessarily beautiful ones), and for each of those rectangles he wants to find its beauty degree. Beauty degree of a rectangle is the number of beautiful rectangles that share at least one square with the given one.Now Ilya thinks that he might not have enough time to solve the problem till the departure of his flight. You are given the description of marked cells and the query rectangles, help Ilya find the beauty degree of each of the query rectangles.
512 megabytes
import java.io.*; import java.util.*; /* 6 1 1 5 3 4 2 6 3 3 4 4 */ public class C { static InputStream is; static long[] ans; public static void main(String[] args) throws IOException { is = System.in; int n = ni(); int q = ni(); int[] p = new int[n]; int[] prev = new int[n]; for (int i = 0; i < p.length; i++) { p[i] = ni()-1; } for (int i = 0; i < p.length; i++) { prev[i] = p[p.length-1-i]; } ans = new long[q]; ev[] fw = new ev[q]; ev[] rev = new ev[q]; for(int i =0; i < q; i++){ int c1 = ni()-1; int r1 = ni()-1; int c2 = ni()-1; int r2 = ni()-1; ans[i] = n*(long)(n-1)/2; ans[i] -= c1*(long)(c1-1)/2; ans[i] -= (n-1-c2)*(long)(n-2-c2)/2; ans[i] -= r1*(long)(r1-1)/2; ans[i] -= (n-1-r2)*(long)(n-2-r2)/2; fw[i] = new ev(c1,r1,r2,i); rev[i] = new ev(n-1-c2,r1,r2,i); } Arrays.sort(fw); Arrays.sort(rev); sweep(p,fw); sweep(prev,rev); PrintWriter out = new PrintWriter(System.out); for(int i =0; i < ans.length; i++){ out.println(ans[i]); } out.close(); } static void sweep(int[] p, ev[] qs){ int curcol = 0; Bit bit = new Bit(p.length); for (int i = 0; i < qs.length; i++) { while(curcol < qs[i].t){ bit.update(p[curcol], 1); //System.out.println("updated at " + curcol); curcol++; } long top = bit.query(0,qs[i].l-1); ans[qs[i].qid] += top*(top-1)/2; long bot = bit.query(qs[i].r+1,p.length-1); ans[qs[i].qid] += bot*(bot-1)/2; //System.out.println(top + " tb " + bot); } } static class ev implements Comparable<ev>{ int t,l,r,qid; public ev(int t, int l, int r, int qid) { super(); this.t = t; this.l = l; this.r = r; this.qid = qid; } @Override public int compareTo(ev o) { return t - o.t; } } static class Bit{ long[] val; int n; public Bit(int n){ this.n = n; val = new long[n]; } public long query(int pos){ long ans = 0; for(int i = pos; i >=0; i = (i&(i+1))-1) { ans += val[i]; } return ans; } public long query(int start, int end){ if(start > end) return 0; return query(end)- query(start-1); } public void update(int pos, long inc){ for(int i = pos; i <n; i |=(i+1)){ val[i] += inc; } } } private static byte[] inbuf = new byte[1024]; public static int lenbuf = 0, ptrbuf = 0; private static int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static double nd() { return Double.parseDouble(ns()); } private static char nc() { return (char)skip(); } private static String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private static 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 static 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 static int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private static int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } }
Java
["2 3\n1 2\n1 1 1 1\n1 1 1 2\n1 1 2 2", "4 2\n1 3 2 4\n4 1 4 4\n1 1 2 3"]
2 seconds
["1\n1\n1", "3\n5"]
NoteThe first sample test has one beautiful rectangle that occupies the whole grid, therefore the answer to any query is 1.In the second sample test the first query rectangle intersects 3 beautiful rectangles, as shown on the picture below: There are 5 beautiful rectangles that intersect the second query rectangle, as shown on the following picture:
Java 8
standard input
[ "data structures" ]
bc834c0aa602a8ba789b676affb0b33a
The first line of input contains two integers n and q (2 ≀ n ≀ 200 000, 1 ≀ q ≀ 200 000)Β β€” the size of the grid and the number of query rectangles. The second line contains n integers p1, p2, ..., pn, separated by spaces (1 ≀ pi ≀ n, all pi are different), they specify grid squares marked by Ilya: in column i he has marked a square at row pi, rows are numbered from 1 to n, bottom to top, columns are numbered from 1 to n, left to right. The following q lines describe query rectangles. Each rectangle is described by four integers: l, d, r, u (1 ≀ l ≀ r ≀ n, 1 ≀ d ≀ u ≀ n), here l and r are the leftmost and the rightmost columns of the rectangle, d and u the bottommost and the topmost rows of the rectangle.
2,100
For each query rectangle output its beauty degree on a separate line.
standard output
PASSED
d4001ee037e599d51a151fa225d75a94
train_002.jsonl
1504702500
Ilya is sitting in a waiting area of Metropolis airport and is bored of looking at time table that shows again and again that his plane is delayed. So he took out a sheet of paper and decided to solve some problems.First Ilya has drawn a grid of size n × n and marked n squares on it, such that no two marked squares share the same row or the same column. He calls a rectangle on a grid with sides parallel to grid sides beautiful if exactly two of its corner squares are marked. There are exactly nΒ·(n - 1) / 2 beautiful rectangles.Ilya has chosen q query rectangles on a grid with sides parallel to grid sides (not necessarily beautiful ones), and for each of those rectangles he wants to find its beauty degree. Beauty degree of a rectangle is the number of beautiful rectangles that share at least one square with the given one.Now Ilya thinks that he might not have enough time to solve the problem till the departure of his flight. You are given the description of marked cells and the query rectangles, help Ilya find the beauty degree of each of the query rectangles.
512 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Boredom { InputStream in; PrintWriter out; long tree[]; int left[],right[]; int root[]; int MAX=(int)2e5+7; int MAXN=25*((int)1e6); int nnode=1; void solve() { int n=ni(); int q=ni(); tree = new long[MAXN]; left = new int[MAXN]; right = new int[MAXN]; root = new int[MAX]; int p[]=new int[n+1]; for (int i=1;i<=n;i++) p[i]=ni(); root[0]=0; for (int i=1;i<=n;i++) root[i]=build(root[i-1],1, n, p[i], 1); while (q-->0){ int l,r,d,u; l=ni();d=ni();r=ni();u=ni(); long r1,r2,r3,r4,r5,r6,r7,r8,r9; //left side r1=Query(l-1,0, 0, d-1, n); r2=Query(l-1,0, d, u, n); r3=l-1-r1-r2; //centre side r4=Query(r, l-1, 0, d-1, n); r5=Query(r, l-1, d, u, n); r6=r-l+1-r4-r5; //right side r7=Query(n, r, 0, d-1, n); r8=Query(n, r, d, u, n); r9=n-r-r7-r8; //tr(r1+" "+r2+" "+r3+" "+r4+" "+r5+" "+r6+" "+r7+" "+r8+" "+r9); long val1,val2,val3,val4,val5,val6,val7,val8,val9; val1=r1*(r5+r8+r6+r9); val2=r2*(n-r1-r3-r2); val3=r3*(r4+r5+r7+r8); val7=r7*(r5+r6+r2+r3); val8=r8*(n-r7-r9-r8); val9=r9*(r4+r5+r1+r2); val4=r4*(n-r1-r7-r4); val5=r5*(n-r5)+(r5*(r5-1)); val6=r6*(n-r3-r9-r6); //tr(val1+" "+val2+" "+val3+" "+val4+" "+val5+" "+val6+" "+val7+" "+val8+" "+val9); long ans=(val1+val2+val3+val4+val5+val6+val7+val8+val9)/2L; out.println(ans); } } class Node { int left,right; long value; Node () { left=right=-1; value=0; } } long query(int s1,int l,int r,int start,int end) { if (s1==-1||start > r || end < l || start > end) return 0; if (start >= l && end <= r) return tree[s1]; int mid = ((start + end) >> 1); return query(left[s1],l,r ,start, mid)+query(right[s1],l,r ,mid + 1, end); } long Query(int r,int l,int d,int u,int n) { return query(root[r],d,u,1,n)-query(root[l],d,u,1,n); } int build(int v,int l,int r,int pos,int val) { int newid=nnode++; if (v != -1) { tree[newid] = tree[v]; left[newid] = left[v]; right[newid] = right[v]; } tree[newid] += val; if (l == r) return newid; int x = ((l + r)>>1); if (pos <= x) left[newid] = build(left[newid], l, x, pos, val); else right[newid] = build(right[newid], x + 1, r, pos, val); return newid; } 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 Boredom().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
["2 3\n1 2\n1 1 1 1\n1 1 1 2\n1 1 2 2", "4 2\n1 3 2 4\n4 1 4 4\n1 1 2 3"]
2 seconds
["1\n1\n1", "3\n5"]
NoteThe first sample test has one beautiful rectangle that occupies the whole grid, therefore the answer to any query is 1.In the second sample test the first query rectangle intersects 3 beautiful rectangles, as shown on the picture below: There are 5 beautiful rectangles that intersect the second query rectangle, as shown on the following picture:
Java 8
standard input
[ "data structures" ]
bc834c0aa602a8ba789b676affb0b33a
The first line of input contains two integers n and q (2 ≀ n ≀ 200 000, 1 ≀ q ≀ 200 000)Β β€” the size of the grid and the number of query rectangles. The second line contains n integers p1, p2, ..., pn, separated by spaces (1 ≀ pi ≀ n, all pi are different), they specify grid squares marked by Ilya: in column i he has marked a square at row pi, rows are numbered from 1 to n, bottom to top, columns are numbered from 1 to n, left to right. The following q lines describe query rectangles. Each rectangle is described by four integers: l, d, r, u (1 ≀ l ≀ r ≀ n, 1 ≀ d ≀ u ≀ n), here l and r are the leftmost and the rightmost columns of the rectangle, d and u the bottommost and the topmost rows of the rectangle.
2,100
For each query rectangle output its beauty degree on a separate line.
standard output
PASSED
65987494e6576704c2a2ae899572fe9b
train_002.jsonl
1504702500
Ilya is sitting in a waiting area of Metropolis airport and is bored of looking at time table that shows again and again that his plane is delayed. So he took out a sheet of paper and decided to solve some problems.First Ilya has drawn a grid of size n × n and marked n squares on it, such that no two marked squares share the same row or the same column. He calls a rectangle on a grid with sides parallel to grid sides beautiful if exactly two of its corner squares are marked. There are exactly nΒ·(n - 1) / 2 beautiful rectangles.Ilya has chosen q query rectangles on a grid with sides parallel to grid sides (not necessarily beautiful ones), and for each of those rectangles he wants to find its beauty degree. Beauty degree of a rectangle is the number of beautiful rectangles that share at least one square with the given one.Now Ilya thinks that he might not have enough time to solve the problem till the departure of his flight. You are given the description of marked cells and the query rectangles, help Ilya find the beauty degree of each of the query rectangles.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Egor Kulikov (egor@egork.net) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int q = in.readInt(); int[] p = IOUtils.readIntArray(in, n); int[] l = new int[q]; int[] d = new int[q]; int[] r = new int[q]; int[] u = new int[q]; IOUtils.readIntArrays(in, l, d, r, u); MiscUtils.decreaseByOne(l, d); int[] firstL = ArrayUtils.createArray(n + 1, -1); int[] nextL = new int[q]; int[] firstR = ArrayUtils.createArray(n + 1, -1); int[] nextR = new int[q]; for (int i = 0; i < q; i++) { nextL[i] = firstL[l[i]]; firstL[l[i]] = i; nextR[i] = firstR[r[i]]; firstR[r[i]] = i; } FenwickTree tree = new FenwickTree(n + 1); long[][] values = new long[q][9]; for (int i = 0; i <= n; i++) { for (int j = firstL[i]; j != -1; j = nextL[j]) { values[j][0] = tree.get(1, d[j]); values[j][3] = tree.get(d[j] + 1, u[j]); values[j][6] = tree.get(u[j] + 1, n); } for (int j = firstR[i]; j != -1; j = nextR[j]) { values[j][1] = tree.get(1, d[j]) - values[j][0]; values[j][4] = tree.get(d[j] + 1, u[j]) - values[j][3]; values[j][7] = tree.get(u[j] + 1, n) - values[j][6]; } if (i < n) { tree.add(p[i], 1); } } for (int i = 0; i < q; i++) { values[i][2] = tree.get(1, d[i]) - values[i][0] - values[i][1]; values[i][5] = tree.get(d[i] + 1, u[i]) - values[i][3] - values[i][4]; values[i][8] = tree.get(u[i] + 1, n) - values[i][6] - values[i][7]; long aa = values[i][0]; long bb = values[i][1]; long cc = values[i][2]; long dd = values[i][3]; long ee = values[i][4]; long ff = values[i][5]; long gg = values[i][6]; long hh = values[i][7]; long ii = values[i][8]; out.printLine(aa * (ee + ff + hh + ii) + bb * (dd + ee + ff + gg + hh + ii) + cc * (dd + ee + gg + hh) + dd * (ee + ff + hh + ii) + ee * (ff + gg + hh + ii) + ff * (gg + hh) + ee * (ee - 1) / 2); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class FenwickTree { private final long[] value; public FenwickTree(int size) { value = new long[size]; } public long get(int from, int to) { if (from > to) { return 0; } return get(to) - get(from - 1); } private long get(int to) { to = Math.min(to, value.length - 1); long result = 0; while (to >= 0) { result += value[to]; to = (to & (to + 1)) - 1; } return result; } public void add(int at, long value) { while (at < this.value.length) { this.value[at] += value; at = at | (at + 1); } } } static class MiscUtils { public static void decreaseByOne(int[]... arrays) { for (int[] array : arrays) { for (int i = 0; i < array.length; i++) { array[i]--; } } } } static 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; } public static void readIntArrays(InputReader in, int[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = in.readInt(); } } } } 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(long i) { writer.println(i); } } static class ArrayUtils { public static int[] createArray(int count, int value) { int[] array = new int[count]; Arrays.fill(array, value); return array; } } }
Java
["2 3\n1 2\n1 1 1 1\n1 1 1 2\n1 1 2 2", "4 2\n1 3 2 4\n4 1 4 4\n1 1 2 3"]
2 seconds
["1\n1\n1", "3\n5"]
NoteThe first sample test has one beautiful rectangle that occupies the whole grid, therefore the answer to any query is 1.In the second sample test the first query rectangle intersects 3 beautiful rectangles, as shown on the picture below: There are 5 beautiful rectangles that intersect the second query rectangle, as shown on the following picture:
Java 8
standard input
[ "data structures" ]
bc834c0aa602a8ba789b676affb0b33a
The first line of input contains two integers n and q (2 ≀ n ≀ 200 000, 1 ≀ q ≀ 200 000)Β β€” the size of the grid and the number of query rectangles. The second line contains n integers p1, p2, ..., pn, separated by spaces (1 ≀ pi ≀ n, all pi are different), they specify grid squares marked by Ilya: in column i he has marked a square at row pi, rows are numbered from 1 to n, bottom to top, columns are numbered from 1 to n, left to right. The following q lines describe query rectangles. Each rectangle is described by four integers: l, d, r, u (1 ≀ l ≀ r ≀ n, 1 ≀ d ≀ u ≀ n), here l and r are the leftmost and the rightmost columns of the rectangle, d and u the bottommost and the topmost rows of the rectangle.
2,100
For each query rectangle output its beauty degree on a separate line.
standard output