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
60d0a89eafadd9a39b6e52be159a3f59
train_003.jsonl
1520696100
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο€ such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pradyumn */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int[] P = in.nextIntArray(n); TrieBinary trieBinary = new TrieBinary(31); for (int pp : P) trieBinary.add(pp); int[] ans = new int[n]; for (int i = 0; i < n; ++i) { ans[i] = trieBinary.xorMin(a[i]); trieBinary.remove(ans[i]); ans[i] ^= a[i]; } ArrayUtils.printArray(out, ans); } } static class ArrayUtils { public static void fill(int[][] array, int value) { for (int[] row : array) { Arrays.fill(row, value); } } public static void printArray(PrintWriter out, int[] array) { if (array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i != 0) out.print(" "); out.print(array[i]); } out.println(); } } static class TrieBinary { int MAX; int[][] next; int[] count; int states = 1; int BIT; public TrieBinary(int bitCount) { this.BIT = bitCount; MAX = bitCount * 1000000 + 1; next = new int[2][MAX]; count = new int[MAX]; ArrayUtils.fill(next, -1); } public void add(int num) { int cur = 0; ++count[cur]; for (int bit = BIT - 1; bit >= 0; --bit) { int c = (num >> bit) & 1; if (next[c][cur] == -1) { next[c][cur] = states++; } cur = next[c][cur]; ++count[cur]; } } public boolean search(int num) { int cur = 0; for (int bit = BIT - 1; bit >= 0; --bit) { int c = (num >> bit) & 1; if (next[c][cur] == -1 || (next[c][cur] != -1 && count[next[c][cur]] == 0)) { return false; } cur = next[c][cur]; } return true; } public int xorMin(int num) { int cur = 0; int value = 0; for (int bit = BIT - 1; bit >= 0; --bit) { int c = (num >> bit) & 1; if (next[c][cur] != -1 && count[next[c][cur]] > 0) { } else { c ^= 1; } cur = next[c][cur]; value = (value << 1) | c; } return value; } public boolean remove(int num) { if (!search(num)) return false; int cur = 0; --count[cur]; for (int bit = BIT - 1; bit >= 0; --bit) { int c = (num >> bit) & 1; cur = next[c][cur]; --count[cur]; } return true; } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"]
3.5 seconds
["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"]
NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Java 8
standard input
[ "data structures", "greedy", "trees", "strings" ]
dc778193a126009f545d1d6f307bba83
The first line contains a single integer N (1 ≀ N ≀ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≀ Ai &lt; 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≀ Pi &lt; 230) representing the permuted encryption key.
1,800
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
standard output
PASSED
0b04f9eb6615269fcde0224e1bf8207b
train_003.jsonl
1520696100
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο€ such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si &lt; Ti and for all j &lt; i the condition Sj = Tj holds.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pradyumn */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int[] p = in.nextIntArray(n); int MAX = 30 * 300000 + 1; int[][] next = new int[2][MAX]; int[] count = new int[MAX]; int states = 1; ArrayUtils.fill(next, -1); for (int i = 0; i < n; ++i) { int cur = 0; ++count[cur]; for (int bit = 29; bit >= 0; --bit) { int c = (p[i] >> bit) & 1; if (next[c][cur] == -1) { next[c][cur] = states++; } cur = next[c][cur]; ++count[cur]; } } int[] ans = new int[n]; for (int i = 0; i < n; ++i) { int cur = 0; int value = 0; --count[cur]; for (int bit = 29; bit >= 0; --bit) { int c = (a[i] >> bit) & 1; if (next[c][cur] != -1 && count[next[c][cur]] > 0) { } else { c ^= 1; } cur = next[c][cur]; --count[cur]; value = (value << 1) | c; } ans[i] = a[i] ^ value; } ArrayUtils.printArray(out, ans); } } static class ArrayUtils { public static void fill(int[][] array, int value) { for (int[] row : array) { Arrays.fill(row, value); } } public static void printArray(PrintWriter out, int[] array) { if (array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i != 0) out.print(" "); out.print(array[i]); } out.println(); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"]
3.5 seconds
["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"]
NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Java 8
standard input
[ "data structures", "greedy", "trees", "strings" ]
dc778193a126009f545d1d6f307bba83
The first line contains a single integer N (1 ≀ N ≀ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≀ Ai &lt; 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≀ Pi &lt; 230) representing the permuted encryption key.
1,800
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
standard output
PASSED
82aeb65d333bd4e2c8767d6169201d0d
train_003.jsonl
1520696100
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο€ such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si &lt; Ti and for all j &lt; i the condition Sj = Tj holds.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pradyumn */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int[] P = in.nextIntArray(n); TaskC.Trie trie = new TaskC.Trie(P); int[] ans = new int[n]; for (int i = 0; i < n; ++i) ans[i] = trie.xorMin(a[i]); ArrayUtils.printArray(out, ans); } static class Trie { int MAX = 30 * 300000 + 1; int[][] next; int[] count; int states = 1; public Trie(int[] a) { next = new int[2][MAX]; count = new int[MAX]; ArrayUtils.fill(next, -1); for (int aa : a) insert(aa); } public void insert(int num) { int cur = 0; ++count[cur]; for (int bit = 29; bit >= 0; --bit) { int c = (num >> bit) & 1; if (next[c][cur] == -1) { next[c][cur] = states++; } cur = next[c][cur]; ++count[cur]; } } public int xorMin(int num) { int cur = 0; --count[cur]; int value = 0; for (int bit = 29; bit >= 0; --bit) { int c = (num >> bit) & 1; if (next[c][cur] != -1 && count[next[c][cur]] > 0) { } else { c ^= 1; } cur = next[c][cur]; --count[cur]; value = (value << 1) | c; } return value ^ num; } } } static class ArrayUtils { public static void fill(int[][] array, int value) { for (int[] row : array) { Arrays.fill(row, value); } } public static void printArray(PrintWriter out, int[] array) { if (array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i != 0) out.print(" "); out.print(array[i]); } out.println(); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"]
3.5 seconds
["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"]
NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Java 8
standard input
[ "data structures", "greedy", "trees", "strings" ]
dc778193a126009f545d1d6f307bba83
The first line contains a single integer N (1 ≀ N ≀ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≀ Ai &lt; 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≀ Pi &lt; 230) representing the permuted encryption key.
1,800
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
standard output
PASSED
e4bf6ffc03452dbd7da270aa14a9f769
train_003.jsonl
1520696100
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο€ such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si &lt; Ti and for all j &lt; i the condition Sj = Tj holds.
512 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader reader = null; static StringTokenizer tokenizer = null; static PrintWriter writer = null; static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } static double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } static long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); banana(); reader.close(); writer.close(); } static Node getNode(int value) { Node curr = root; for (int j = 29; j >= 0; j--) { boolean bit = (((1 << j) & value) == (1 << j)); if (bit) { // right if ((curr.right != null) && (curr.right.size != 0)) { curr = curr.right; } else { curr = curr.left; } } else { // left if ((curr.left != null) && (curr.left.size != 0)) { curr = curr.left; } else { curr = curr.right; } } } curr.size--; curr.parent.updateSize(); return curr; } static void addNode(int value) { Node curr = root; for (int j = 29; j >= 0; j--) { boolean bit = (((1 << j) & value) == (1 << j)); if (bit) { // right if (curr.right == null) { curr.right = new Node(curr); } curr = curr.right; } else { // left if (curr.left == null) { curr.left = new Node(curr); } curr = curr.left; } } curr.value = value; curr.size++; curr.parent.updateSize(); } static Node root = new Node(null); static void banana() throws NumberFormatException, IOException { int n = nextInt(); int[] a = new int[n]; int[] p = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } for (int i = 0; i < n; i++) { p[i] = nextInt(); addNode(p[i]); } for (int i = 0; i < n; i++) { Node node = getNode(a[i]); // System.err.print(node.value + " "); writer.print((node.value ^ a[i]) + " "); } } static class Node { int value; int size; Node parent; Node left; Node right; public Node(Node parent) { this.parent = parent; } void updateSize() { int oldSize = size; size = 0; if (left != null) { size += left.size; } if (right != null) { size += right.size; } if (parent != null && size != oldSize) { parent.updateSize(); } } } }
Java
["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"]
3.5 seconds
["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"]
NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Java 8
standard input
[ "data structures", "greedy", "trees", "strings" ]
dc778193a126009f545d1d6f307bba83
The first line contains a single integer N (1 ≀ N ≀ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≀ Ai &lt; 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≀ Pi &lt; 230) representing the permuted encryption key.
1,800
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
standard output
PASSED
a0a5592427dd004f8901afa959f00d80
train_003.jsonl
1520696100
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο€ such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si &lt; Ti and for all j &lt; i the condition Sj = Tj holds.
512 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.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; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int MAX = 30 * 300_000 + 1; int[][] next = new int[2][MAX]; int[] count = new int[MAX]; int states = 1; public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int[] p = in.nextIntArray(n); for (int[] i : next) { Arrays.fill(i, -1); } for (int i = 0; i < n; i++) { int cur = 0; count[cur]++; for (int bit = 29; bit >= 0; bit--) { int c = (p[i] >> bit) & 1; if (next[c][cur] == -1) { next[c][cur] = states++; } cur = next[c][cur]; count[cur]++; } } for (int i = 0; i < n; i++) { int cur = 0; int value = 0; count[cur]--; for (int bit = 29; bit >= 0; bit--) { int c = (a[i] >> bit) & 1; if (next[c][cur] != -1 && count[next[c][cur]] > 0) { } else { c ^= 1; } cur = next[c][cur]; count[cur]--; value = (value << 1) | c; } out.print((a[i] ^ value)); out.print(' '); } } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (st == null || !st.hasMoreElements()) { String line = null; try { line = br.readLine(); } catch (IOException e) { } st = new StringTokenizer(line); } return st.nextToken(); } public int[] nextIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } }
Java
["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"]
3.5 seconds
["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"]
NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Java 8
standard input
[ "data structures", "greedy", "trees", "strings" ]
dc778193a126009f545d1d6f307bba83
The first line contains a single integer N (1 ≀ N ≀ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≀ Ai &lt; 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≀ Pi &lt; 230) representing the permuted encryption key.
1,800
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
standard output
PASSED
a90221f52215d41f95ffe3e89c2f784b
train_003.jsonl
1520696100
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο€ such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si &lt; Ti and for all j &lt; i the condition Sj = Tj holds.
512 megabytes
//package com.company; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { MyScanner sc = new MyScanner(System.in); PrintWriter pw = new PrintWriter(System.out); long start = System.currentTimeMillis(); Task t = new Task(); t.solve(sc, pw); long end = System.currentTimeMillis(); // pw.println("Used time " + (end - start) + "ms."); pw.close(); } public static class Task { public class Node { int childc[]; Node child[]; int cnt; Node(){ child = new Node[2]; childc = new int[2]; cnt = 0; } } Node[] lvNodes; public void addNode(int x){ char[] crr = Integer.toBinaryString(x).toCharArray(); int length = crr.length; Node head = lvNodes[length]; for (int i = 0; i < length; i++) { int dir = crr[i] - '0'; if (head.childc[dir] == 0) { head.child[dir] = new Node(); } head.cnt++; head.childc[dir]++; head = head.child[dir]; } head.cnt++; } public int traverse(char[] arr, int start, Node move) { int res = 0; for (int i = start; i < arr.length; i++) { int dir; if (i < 0) { dir = 0; } else { dir = arr[i] - '0'; } if (move.childc[dir] != 0) { move.cnt--; move.childc[dir]--; move = move.child[dir]; res = res * 2 + dir; } else if (move.childc[dir ^1] != 0) { move.cnt--; move.childc[dir^1]--; move = move.child[dir^1]; res = res * 2 + (dir ^ 1); } else { if (i != start) { throw new RuntimeException(); } return -1; } } move.cnt--; return res; } public int findBest(int x) { char[] crr = Integer.toBinaryString(x).toCharArray(); int length = crr.length; int c = traverse(crr, 0, lvNodes[length]); if (c != -1) { return x ^ c; } else { for (int i = 0; i < length; i++) { if (crr[i] == '1') { c = traverse(crr, i, lvNodes[length - i]); if (c != -1) { return x ^ c; } } } for (int i = 1; i < lvNodes.length; i++) { if (i == 28){ int t = 4; } c = traverse(crr, length - i, lvNodes[i]); if (c != -1) { return x ^ c; } } } return -1; } public void solve(MyScanner sc, PrintWriter pw) throws IOException { lvNodes = new Node[33]; for (int i = 0; i < lvNodes.length; i++) { lvNodes[i] = new Node(); } int n = sc.nextInt(); int[] arr = new int[n]; int[] qrr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { qrr[i] = sc.nextInt(); addNode(qrr[i]); } // for (int i = 0; i < n; i++) { // if ((arr[4] ^ qrr[i]) == 223689619){ // System.out.println(Integer.toBinaryString(qrr[i])); // System.out.println(Integer.toBinaryString(arr[4])); // } // } for (int i = 0; i < n; i++) { qrr[i] = findBest(arr[i]); } for (int i = 0; i < n; i++) { pw.print(qrr[i] + " "); } pw.println(); } } static class MyScanner { StringTokenizer st; BufferedReader br; public MyScanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public MyScanner(FileReader s) throws FileNotFoundException {br = new BufferedReader(s);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"]
3.5 seconds
["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"]
NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Java 8
standard input
[ "data structures", "greedy", "trees", "strings" ]
dc778193a126009f545d1d6f307bba83
The first line contains a single integer N (1 ≀ N ≀ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≀ Ai &lt; 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≀ Pi &lt; 230) representing the permuted encryption key.
1,800
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
standard output
PASSED
ce0edcf8133e507ab4f1c947ed318055
train_003.jsonl
1520696100
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο€ such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si &lt; Ti and for all j &lt; i the condition Sj = Tj holds.
512 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; /* public class _948C { } */ public class _948C { class trie { class node { int subsz; node left; node right; /** * @param subsz * @param left * @param right */ public node(int subsz, node left, node right) { super(); this.subsz = subsz; this.left = left; this.right = right; } } node root = new node(0, null, null); void insert(int num) { node cn = root; cn.subsz++; for (int i = 0; i < 30; i++) { int ci = (num & (1 << (29 - i))); if (ci == 0) { if (cn.left == null) { cn.left = new node(0, null, null); } cn = cn.left; } else { if (cn.right == null) { cn.right = new node(0, null, null); } cn = cn.right; } cn.subsz++; } } int search(int num) { node cn = root; int fn = 0; int i; for (i = 0; i < 30; i++) { int ci = (num & (1 << (29 - i))); if (ci == 0) { if (cn.left != null && cn.left.subsz > 0) { cn = cn.left; } else { cn = cn.right; fn += (1 << (29 - i)); } } else { if (cn.right != null && cn.right.subsz > 0) { cn = cn.right; fn += (1 << (29 - i)); } else { cn = cn.left; } } if (cn == null) break; } i++; for (; i < 30; i++) { int ci = (num & (1 << (29 - i))); if (ci != 0) { fn += (1 << (29 - i)); } } return fn; } void delete(int num) { node cn = root; cn.subsz--; for (int i = 0; i < 30; i++) { int ci = (num & (1 << (29 - i))); if (ci == 0) { cn = cn.left; } else { cn = cn.right; } cn.subsz--; } } } public void solve() throws FileNotFoundException { InputStream inputStream = System.in; InputHelper in = new InputHelper(inputStream); // actual solution int n = in.readInteger(); int[] a = new int[n]; int[] p = new int[n]; trie trie = new trie(); for (int i = 0; i < n; i++) { a[i] = in.readInteger(); } StringBuilder ans = new StringBuilder(); for (int i = 0; i < n; i++) { p[i] = in.readInteger(); trie.insert(p[i]); } for (int i = 0; i < n; i++) { int sn = trie.search(a[i]); trie.delete(sn); ans.append(a[i] ^ sn); ans.append(" "); } System.out.println(ans.toString()); // end here } public static void main(String[] args) throws FileNotFoundException { (new _948C()).solve(); } class InputHelper { StringTokenizer tokenizer = null; private BufferedReader bufferedReader; public InputHelper(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader, 16384); } public String read() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = bufferedReader.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public Integer readInteger() { return Integer.parseInt(read()); } public Long readLong() { return Long.parseLong(read()); } } }
Java
["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"]
3.5 seconds
["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"]
NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Java 8
standard input
[ "data structures", "greedy", "trees", "strings" ]
dc778193a126009f545d1d6f307bba83
The first line contains a single integer N (1 ≀ N ≀ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≀ Ai &lt; 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≀ Pi &lt; 230) representing the permuted encryption key.
1,800
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
standard output
PASSED
375ea66e260b321c8e26b87c4b770f9a
train_003.jsonl
1520696100
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο€ such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si &lt; Ti and for all j &lt; i the condition Sj = Tj holds.
512 megabytes
//package round470; 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 C { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); int[] P = na(n); TrieArrayBinary trie = new TrieArrayBinary(31); for(int v : P)trie.add(v); for(int v : a){ long ret = trie.xormin(v); out.print(ret + " "); trie.remove(ret^v); } } public static class L { public int[] a; public int p = 0; public L(int n) { a = new int[n]; } public L add(int n) { if(p >= a.length)a = Arrays.copyOf(a, a.length*3/2+1); a[p++] = n; return this; } public int size() { return p; } public L clear() { p = 0; return this; } public int[] toArray() { return Arrays.copyOf(a, p); } @Override public String toString() {return Arrays.toString(toArray());} } public static class TrieArrayBinary { // root = 0 public L next; public int gen; public int W; public L hit; public TrieArrayBinary(int W) { this.W = W; this.next = new L(2); this.hit = new L(1); this.gen = 1; this.next.add(-1).add(-1); this.hit.add(0); } public void add(long s) { int cur = 0; for(int d = W-1;d >= 0;d--){ int v = (int)(s>>>d&1); int nex = next.a[cur*2+v]; if(nex == -1){ nex = next.a[cur*2+v] = gen++; next.add(-1).add(-1); hit.add(0); } cur = nex; } hit.a[cur]++; } public void remove(long s) { int cur = 0; int[] hist = new int[W]; for(int d = W-1;d >= 0;d--){ hist[d] = cur; int v = (int)(s>>>d&1); int nex = next.a[cur*2+v]; if(nex == -1){ throw new RuntimeException(); } cur = nex; } if(--hit.a[cur] == 0){ for(int d = 0;d < W;d++){ int v = (int)(s>>>d&1); next.a[hist[d]*2|v] = -1; if(next.a[hist[d]*2|v^1] != -1)break; } } } public long xormin(long x) { int cur = 0; long ret = 0; for(int d = W-1;d >= 0;d--){ if(cur == -1){ ret |= x<<-d>>>-d; break; } int xd = (int)(x>>>d&1); if(next.a[cur*2|xd] != -1){ cur = next.a[cur*2|xd]; }else{ ret |= 1L<<d; cur = next.a[cur*2|xd^1]; } } return ret; } public int[] des() { int[] des = new int[gen]; for(int i = gen-1;i >= 0;i--){ if(next.a[2*i] != -1)des[i] += des[next.a[2*i]]; if(next.a[2*i+1] != -1)des[i] += des[next.a[2*i+1]]; if(des[i] == 0)des[i] = 1; } return des; } public int mex(long x, int[] des) { int ret = 0; for(int cur = 0, d = W-1;d >= 0 && cur != -1;d--){ int xd = (int)(x>>>d&1); if(next.a[2*cur|xd] != -1 && des[next.a[2*cur|xd]] == 1<<d){ ret |= 1<<d; cur = next.a[2*cur|xd^1]; }else{ cur = next.a[2*cur|xd]; } } return ret; } public boolean contains(long x, int low) { int cur = 0; for(int d = W-1;d >= low;d--){ int v = (int)(x>>>d&1); int nex = next.a[cur*2+v]; if(nex == -1)return false; } return true; } } 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 C().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
["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"]
3.5 seconds
["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"]
NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Java 8
standard input
[ "data structures", "greedy", "trees", "strings" ]
dc778193a126009f545d1d6f307bba83
The first line contains a single integer N (1 ≀ N ≀ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≀ Ai &lt; 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≀ Pi &lt; 230) representing the permuted encryption key.
1,800
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
standard output
PASSED
d9a936b342b332c92ad366f2daf2ef95
train_003.jsonl
1520696100
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο€ such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si &lt; Ti and for all j &lt; i the condition Sj = Tj holds.
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 */ 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 { static final int MAXNODES = 30 * 300000 + 101; static final int MAXB = 29; int[] count; int[][] next; int cidx; int create() { return cidx++; } void insert(int num) { int cur = 0; for (int bit = MAXB; bit >= 0; bit--) { count[cur]++; int c = (num >> bit) & 1; if (next[cur][c] == -1) next[cur][c] = create(); cur = next[cur][c]; } count[cur]++; } int query(int num) { int cur = 0; int res = 0; for (int bit = MAXB; bit >= 0; bit--) { count[cur]--; int c = (num >> bit) & 1; int want = c; if (next[cur][want] == -1 || count[next[cur][want]] == 0) { want = 1 ^ want; res += 1 << bit; } cur = next[cur][want]; } count[cur]--; return res; } public void solve(int testNumber, InputReader in, OutputWriter out) { count = new int[MAXNODES]; next = new int[MAXNODES][2]; AUtils.deepFill(next, -1); create(); int n = in.nextInt(); int[] arr = in.readIntArray(n); for (int i = 0; i < n; i++) { insert(in.nextInt()); } for (int i = 0; i < n; i++) { out.println(query(arr[i])); } } } static class AUtils { public static void deepFill(int[][] x, int val) { for (int[] y : x) deepFill(y, val); } public static void deepFill(int[] x, int val) { Arrays.fill(x, val); } } 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 println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int tokens) { int[] ret = new int[tokens]; for (int i = 0; i < tokens; i++) { ret[i] = nextInt(); } return ret; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } }
Java
["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"]
3.5 seconds
["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"]
NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Java 8
standard input
[ "data structures", "greedy", "trees", "strings" ]
dc778193a126009f545d1d6f307bba83
The first line contains a single integer N (1 ≀ N ≀ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≀ Ai &lt; 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≀ Pi &lt; 230) representing the permuted encryption key.
1,800
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
standard output
PASSED
d86449f10da499b1db2dfafaf3e61633
train_003.jsonl
1520696100
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο€ such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si &lt; Ti and for all j &lt; i the condition Sj = Tj holds.
512 megabytes
import java.io.*; import java.math.*; import java.util.*; public class C { static final int LOG = 30; int[][] to; int[] cnt; int sz; int newNode() { to[0][sz] = to[1][sz] = -1; return sz++; } void submit() { int n = nextInt(); int[] a = new int[n]; int[] p = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } for (int i = 0; i < n; i++) { p[i] = nextInt(); } to = new int[2][n * (LOG + 1)]; cnt = new int[n * (LOG + 1)]; int root = newNode(); for (int x : p) { insert(x); } for (int x : a) { int node = 0; int outp = 0; for (int bit = LOG - 1; bit >= 0; bit--) { cnt[node]--; int v = (x >> bit) & 1; int fst = to[v][node]; if (fst == -1 || cnt[fst] == 0) { node = to[v ^ 1][node]; outp |= (1 << bit); } else { node = fst; } } cnt[node]--; out.print(outp + " "); } } void insert(int x) { int node = 0; for (int bit = LOG - 1; bit >= 0; bit--) { cnt[node]++; int v = (x >> bit) & 1; if (to[v][node] == -1) { to[v][node] = newNode(); } node = to[v][node]; } cnt[node]++; } void preCalc() { } void test() { } void stress() { for (int tst = 0;; tst++) { if (false) { throw new AssertionError(); } System.err.println(tst); } } C() throws IOException { is = System.in; out = new PrintWriter(System.out); preCalc(); submit(); // stress(); // test(); out.close(); } static final Random rng = new Random(); static final int C = 5; static int rand(int l, int r) { return l + rng.nextInt(r - l + 1); } public static void main(String[] args) throws IOException { new C(); } private InputStream is; PrintWriter out; private byte[] buf = new byte[1 << 14]; private int bufSz = 0, bufPtr = 0; private int readByte() { if (bufSz == -1) throw new RuntimeException("Reading past EOF"); if (bufPtr >= bufSz) { bufPtr = 0; try { bufSz = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufSz <= 0) return -1; } return buf[bufPtr++]; } private boolean isTrash(int c) { return c < 33 || c > 126; } private int skip() { int b; while ((b = readByte()) != -1 && isTrash(b)) ; return b; } String nextToken() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!isTrash(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextString() { int b = readByte(); StringBuilder sb = new StringBuilder(); while (!isTrash(b) || b == ' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } double nextDouble() { return Double.parseDouble(nextToken()); } char nextChar() { return (char) skip(); } int nextInt() { int ret = 0; int b = skip(); if (b != '-' && (b < '0' || b > '9')) { throw new InputMismatchException(); } boolean neg = false; if (b == '-') { neg = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); } return neg ? -ret : ret; } b = readByte(); } } long nextLong() { long ret = 0; int b = skip(); if (b != '-' && (b < '0' || b > '9')) { throw new InputMismatchException(); } boolean neg = false; if (b == '-') { neg = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); } return neg ? -ret : ret; } b = readByte(); } } }
Java
["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"]
3.5 seconds
["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"]
NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Java 8
standard input
[ "data structures", "greedy", "trees", "strings" ]
dc778193a126009f545d1d6f307bba83
The first line contains a single integer N (1 ≀ N ≀ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≀ Ai &lt; 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≀ Pi &lt; 230) representing the permuted encryption key.
1,800
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
standard output
PASSED
afdc72539da6c7fde7e09e767582266c
train_003.jsonl
1520696100
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο€ such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si &lt; Ti and for all j &lt; i the condition Sj = Tj holds.
512 megabytes
import java.awt.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; import java.util.Queue; import static java.lang.Math.max; import static java.lang.Math.min; public class C implements Runnable{ // SOLUTION AT THE TOP OF CODE!!! // HACK ME PLEASE IF YOU CAN!!! // PLEASE!!! // PLEASE!!! // PLEASE!!! private final static boolean FIRST_INPUT_STRING = false; private final static boolean MULTIPLE_TESTS = true; private final boolean ONLINE_JUDGE = !new File("input.txt").exists(); // private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private final static int MAX_STACK_SIZE = 128; private final static boolean OPTIMIZE_READ_NUMBERS = false; ///////////////////////////////////////////////////////////////////// private final static Random rnd = new Random(); private final static String fileName = ""; private final static long MODULO = 1000 * 1000 * 1000 + 7; // THERE SOLUTION STARTS!!! private void solve() { int n = readInt(); int[] a = readIntArray(n); int[] p = readIntArray(n); RadixTree tree = new RadixTree(); for (int key : p) tree.add(key); for (int message : a) { int partner = tree.getMinXorPartner(message); tree.remove(partner); int xor = message ^ partner; out.print(xor + " "); } out.println(); } static class RadixTree { static class Node { Node left, right; int leftSize, rightSize; Node() { this.left = null; this.right = null; this.leftSize = 0; this.rightSize = 0; } Node getLeft() { if (left == null) left = new Node(); return left; } Node getRight() { if (right == null) right = new Node(); return right; } } Node root; RadixTree() { root = new Node(); } void add(int value) { update(value, 1); } void remove(int value) { update(value, -1); } void update(int value, int delta) { Node cur = root; for (int bit = 30; bit >= 0; --bit) { if (checkBit(value, bit)) { cur.rightSize += delta; cur = cur.getRight(); } else { cur.leftSize += delta; cur = cur.getLeft(); } } } int getMinXorPartner(int value) { Node cur = root; int result = 0; for (int bit = 30; bit >= 0; --bit) { if (checkBit(value, bit)) { if (cur.rightSize > 0) { result |= (1 << bit); cur = cur.right; } else { cur = cur.left; } } else { if (cur.leftSize > 0) { cur = cur.left; } else { result |= (1 << bit); cur = cur.right; } } } return result; } } ///////////////////////////////////////////////////////////////////// private static long add(long a, long b) { return (a + b) % MODULO; } private static long subtract(long a, long b) { return add(a, MODULO - b % MODULO); } private static long mult(long a, long b) { return (a * b) % MODULO; } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeInit(); Locale.setDefault(Locale.US); init(); if (ONLINE_JUDGE) { solve(); } else { do { try { timeInit(); solve(); time(); out.println(); out.flush(); } catch (NumberFormatException e) { break; } catch (NullPointerException e) { if (FIRST_INPUT_STRING) break; else throw e; } } while (MULTIPLE_TESTS); } out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// private BufferedReader in; private OutputWriter out; private StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new C(), "", MAX_STACK_SIZE * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// private void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new OutputWriter(fileName + ".out"); } }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// private long timeBegin; private void timeInit() { this.timeBegin = System.currentTimeMillis(); } private void time(){ long timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } private void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// private String delim = " "; private String readLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeIOException(e); } } private String readString() { try { while(!tok.hasMoreTokens()){ tok = new StringTokenizer(readLine(), delim); } return tok.nextToken(delim); } catch (NullPointerException e) { return null; } } ///////////////////////////////////////////////////////////////// private final char NOT_A_SYMBOL = '\0'; private char readChar() { try { int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } catch (IOException e) { throw new RuntimeIOException(e); } } private char[] readCharArray() { return readLine().toCharArray(); } private char[][] readCharField(int rowsCount) { char[][] field = new char[rowsCount][]; for (int row = 0; row < rowsCount; ++row) { field[row] = readCharArray(); } return field; } ///////////////////////////////////////////////////////////////// private long optimizedReadLong() { int sign = 1; long result = 0; boolean started = false; while (true) { try { int j = in.read(); if (-1 == j) { if (started) return sign * result; throw new NumberFormatException(); } if (j == '-') { if (started) throw new NumberFormatException(); sign = -sign; } if ('0' <= j && j <= '9') { result = result * 10 + j - '0'; started = true; } else if (started) { return sign * result; } } catch (IOException e) { throw new RuntimeIOException(e); } } } private int readInt() { if (!OPTIMIZE_READ_NUMBERS) { return Integer.parseInt(readString()); } else { return (int) optimizedReadLong(); } } private int[] readIntArray(int size) { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } private int[] readSortedIntArray(int size) { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } private int[] readIntArrayWithDecrease(int size) { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// private int[][] readIntMatrix(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// private long readLong() { if (!OPTIMIZE_READ_NUMBERS) { return Long.parseLong(readString()); } else { return optimizedReadLong(); } } private long[] readLongArray(int size) { long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// private double readDouble() { return Double.parseDouble(readString()); } private double[] readDoubleArray(int size) { double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// private BigInteger readBigInteger() { return new BigInteger(readString()); } private BigDecimal readBigDecimal() { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// private Point readPoint() { int x = readInt(); int y = readInt(); return new Point(x, y); } private Point[] readPointArray(int size) { Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// @Deprecated private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) { @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<Integer>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } private static class GraphBuilder { final int size; final List<Integer>[] edges; static GraphBuilder createInstance(int size) { List<Integer>[] edges = new List[size]; for (int v = 0; v < size; ++v) { edges[v] = new ArrayList<Integer>(); } return new GraphBuilder(edges); } private GraphBuilder(List<Integer>[] edges) { this.size = edges.length; this.edges = edges; } public void addEdge(int from, int to) { addDirectedEdge(from, to); addDirectedEdge(to, from); } public void addDirectedEdge(int from, int to) { edges[from].add(to); } public int[][] build() { int[][] graph = new int[size][]; for (int v = 0; v < size; ++v) { List<Integer> vEdges = edges[v]; graph[v] = castInt(vEdges); } return graph; } } private final static int ZERO_INDEXATION = 0, ONE_INDEXATION = 1; private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber) { return readUnweightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed ) { GraphBuilder graphBuilder = GraphBuilder.createInstance(vertexNumber); for (int i = 0; i < edgesNumber; ++i) { int from = readInt() - indexation; int to = readInt() - indexation; if (directed) graphBuilder.addDirectedEdge(from, to); else graphBuilder.addEdge(from, to); } return graphBuilder.build(); } private static class Edge { int to; int w; Edge(int to, int w) { this.to = to; this.w = w; } } private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber) { return readWeightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed) { @SuppressWarnings("unchecked") List<Edge>[] graph = new List[vertexNumber]; for (int v = 0; v < vertexNumber; ++v) { graph[v] = new ArrayList<Edge>(); } while (edgesNumber --> 0) { int from = readInt() - indexation; int to = readInt() - indexation; int w = readInt(); graph[from].add(new Edge(to, w)); if (!directed) graph[to].add(new Edge(from, w)); } Edge[][] graphArrays = new Edge[vertexNumber][]; for (int v = 0; v < vertexNumber; ++v) { graphArrays[v] = graph[v].toArray(new Edge[0]); } return graphArrays; } ///////////////////////////////////////////////////////////////////// private static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<C.IntIndexPair>() { @Override public int compare(C.IntIndexPair indexPair1, C.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<C.IntIndexPair>() { @Override public int compare(C.IntIndexPair indexPair1, C.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static IntIndexPair[] from(int[] array) { IntIndexPair[] iip = new IntIndexPair[array.length]; for (int i = 0; i < array.length; ++i) { iip[i] = new IntIndexPair(array[i], i); } return iip; } int value, index; IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } int getRealIndex() { return index + 1; } } private IntIndexPair[] readIntIndexArray(int size) { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// private static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; private int precision; private String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } OutputWriter(OutputStream out) { super(out); } OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } int getPrecision() { return precision; } void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } @Override public void println(double d){ print(d); println(); } void printWithSpace(double d){ printf(formatWithSpace, d); } void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } void printlnAll(double... d){ printAll(d); println(); } void printAll(int... array) { for (int value : array) { print(value + " "); } } void printlnAll(int... array) { printAll(array); println(); } void printAll(long... array) { for (long value : array) { print(value + " "); } } void printlnAll(long... array) { printAll(array); println(); } } ///////////////////////////////////////////////////////////////////// private static class RuntimeIOException extends RuntimeException { /** * */ private static final long serialVersionUID = -6463830523020118289L; RuntimeIOException(Throwable cause) { super(cause); } } ///////////////////////////////////////////////////////////////////// //////////////// Some useful constants andTo functions //////////////// ///////////////////////////////////////////////////////////////////// private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; private static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) { return checkIndex(row, rowsCount) && checkIndex(column, columnsCount); } private static boolean checkIndex(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// private static int getBit(long mask, int bit) { return (int)((mask >> bit) & 1); } private static boolean checkBit(long mask, int bit){ return getBit(mask, bit) != 0; } ///////////////////////////////////////////////////////////////////// private static long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } private static Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// private static boolean isPrime(int x) { if (x < 2) return false; for (int d = 2; d * d <= x; ++d) { if (x % d == 0) return false; } return true; } private static int[] getPrimes(int n) { boolean[] used = new boolean[n]; used[0] = used[1] = true; int size = 0; for (int i = 2; i < n; ++i) { if (!used[i]) { ++size; for (int j = 2 * i; j < n; j += i) { used[j] = true; } } } int[] primes = new int[size]; for (int i = 0, cur = 0; i < n; ++i) { if (!used[i]) { primes[cur++] = i; } } return primes; } ///////////////////////////////////////////////////////////////////// int[] getDivisors(int value) { List<Integer> divisors = new ArrayList<Integer>(); for (int divisor = 1; divisor * divisor <= value; ++divisor) { if (value % divisor == 0) { divisors.add(divisor); if (divisor * divisor != value) { divisors.add(value / divisor); } } } return castInt(divisors); } ///////////////////////////////////////////////////////////////////// private static long lcm(long a, long b) { return a / gcd(a, b) * b; } private static long gcd(long a, long b) { return (a == 0 ? b : gcd(b % a, a)); } ///////////////////////////////////////////////////////////////////// private interface MultiSet<ValueType> { int size(); void inc(ValueType value); boolean dec(ValueType value); int count(ValueType value); } private static abstract class MultiSetImpl <ValueType, MapType extends Map<ValueType, Integer>> implements MultiSet<ValueType> { protected final MapType map; protected int size; protected MultiSetImpl(MapType map) { this.map = map; this.size = 0; } public int size() { return size; } public void inc(ValueType value) { int count = count(value); map.put(value, count + 1); ++size; } public boolean dec(ValueType value) { int count = count(value); if (count == 0) return false; if (count == 1) map.remove(value); else map.put(value, count - 1); --size; return true; } public int count(ValueType value) { Integer count = map.get(value); return (count == null ? 0 : count); } } private static class HashMultiSet<ValueType> extends MultiSetImpl<ValueType, Map<ValueType, Integer>> { public static <ValueType> MultiSet<ValueType> createMultiSet() { Map<ValueType, Integer> map = new HashMap<ValueType, Integer>(); return new HashMultiSet<ValueType>(map); } HashMultiSet(Map<ValueType, Integer> map) { super(map); } } ///////////////////////////////////////////////////////////////////// private interface SortedMultiSet<ValueType> extends MultiSet<ValueType> { ValueType min(); ValueType max(); ValueType pollMin(); ValueType pollMax(); ValueType lower(ValueType value); ValueType floor(ValueType value); ValueType ceiling(ValueType value); ValueType higher(ValueType value); } private static abstract class SortedMultiSetImpl<ValueType> extends MultiSetImpl<ValueType, NavigableMap<ValueType, Integer>> implements SortedMultiSet<ValueType> { SortedMultiSetImpl(NavigableMap<ValueType, Integer> map) { super(map); } @Override public ValueType min() { return (size == 0 ? null : map.firstKey()); } @Override public ValueType max() { return (size == 0 ? null : map.lastKey()); } @Override public ValueType pollMin() { ValueType first = min(); if (first != null) dec(first); return first; } @Override public ValueType pollMax() { ValueType last = max(); dec(last); return last; } @Override public ValueType lower(ValueType value) { return map.lowerKey(value); } @Override public ValueType floor(ValueType value) { return map.floorKey(value); } @Override public ValueType ceiling(ValueType value) { return map.ceilingKey(value); } @Override public ValueType higher(ValueType value) { return map.higherKey(value); } } private static class TreeMultiSet<ValueType> extends SortedMultiSetImpl<ValueType> { public static <ValueType> SortedMultiSet<ValueType> createMultiSet() { NavigableMap<ValueType, Integer> map = new TreeMap<ValueType, Integer>(); return new TreeMultiSet<ValueType>(map); } TreeMultiSet(NavigableMap<ValueType, Integer> map) { super(map); } } ///////////////////////////////////////////////////////////////////// private static class IdMap<KeyType> extends HashMap<KeyType, Integer> { /** * */ private static final long serialVersionUID = -3793737771950984481L; public IdMap() { super(); } int register(KeyType key) { Integer id = super.get(key); if (id == null) { super.put(key, id = size()); } return id; } int getId(KeyType key) { return get(key); } } ///////////////////////////////////////////////////////////////////// private static class SortedIdMapper<ValueType extends Comparable<ValueType>> { private List<ValueType> values; public SortedIdMapper() { this.values = new ArrayList<ValueType>(); } void addValue(ValueType value) { values.add(value); } IdMap<ValueType> build() { Collections.sort(values); IdMap<ValueType> ids = new IdMap<ValueType>(); List<ValueType> uniqueValues = new ArrayList<ValueType>(); for (int index = 0; index < values.size(); ++index) { ValueType value = values.get(index); if (index == 0 || values.get(index - 1).compareTo(value) != 0) { ids.register(value); uniqueValues.add(value); } } values = uniqueValues; return ids; } } ///////////////////////////////////////////////////////////////////// private static int[] castInt(List<Integer> list) { int[] array = new int[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } private static long[] castLong(List<Long> list) { long[] array = new long[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } ///////////////////////////////////////////////////////////////////// /** * Generates list with keys 0..<n * @param n - exclusive limit of sequence */ private static List<Integer> order(int n) { List<Integer> sequence = new ArrayList<Integer>(); for (int i = 0; i < n; ++i) { sequence.add(i); } return sequence; } ///////////////////////////////////////////////////////////////////// interface Rmq { int getMin(int left, int right); int getMinIndex(int left, int right); } private static class SparseTable implements Rmq { private static final int MAX_BIT = 20; int n; int[] array; SparseTable(int[] array) { this.n = array.length; this.array = array; } int[] lengthMaxBits; int[][] table; int getIndexOfLess(int leftIndex, int rightIndex) { return (array[leftIndex] <= array[rightIndex]) ? leftIndex : rightIndex; } SparseTable build() { this.lengthMaxBits = new int[n + 1]; lengthMaxBits[0] = 0; for (int i = 1; i <= n; ++i) { lengthMaxBits[i] = lengthMaxBits[i - 1]; int length = (1 << lengthMaxBits[i]); if (length + length <= i) ++lengthMaxBits[i]; } this.table = new int[MAX_BIT][n]; table[0] = castInt(order(n)); for (int bit = 0; bit < MAX_BIT - 1; ++bit) { for (int i = 0, j = (1 << bit); j < n; ++i, ++j) { table[bit + 1][i] = getIndexOfLess( table[bit][i], table[bit][j] ); } } return this; } @Override public int getMinIndex(int left, int right) { int length = (right - left + 1); int bit = lengthMaxBits[length]; int segmentLength = (1 << bit); return getIndexOfLess( table[bit][left], table[bit][right - segmentLength + 1] ); } @Override public int getMin(int left, int right) { return array[getMinIndex(left, right)]; } } private static Rmq createRmq(int[] array) { return new SparseTable(array).build(); } ///////////////////////////////////////////////////////////////////// interface Lca { Lca build(int root); int lca(int a, int b); int height(int v); } private static class LcaRmq implements Lca { int n; int[][] graph; LcaRmq(int[][] graph) { this.n = graph.length; this.graph = graph; } int time; int[] order; int[] heights; int[] first; Rmq rmq; @Override public LcaRmq build(int root) { this.order = new int[n + n]; this.heights = new int[n]; this.first = new int[n]; Arrays.fill(first, -1); this.time = 0; dfs(root, 0); int[] orderedHeights = new int[n + n]; for (int i = 0; i < order.length; ++i) { orderedHeights[i] = heights[order[i]]; } this.rmq = createRmq(orderedHeights); return this; } void dfs(int from, int height) { first[from] = time; order[time] = from; heights[from] = height; ++time; for (int to : graph[from]) { if (first[to] == -1) { dfs(to, height + 1); order[time] = from; ++time; } } } @Override public int lca(int a, int b) { int aFirst = first[a], bFirst = first[b]; int left = min(aFirst, bFirst), right = max(aFirst, bFirst); int orderIndex = rmq.getMinIndex(left, right); return order[orderIndex]; } @Override public int height(int v) { return heights[v]; } } private static class LcaBinary implements Lca { private static final int MAX_BIT = 20; int n; int[][] graph; int[] h; int[][] parents; LcaBinary(int[][] graph) { this.n = graph.length; this.graph = graph; } @Override public Lca build(int root) { this.h = new int[n]; this.parents = new int[MAX_BIT][n]; Arrays.fill(parents[0], -1); Queue<Integer> queue = new ArrayDeque<Integer>(); queue.add(root); add(root, root); while (queue.size() > 0) { int from = queue.poll(); for (int to : graph[from]) { if (parents[0][to] == -1) { add(from, to); queue.add(to); } } } return this; } void add(int parent, int v) { h[v] = h[parent] + 1; parents[0][v] = parent; for (int bit = 0; bit < MAX_BIT - 1; ++bit) { parents[bit + 1][v] = parents[bit][parents[bit][v]]; } } @Override public int lca(int a, int b) { if (h[a] < h[b]) { int tmp = a; a = b; b = tmp; } int delta = h[a] - h[b]; for (int bit = MAX_BIT - 1; bit >= 0; --bit) { if (delta >= (1 << bit)) { delta -= (1 << bit); a = parents[bit][a]; } } if (a == b) return a; for (int bit = MAX_BIT - 1; bit >= 0; --bit) { int nextA = parents[bit][a], nextB = parents[bit][b]; if (nextA != nextB) { a = nextA; b = nextB; } } return parents[0][a]; } @Override public int height(int v) { return h[v]; } } private static Lca createLca(int[][] graph, int root) { return new LcaRmq(graph).build(root); } ///////////////////////////////////////////////////////////////////// private static class BiconnectedGraph { int n; int[][] graph; BiconnectedGraph(int[][] graph) { this.n = graph.length; this.graph = graph; } int time; int[] tin, up; boolean[] used; BiconnectedGraph build() { calculateTimes(); condensateComponents(); return this; } void calculateTimes() { this.tin = new int[n]; this.up = new int[n]; this.time = 0; this.used = new boolean[n]; timeDfs(0, -1); } void timeDfs(int from, int parent) { used[from] = true; up[from] = tin[from] = time; ++time; for (int to : graph[from]) { if (to == parent) continue; if (used[to]) { up[from] = min(up[from], tin[to]); } else { timeDfs(to, from); up[from] = min(up[from], up[to]); } } } int[] components; int[][] componentsGraph; int component(int v) { return components[v]; } int[][] toGraph() { return componentsGraph; } void condensateComponents() { this.components = new int[n]; Arrays.fill(components, -1); for (int v = 0; v < n; ++v) { if (components[v] == -1) { componentsDfs(v, v); } } GraphBuilder graphBuilder = GraphBuilder.createInstance(n); Set<Point> edges = new HashSet<Point>(); for (int from = 0; from < n; ++from) { int fromComponent = components[from]; for (int to : graph[from]) { int toComponent = components[to]; if (fromComponent == toComponent) continue; Point edge = new Point(fromComponent, toComponent); if (edges.add(edge)) graphBuilder.addDirectedEdge(fromComponent, toComponent); } } this.componentsGraph = graphBuilder.build(); } void componentsDfs(int from, int color) { components[from] = color; for (int to : graph[from]) { if (components[to] != -1) continue; if (tin[from] >= up[to] && tin[to] >= up[from]) { componentsDfs(to, color); } } } } ///////////////////////////////////////////////////////////////////// private static class VertexBiconnectedGraph { static class Edge { int to; int index; Edge(int to, int index) { this.to = to; this.index = index; } } int n, m; List<Edge>[] graph; List<Edge> edges; VertexBiconnectedGraph(int n) { this.n = n; this.m = 0; this.graph = new List[n]; for (int v = 0; v < n; ++v) { graph[v] = new ArrayList<Edge>(); } this.edges = new ArrayList<Edge>(); } void addEdge(int from, int to) { Edge fromToEdge = new Edge(to, m); Edge toFromEdge = new Edge(from, m + 1); edges.add(fromToEdge); edges.add(toFromEdge); graph[from].add(fromToEdge); graph[to].add(toFromEdge); m += 2; } int time; boolean[] used; int[] tin, up; int[] parents; boolean[] isArticulation; boolean[] findArticulationPoints() { this.isArticulation = new boolean[n]; this.used = new boolean[n]; this.parents = new int[n]; Arrays.fill(parents, -1); this.tin = new int[n]; this.up = new int[n]; this.time = 0; for (int v = 0; v < n; ++v) { if (!used[v]) { articulationDfs(v, -1); } } return isArticulation; } void articulationDfs(int from, int parent) { used[from] = true; parents[from] = parent; ++time; up[from] = tin[from] = time; int childrenCount = 0; for (Edge e : graph[from]) { int to = e.to; if (to == parent) continue; if (used[to]) { up[from] = min(up[from], tin[to]); } else { ++childrenCount; articulationDfs(to, from); up[from] = min(up[from], up[to]); if (up[to] >= tin[from] && parent != -1) { isArticulation[from] = true; } } } if (parent == -1 && childrenCount > 1) { isArticulation[from] = true; } } int[] edgeColors; int maxEdgeColor; int[] paintEdges() { this.edgeColors = new int[m]; Arrays.fill(edgeColors, -1); this.maxEdgeColor = -1; this.used = new boolean[n]; for (int v = 0; v < n; ++v) { if (!used[v]) { ++maxEdgeColor; paintDfs(v, maxEdgeColor, -1); } } return edgeColors; } void paintEdge(int edgeIndex, int color) { if (edgeColors[edgeIndex] != -1) return; edgeColors[edgeIndex] = edgeColors[edgeIndex ^ 1] = color; } void paintDfs(int from, int color, int parent) { used[from] = true; for (Edge e : graph[from]) { int to = e.to; if (to == parent) continue; if (!used[to]) { if (up[to] >= tin[from]) { int newColor = ++maxEdgeColor; paintEdge(e.index, newColor); paintDfs(to, newColor, from); } else { paintEdge(e.index, color); paintDfs(to, color, from); } } else if (up[to] <= tin[from]){ paintEdge(e.index, color); } } } Set<Integer>[] collectVertexEdgeColors() { Set<Integer>[] vertexEdgeColors = new Set[n]; for (int v = 0; v < n; ++v) { vertexEdgeColors[v] = new HashSet<Integer>(); for (Edge e : graph[v]) { vertexEdgeColors[v].add(edgeColors[e.index]); } } return vertexEdgeColors; } VertexBiconnectedGraph build() { findArticulationPoints(); paintEdges(); createComponentsGraph(); return this; } int[][] componentsGraph; void createComponentsGraph() { Set<Integer>[] vertexEdgeColors = collectVertexEdgeColors(); int edgeColorShift = vertexEdgeColors.length; int size = vertexEdgeColors.length + maxEdgeColor + 1; GraphBuilder graphBuilder = GraphBuilder.createInstance(size); for (int v = 0; v < vertexEdgeColors.length; ++v) { for (int edgeColor : vertexEdgeColors[v]) { graphBuilder.addEdge(v, edgeColor + edgeColorShift); } } this.componentsGraph = graphBuilder.build(); } int[][] toGraph() { return componentsGraph; } } ///////////////////////////////////////////////////////////////////// private static class DSU { int[] sizes; int[] ranks; int[] parents; static DSU createInstance(int size) { int[] sizes = new int[size]; Arrays.fill(sizes, 1); return new DSU(sizes); } DSU(int[] sizes) { this.sizes = sizes; int size = sizes.length; this.ranks = new int[size]; Arrays.fill(ranks, 1); this.parents = castInt(order(size)); } int get(int v) { if (v == parents[v]) return v; return parents[v] = get(parents[v]); } boolean union(int a, int b) { a = get(a); b = get(b); if (a == b) return false; if (ranks[a] < ranks[b]) { int tmp = a; a = b; b = tmp; } parents[b] = a; sizes[a] += sizes[b]; if (ranks[a] == ranks[b]) ++ranks[a]; return true; } } ///////////////////////////////////////////////////////////////////// static abstract class SegmentTree { int size; boolean lazySupported; boolean[] lazy; long[] values; long[] tree; SegmentTree(int n, boolean lazySupported) { this.size = n; this.lazySupported = lazySupported; int treeSize = size << 2; this.tree = new long[treeSize]; if (lazySupported) { this.lazy = new boolean[treeSize]; this.values = new long[treeSize]; } } SegmentTree(int[] a, boolean lazySupported) { this(a.length, lazySupported); } abstract void updateValue(int v, int left, int right, long value); void setLazyValue(int v, long value) { throw new UnsupportedOperationException(); } void pushVertex(int v, int vLeft, int vRight) { if (lazy[v]) { setLazyValue(vLeft, values[v]); setLazyValue(vRight, values[v]); lazy[v] = false; values[v] = 0; } } abstract void updateVertex(int v, int vLeft, int vRight); int[] a; void buildTree(int[] a) { this.a = a; buildTree(1, 0, size - 1); } void buildTree(int v, int left, int right) { if (left == right) { updateValue(v, left, right, a[left]); } else { int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); buildTree(vLeft, left, mid); buildTree(vRight, mid + 1, right); updateVertex(v, vLeft, vRight); } } long value; int index; void updateIndex(int index, long value) { this.index = index; this.value = value; updateTreeIndex(1, 0, size - 1); } void updateTreeIndex(int v, int left, int right) { if (left == right) { updateValue(v, left, right, value); } else { int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); if (index <= mid) updateTreeIndex(vLeft, left, mid); else updateTreeIndex(vRight, mid + 1, right); updateVertex(v, vLeft, vRight); } } int start, end; void updateSegment(int start, int end, long value) { this.start = start; this.end = end; this.value = value; updateTreeSegment(1, 0, size - 1); } void updateTreeSegment(int v, int left, int right) { if (start <= left && right <= end) { if (lazySupported) { setLazyValue(v, value); } else { updateValue(v, left, right, value); } } else { int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); if (lazySupported) pushVertex(v, vLeft, vRight); if (start <= mid) updateTreeSegment(vLeft, left, mid); if (mid < end) updateTreeSegment(vRight, mid + 1, right); updateVertex(v, vLeft, vRight); } } abstract void initResult(long... initResultValues); abstract void accumulateResult(int v, int left, int right); void getIndex(int index, long... initResultValues) { this.index = index; initResult(initResultValues); getTreeIndex(1, 0, size - 1); } void getTreeIndex(int v, int left, int right) { if (lazySupported) { if (left == right) { accumulateResult(v, left, right); } else { int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); pushVertex(v, vLeft, vRight); if (index <= mid) getTreeIndex(vLeft, left, mid); else getTreeIndex(vRight, mid + 1, right); updateVertex(v, vLeft, vRight); } } else { while (left <= right) { accumulateResult(v, left, right); if (left == right) break; int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); if (index <= mid) { v = vLeft; right = mid; } else { v = vRight; left = mid + 1; } } } } void getSegment(int start, int end, long... initResultValues) { this.start = start; this.end = end; initResult(initResultValues); getTreeSegment(1, 0, size - 1); } void getTreeSegment(int v, int left, int right) { if (start <= left && right <= end) { accumulateResult(v, left, right); } else { int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); if (lazySupported) pushVertex(v, vLeft, vRight); if (start <= mid) getTreeSegment(vLeft, left, mid); if (mid < end) getTreeSegment(vRight, mid + 1, right); if (lazySupported) updateVertex(v, vLeft, vRight); } } int[] toArray() { this.a = new int[size]; fillTreeArray(1, 0, size - 1); return a; } void fillTreeArray(int v, int left, int right) { if (left == right) { a[left] = (int)(tree[v]); } else { int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); if (lazySupported) pushVertex(v, vLeft, vRight); fillTreeArray(vLeft, left, mid); fillTreeArray(vRight, mid + 1, right); if (lazySupported) updateVertex(v, vLeft, vRight); } } } ///////////////////////////////////////////////////////////////////// }
Java
["3\n8 4 13\n17 2 7", "5\n12 7 87 22 11\n18 39 9 12 16", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667"]
3.5 seconds
["10 3 28", "0 14 69 6 44", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284"]
NoteIn the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Java 8
standard input
[ "data structures", "greedy", "trees", "strings" ]
dc778193a126009f545d1d6f307bba83
The first line contains a single integer N (1 ≀ N ≀ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≀ Ai &lt; 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≀ Pi &lt; 230) representing the permuted encryption key.
1,800
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
standard output
PASSED
ef152fdece9aec4fc154651dda0d0135
train_003.jsonl
1267963200
A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times bigger than kayaks (and occupy the space of 2 cubic metres).Each waterborne vehicle has a particular carrying capacity, and it should be noted that waterborne vehicles that look the same can have different carrying capacities. Knowing the truck body volume and the list of waterborne vehicles in the boat depot (for each one its type and carrying capacity are known), find out such set of vehicles that can be taken in the lorry, and that has the maximum total carrying capacity. The truck body volume of the lorry can be used effectively, that is to say you can always put into the lorry a waterborne vehicle that occupies the space not exceeding the free space left in the truck body.
64 megabytes
//package cf_3b; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; public class Main { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] input = in.readLine().split("\\s"); int n = Integer.parseInt(input[0]); int maxVol = Integer.parseInt(input[1]); ArrayList<Boat> kayak = new ArrayList<Boat>(); ArrayList<Boat> catam = new ArrayList<Boat>(); int cSize = 0; int kSize = 0; for(int i = 0; i < n; i++){ String[] line = in.readLine().split("\\s"); int boatSize = Integer.parseInt(line[0]); int capacity = Integer.parseInt(line[1]); if(boatSize == 1){ kayak.add(new Boat(capacity, i)); kSize++; } else{ catam.add(new Boat(capacity, i)); cSize++; } } Collections.sort(kayak); Collections.sort(catam); ArrayList<Integer> indexes = new ArrayList<Integer>(); int maxCap = 0; int k = 0; int c = 0; for(int i = maxVol; i > 0;){ if(i > 1){ int temp = 0; if(k < kSize && c < cSize){ int next = k + 1; if(next < kSize) temp = kayak.get(k).capacity + kayak.get(next).capacity; else temp = kayak.get(k).capacity; if(temp > catam.get(c).capacity){ maxCap += kayak.get(k).capacity; indexes.add(kayak.get(k).index + 1); i--; k++; } else{ maxCap += catam.get(c).capacity; indexes.add(catam.get(c).index + 1); i -= 2; c++; } } else if(k < kSize){ maxCap += kayak.get(k).capacity; indexes.add(kayak.get(k).index + 1); i--; k++; } else if(c < cSize){ maxCap += catam.get(c).capacity; indexes.add(catam.get(c).index + 1); i--; c++; } else break; } else { if(k < kSize){ maxCap += kayak.get(k).capacity; indexes.add(kayak.get(k).index + 1); i--; k++; } else break; } } System.out.println(maxCap); StringBuffer index = new StringBuffer(); for(int ind: indexes) index.append(ind + " "); System.out.println(index); } public static class Boat implements Comparable<Boat>{ int capacity, index; Boat(int c, int i){ this.capacity = c; this.index = i; } @Override public int compareTo(Boat b) { return b.capacity - this.capacity; } } }
Java
["3 2\n1 2\n2 7\n1 3"]
2 seconds
["7\n2"]
null
Java 8
standard input
[ "sortings", "greedy" ]
a1f98b06650a5755e784cd6ec6f3b211
The first line contains a pair of integer numbers n and v (1 ≀ n ≀ 105; 1 ≀ v ≀ 109), where n is the number of waterborne vehicles in the boat depot, and v is the truck body volume of the lorry in cubic metres. The following n lines contain the information about the waterborne vehicles, that is a pair of numbers ti, pi (1 ≀ ti ≀ 2; 1 ≀ pi ≀ 104), where ti is the vehicle type (1 – a kayak, 2 – a catamaran), and pi is its carrying capacity. The waterborne vehicles are enumerated in order of their appearance in the input file.
1,900
In the first line print the maximum possible carrying capacity of the set. In the second line print a string consisting of the numbers of the vehicles that make the optimal set. If the answer is not unique, print any of them.
standard output
PASSED
15b6aa5e306ca59dd418a33feaee9162
train_003.jsonl
1267963200
A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times bigger than kayaks (and occupy the space of 2 cubic metres).Each waterborne vehicle has a particular carrying capacity, and it should be noted that waterborne vehicles that look the same can have different carrying capacities. Knowing the truck body volume and the list of waterborne vehicles in the boat depot (for each one its type and carrying capacity are known), find out such set of vehicles that can be taken in the lorry, and that has the maximum total carrying capacity. The truck body volume of the lorry can be used effectively, that is to say you can always put into the lorry a waterborne vehicle that occupies the space not exceeding the free space left in the truck body.
64 megabytes
// Problem : B. Lorry // Contest : Codeforces - Codeforces Beta Round #3 // URL : https://codeforces.com/problemset/problem/3/B // Memory Limit : 64 MB // Time Limit : 2000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) import java.io.*; import java.util.*; import java.util.stream.*; public class a implements Runnable{ public static void main(String[] args) { new Thread(null, new a(), "process", 1<<26).start(); } public void run() { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); //PrintWriter out = new PrintWriter("file.out"); Task solver = new Task(); //int t = scan.nextInt(); int t = 1; for(int i = 1; i <= t; i++) solver.solve(i, scan, out); out.close(); } static class Task { static final int inf = Integer.MAX_VALUE; public void solve(int testNumber, FastReader sc, PrintWriter pw) { //CHECK FOR QUICKSORT TLE //***********************// //CHECK FOR INT OVERFLOW //***********************// int n = sc.nextInt(); int m = sc.nextInt(); ArrayList<tup> on = new ArrayList<tup>(); ArrayList<tup> yt = new ArrayList<tup>(); for(int i = 0; i < n; i++) { int k = sc.nextInt(); if(k == 1) { on.add(new tup(i + 1, sc.nextInt())); } else{ yt.add(new tup(i + 1, sc.nextInt())); } } Collections.sort(on); Collections.sort(yt); int ptr1 = on.size()-1; int ptr2 = yt.size()-1; long ans = 0; while(m > 1 && ptr2 >= 0) { ans += yt.get(ptr2--).b; m-= 2; } while(m > 0 && ptr1 >= 0) { ans += on.get(ptr1--).b; m--; } long max = ans; int cp1 = ptr1; int cp2 = ptr2; while(ptr2 < yt.size() - 1 && ptr1 > 0) { ans -= yt.get(++ptr2).b; ans += on.get(ptr1--).b; if(ptr1 >= 0) ans += on.get(ptr1--).b; else{ ptr1--; } if(max < ans) { cp1 = ptr1; cp2 = ptr2; max = ans; } } pw.println(max); for(int i = cp2 + 1; i < yt.size(); i++) { pw.print(yt.get(i).a + " "); } for(int i = cp1 + 1; i < on.size(); i++) { pw.print(on.get(i).a + " "); } } } static long binpow(long a, long b, long m) { a %= m; long res = 1; while (b > 0) { if ((b & 1) == 1) res = res * a % m; a = a * a % m; b >>= 1; } return res; } static void sort(int[] x){ shuffle(x); Arrays.sort(x); } static void sort(long[] x){ shuffle(x); Arrays.sort(x); } static class tup implements Comparable<tup>{ int a, b; tup(int a,int b){ this.a=a; this.b=b; } @Override public int compareTo(tup o){ return Integer.compare(b,o.b); } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(i + 1); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(i + 1); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3 2\n1 2\n2 7\n1 3"]
2 seconds
["7\n2"]
null
Java 8
standard input
[ "sortings", "greedy" ]
a1f98b06650a5755e784cd6ec6f3b211
The first line contains a pair of integer numbers n and v (1 ≀ n ≀ 105; 1 ≀ v ≀ 109), where n is the number of waterborne vehicles in the boat depot, and v is the truck body volume of the lorry in cubic metres. The following n lines contain the information about the waterborne vehicles, that is a pair of numbers ti, pi (1 ≀ ti ≀ 2; 1 ≀ pi ≀ 104), where ti is the vehicle type (1 – a kayak, 2 – a catamaran), and pi is its carrying capacity. The waterborne vehicles are enumerated in order of their appearance in the input file.
1,900
In the first line print the maximum possible carrying capacity of the set. In the second line print a string consisting of the numbers of the vehicles that make the optimal set. If the answer is not unique, print any of them.
standard output
PASSED
051d3e42c2910d75d8a0ad76fa27f016
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static class Pair implements Comparable<Pair> { int x,y,ind; public Pair(int x, int y,int ind) { this.x = x; this.y = y; this.ind=ind; } public int compareTo(Pair o) { if(x!=o.x) return x-o.x; return this.y - o.y; } public int hashCode() { return (int)(1L*1000000000*x + y)%1000000007; } public boolean equals(Object o) { if(o instanceof Pair) { Pair other = (Pair)o; return other.hashCode()==this.hashCode(); } else return false; } public String toString(){ return x+" "+y; } } static Scanner sc = new Scanner(System.in); //static Reader sc = new Reader(); static StringBuilder sb = new StringBuilder(); static PrintWriter pw = new PrintWriter(System.out,true); public static void main(String[] args) throws IOException { //Code start from here int n = sc.nextInt(); LinkedList<Integer> list = new LinkedList<>(); for(int i=0;i<n;i++) list.add(sc.nextInt()); int first= list.peekFirst(),last = list.peekLast(),prev =0,cnt=0; while(!list.isEmpty()) { if(first==last) { if(first>prev) { int val1 = left_count(list), val2 = right_count(list); if (val1 > val2) { add(val1, "L"); cnt+=val1; }else { add(val2, "R"); cnt += val2; } } break; } if(first>prev && last>prev) { if(first<last) { sb.append("L"); prev = list.pollFirst(); first = list.peekFirst(); } else if(last<first) { sb.append("R"); prev = list.pollLast(); last = list.peekLast(); } cnt++; } else if(first>prev) { int val = left_count(list); cnt+=val; add(val,"L"); break; } else if(last>prev) { int val = right_count(list); cnt+=val; add(val,"R"); break; } else break; } System.out.println(cnt); pw.println(sb); pw.flush(); pw.close(); } static int right_count(LinkedList<Integer> l) { LinkedList<Integer> local = new LinkedList<>(); for(int i : l) local.add(i); int cnt=1,x = local.pollLast(); while(!local.isEmpty()) { if(local.peekLast()>x) { cnt++; x= local.pollLast(); } else return cnt; } return cnt; } static int left_count(LinkedList<Integer> l) { LinkedList<Integer> local = new LinkedList<>(); for(int i : l) local.add(i); int cnt=1,x = local.pollFirst(); while(!local.isEmpty()) { if(local.peekFirst()>x) { cnt++; x= local.pollFirst(); } else return cnt; } return cnt; } static void add(int val,String str) { while(val-->0) sb.append(str); } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
a0d9cd6b31e2fe57fedc8f85383a2ac1
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import javax.print.DocFlavor; import javax.swing.plaf.basic.BasicInternalFrameTitlePane; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.nio.Buffer; import java.sql.BatchUpdateException; import java.util.*; import java.util.stream.Stream; import java.util.Vector; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static java.lang.Math.*; import java.util.*; import java.nio.file.StandardOpenOption; import java.util.Comparator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Iterator; import java.util.PriorityQueue; public class icpc { public static void main(String[] args)throws IOException { Reader in = new Reader(); // BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = in.nextInt(); int[] A = new int[n]; for(int i=0;i<n;i++) A[i] = in.nextInt(); int len1[] = new int[n]; int len2[] = new int[n]; Arrays.fill(len1, 1); Arrays.fill(len2, 1); for(int i=n-2;i>=0;i--) { if(A[i] < A[i+1]) len1[i] = len1[i+1] + 1; else continue; } for(int i=1;i<n;i++) { if(A[i] < A[i-1]) len2[i] = len2[i-1] + 1; else continue; } StringBuilder stringBuilder = new StringBuilder(); int i = 0; int j = n - 1; int last = Integer.MIN_VALUE; int len = 0; while(true) { if(i > j) break; if(i == j) { if(A[i] > last) { stringBuilder.append("L"); last = A[i]; len++; break; } else break; } if(A[i] < A[j] && A[i] > last) { stringBuilder.append("L"); last = A[i]; i++; len ++; } else if(A[j] < A[i] && A[j] > last) { stringBuilder.append("R"); last = A[j]; j--; len++; } else if(A[i] < A[j] && A[i] <= last) { if(A[j] > last) { stringBuilder.append("R"); last = A[j]; len++; j--; } else { break; } } else if(A[j] < A[i] && A[j] <= last) { if(A[i] > last) { stringBuilder.append("L"); last = A[i]; len++; i++; } else break; } else if(A[i] == A[j]) { if(A[i] <= last) { break; } else { if(A[i+1] == A[i] && A[j-1] == A[j]) { stringBuilder.append("L"); len++; break; } else if(A[i+1] == A[i]) { if(A[j-1] > A[j]) { stringBuilder.append("R"); len++; int remLen = len2[j-1]; len+= remLen; for(int k=0;k<remLen;k++) stringBuilder.append("R"); break; } else { stringBuilder.append("R"); len++; last = A[j]; break; } } else if(A[j-1] == A[j]) { if(A[i+1] > A[i]) { stringBuilder.append("L"); int remLen = len1[i+1]; len+= remLen + 1; for(int k=0;k<remLen;k++) stringBuilder.append("L"); break; } else { stringBuilder.append("L"); len++; last = A[i]; break; } } else { int a1 = len1[i+1]; int a2 = len2[j-1]; if(a1 >= a2 && A[i+1] > A[i]) { stringBuilder.append("L"); for(int k=0;k<a1;k++) stringBuilder.append("L"); len+= a1 + 1; } else if(a2 >= a1 && A[j-1] > A[j]) { stringBuilder.append("R"); for(int k=0;k<a2;k++) { stringBuilder.append("R"); } len += a2 + 1; } else if(a1 >= a2 && A[i+1] < A[i]) { if(A[j-1] > A[j]) { stringBuilder.append("R"); for(int k=0;k<a2;k++) stringBuilder.append("R"); len += a2 + 1; break; } else { stringBuilder.append("R"); len ++; break; } } else if(a2 >= a1 && A[j-1] < A[j]) { if(A[i+1] > A[i]) { stringBuilder.append("L"); for(int k=0;k<a1;k++) stringBuilder.append("L"); len += a1 + 1; break; } else break; } break; } } } else break; } System.out.println(len); System.out.println(stringBuilder); } } class Matrix { long a; long b; long c; long d; public Matrix(long a, long b, long c, long d) { this.a = a; this.b = b; this.c = c; this.d = d; } } class Game implements Comparable<Game> { long x; int y; Game(long a,int b) { this.x = a; this.y = b; } public int compareTo(Game ob) { if(this.x < ob.x) return 1; else if(this.x > ob.x) return -1; return 0; } } class MergeSort { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long [n1]; long R[] = new long [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class Node { String a; String b; Node(String s1,String s2) { this.a = s1; this.b = s2; } @Override public boolean equals(Object ob) { if(ob == null) return false; if(!(ob instanceof Node)) return false; if(ob == this) return true; Node obj = (Node)ob; if(this.a.equals(obj.a) && this.b.equals(obj.b)) return true; return false; } @Override public int hashCode() { return (int)this.a.length(); } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } class Hey { public static int multTwoNumbers(int a, int b, int n) { if(a == 0) return 0; else if(a % 2 == 0) return (2 * ((multTwoNumbers(a / 2, b, n)) % n))% n; else return ((2 * ((multTwoNumbers((a - 1) / 2, b, n)) % n))% n + b) % n; } public static long binPow(long a, long n) { long res = 1L; while (n > 0) { if((n & 1) > 0) { res *= a; } a *= a; n >>= 1; } return res; } public static long phi(long n) { long result = n; for(int i=2;i*i <= n;i++) { if(n % i == 0) { while(n % i == 0) n = n / i; result -= result / (long)i; } } if(n > 1) result -= result / n; return result; } } class SegmentTree { public int nextPowerOfTwo(int num) { if(num == 0) return 1; if(num > 0 && (num & (num - 1)) == 0) return num; while((num &(num - 1)) > 0) { num = num & (num - 1); } return num << 1; } } class FenwickTree { public void update(long[] fenwickTree,long delta,int index) { index += 1; while(index < fenwickTree.length) { fenwickTree[index] += delta; index = index + (index & (-index)); } } public long prefixSum(long[] fenwickTree,int index) { long sum = 0L; index += 1; while(index > 0) { sum += fenwickTree[index]; index -= (index & (-index)); } return sum; } } class SegmentTree1 { public int nextPowerOfTwo(int num) { if(num == 0) return 1; if(num > 0 && (num & (num - 1)) == 0) return num; while((num &(num - 1)) > 0) { num = num & (num - 1); } return num << 1; } public int[] createSegmentTree(int[] input) { int np2 = nextPowerOfTwo(input.length); int[] segmentTree = new int[np2 * 2 - 1]; for(int i=0;i<segmentTree.length;i++) segmentTree[i] = Integer.MAX_VALUE; constructSegmentTree(segmentTree,input,0,input.length-1,0); return segmentTree; } private void constructSegmentTree(int[] segmentTree,int[] input,int low,int high,int pos) { if(low == high) { segmentTree[pos] = input[low]; return; } int mid = (low + high)/ 2; constructSegmentTree(segmentTree,input,low,mid,2*pos + 1); constructSegmentTree(segmentTree,input,mid+1,high,2*pos + 2); segmentTree[pos] = Math.min(segmentTree[2*pos + 1],segmentTree[2*pos + 2]); } public int rangeMinimumQuery(int[] segmentTree,int qlow,int qhigh,int len) { return rangeMinimumQuery(segmentTree,0,len - 1,qlow,qhigh,0); } private int rangeMinimumQuery(int[] segmentTree,int low,int high,int qlow,int qhigh,int pos) { if(qlow <= low && qhigh >= high) { return segmentTree[pos]; } else if(qlow > high || qhigh < low) { return Integer.MAX_VALUE; } int mid = (low + high)/2; return Math.min(rangeMinimumQuery(segmentTree,low,mid,qlow,qhigh,2*pos+1),rangeMinimumQuery(segmentTree,mid+1,high,qlow,qhigh,2*pos+2)); } public void updateSegmentTreeRangeLazy(int[] input,int[] segmentTree,int[] lazy,int startRange,int endRange,int delta) { updateSegmentTreeRangeLazy(input,segmentTree,lazy,startRange,endRange,delta,0,input.length-1,0); } private void updateSegmentTreeRangeLazy(int[] input,int[] segmentTree,int[] lazy,int startRange,int endRange,int delta,int low,int high,int pos) { if(low > high) { return; } if(lazy[pos] != 0) { segmentTree[pos] += lazy[pos]; if(low != high) { lazy[2*pos+1] += lazy[pos]; lazy[2*pos + 2] += lazy[pos]; } lazy[pos] = 0; } if(startRange > high || endRange < low) return; if(startRange <= low && endRange >= high) { segmentTree[pos] += delta; if(low != high) { lazy[2*pos + 1] += delta; lazy[2*pos + 2] += delta; } return; } int mid = (low + high)/2; updateSegmentTreeRangeLazy(input,segmentTree,lazy,startRange,endRange,delta,low,mid,2*pos + 1); updateSegmentTreeRangeLazy(input,segmentTree,lazy,startRange,endRange,delta,mid + 1,high,2 * pos + 2); segmentTree[pos] += Math.min(segmentTree[2*pos + 1],segmentTree[2*pos + 2]); } public int rangeMinimumQueryLazy(int[] segmentTree,int[] lazy,int qlow,int qhigh,int len) { return rangeMinimumQueryLazy(segmentTree,lazy,qlow,qhigh,0,len - 1,0); } private int rangeMinimumQueryLazy(int[] segmentTree,int[] lazy,int qlow,int qhigh,int low,int high,int pos) { if(low > high) return Integer.MAX_VALUE; if(lazy[pos] != 0) { segmentTree[pos] += lazy[pos]; if(low != high) { lazy[2*pos + 1] += lazy[pos]; lazy[2*pos + 2] += lazy[pos]; } lazy[pos] = 0; } if(qlow > high || qhigh < low) return Integer.MAX_VALUE; if(qlow <= low && qhigh >= low) return segmentTree[pos]; int mid = (low + high)/2; return Math.min(rangeMinimumQueryLazy(segmentTree,lazy,qlow,qhigh,low,mid,2*pos + 1),rangeMinimumQueryLazy(segmentTree,lazy,qlow,qhigh,mid + 1,high,2*pos + 2)); } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
a3d6fc4c6c9c278b8790c732fa8c4f56
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
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 C1_Round_555_Div3 { public static long MOD = 998244353; static long[][][] dp; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int[] data = new int[n]; for (int i = 0; i < n; i++) { data[i] = in.nextInt(); } int st = 0; int ed = n - 1; int last = 0; StringBuilder builder = new StringBuilder(); while (st <= ed && (data[st] > last || data[ed] > last)) { if (data[st] < data[ed]) { if (data[st] > last) { last = data[st++]; builder.append("L"); } else { last = data[ed--]; builder.append("R"); } } else if (data[st] > data[ed]) { if (data[ed] > last) { last = data[ed--]; builder.append("R"); } else { last = data[st++]; builder.append("L"); } } else { int a = 0; int v = last; for (int i = st; i <= ed; i++) { if (data[i] > v) { a++; v = data[i]; } else { break; } } int b = 0; v = last; for (int i = ed; i >= st; i--) { if (data[i] > v) { b++; v = data[i]; } else { break; } } //System.out.println(a + " " + b); if (a > b) { for (int i = st; i <= ed; i++) { if (data[i] > last) { last = data[i]; builder.append("L"); } else { break; } } } else { for (int i = ed; i >= st; i--) { if (data[i] > last) { last = data[i]; builder.append("R"); }else{ break; } } } break; } } out.println(builder.length()); out.println(builder.toString()); out.close(); } static class Node { int l, r; int v, index; Node left, right; public Node(int l, int r) { this.l = l; this.r = r; } } static void update(int v, int index, Node node) { if (index > node.r || index < node.l) { return; } if (index == node.l && index == node.r) { node.v = v; node.index = index; return; } int mid = (node.r + node.l) / 2; if (node.left == null) { node.left = new Node(node.l, mid); node.right = new Node(mid + 1, node.r); } update(v, index, node.left); update(v, index, node.right); if (node.left.v > node.right.v) { node.v = node.left.v; node.index = node.left.index; } else { node.v = node.right.v; node.index = node.right.index; } } static Point get(int index, Node node) { if (node.l > index) { return new Point(0, 0); } if (node.r <= index) { return new Point(node.index, node.v); } int mid = (node.r + node.l) / 2; if (node.left == null) { node.left = new Node(node.l, mid); node.right = new Node(mid + 1, node.r); } Point a = get(index, node.left); Point b = get(index, node.right); if (a.y > b.y) { return a; } return b; } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
4b8fb02359aa773552fff1cb383f5ea0
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import java.awt.*; import java.io.*; import java.util.*; public class Abc { public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); int n = sc.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); int l = 0, r = n - 1; StringBuilder sb = new StringBuilder(); while (true) { if (a[l] == a[r]) { if (sb.length() != 0) { int i = sb.length() - 1; if (sb.charAt(i) == 'L') i = l - 1; else i = r + 1; if (a[l] <= a[i]) { break; } } StringBuilder sbl = new StringBuilder(); StringBuilder sbr = new StringBuilder(); int x = l; sbl.append('L'); x++; while (x < r) { if (a[x] <= a[x - 1]) break; sbl.append('L'); x++; } x = r; sbr.append('R'); x--; while (x > l) { if (a[x] <= a[x + 1]) break; sbr.append('R'); x--; } if (sbl.length() > sbr.length()) { sb.append(sbl); } else sb.append(sbr); break; } else { if (sb.length()==0){ if (a[l] < a[r]) { sb.append('L'); l++; } else { sb.append('R'); r--; } }else { int i = sb.length() - 1; if (sb.charAt(i) == 'R') i = r + 1; else i = l - 1; if (a[l]>a[i] && a[r]>a[i]){ if (a[l] < a[r]) { sb.append('L'); l++; } else { sb.append('R'); r--; } }else if (a[l]>a[i]){ sb.append('L'); l++; }else if (a[r]>a[i]){ sb.append('R'); r--; }else break; } } } System.out.println(sb.length()); System.out.println(sb); } 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
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
3581000039fe08ee767a6dd849beb42b
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import java.util.Scanner; public class asdasd { public static void main(String args[]) { Scanner scan=new Scanner(System.in); int maxn=2000000; int n=scan.nextInt(); char s[]=new char[maxn]; int h[]=new int[maxn]; int a[]=new int[maxn]; for(int i=1;i<=n;i++) { a[i]=scan.nextInt(); } int l=1,r=n; int x=0; int tot=0; while(l<=r) { if(a[l]==a[r])break; int y=Math.max(a[l],a[r]); if (x>=y)break; if(a[l]<a[r] && a[l]>x) { s[tot++]='L'; x=a[l]; l++; } else if(a[l]>a[r] && a[r]>x) { s[tot++]='R'; x=a[r]; r--; } else if(a[l]>x) { s[tot++]='L'; x=a[l]; l++; }else { s[tot++]='R'; x=a[r]; r--; } } if(x>=a[l]) { System.out.println(tot); for(int i=0;i<tot;i++) { System.out.print(s[i]); } return; } else { int len1=01; for(int i=l+1;i<=r;i++) { if(a[i]<=a[i-1])break; len1++; } int rlen2=1; // System.out.println(l+" "+r); for(int i=r-1;i>=l;i--) { if(a[i]<=a[i+1])break; // System.out.println("2"); rlen2++; } if(len1>rlen2) { for(int i=0;i<len1;i++) { s[tot++]='L'; } }else { for(int i=0;i<rlen2;i++) { s[tot++]='R'; } } System.out.println(tot); for(int i=0;i<tot;i++) { System.out.print(s[i]); } } } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
8bbc0cf6103cf7836ae9f25fc9387abf
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
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 Main { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); int i = 0, j = n-1; int max = 0; StringBuilder sb = new StringBuilder(); while(i <= j && i < n) { if(a[i] < max && a[j] < max) { out.println(sb.length()); out.println(sb); return; } else { if(a[i] == a[j]) { int ci = 1; while(i+1 < n && a[i] < a[i+1]) { ci++; i++; } int cj = 1; while(j-1 >= 0 && a[j-1] > a[j]) { cj++; j--; } if(cj > ci) { for(int k = 0; k < cj; k++) { sb.append("R"); } } else { for(int k = 0; k < ci; k++) { sb.append("L"); } } break; } if(a[i] > max && a[j] > max) { if(a[i] > a[j]) { sb.append("R"); max = a[j]; j--; } else { sb.append("L"); max = a[i]; i++; } } else if(a[i] > max) { sb.append("L"); max = a[i]; i++; } else if(a[j] > max) { sb.append("R"); max = a[j]; j--; } else break; } } out.println(sb.length()); out.println(sb); } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
c58bd1dbd9859cb337879b7b390d01f0
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import java.io.*; import static java.lang.Math.*; import java.util.*; public class IncreasingSubsequencehardversion { static String res = ""; static int arr[]; static void solve(int le, int r, int last, StringBuilder s) { if ((le<=r&&arr[le] <= last && arr[r] <= last) || le > r) { if (res.length() < s.length()) { res = s + ""; } return; } boolean osl = false; boolean osr = false; if (last < arr[le]) { osl = true; } if (last < arr[r]) { osr = true; } if (osr&&osl&&arr[le]==arr[r]){ int a =1; int b=1; for (int i = le+1; i < r; i++) { if (arr[i]>arr[i-1]) { a++; }else break; } for (int i = r-1; i >=le; i--) { if (arr[i]>arr[i+1]) { b++; }else break; } if (a>b) { for (int i = 0; i < a; i++) { s.append('L'); } }else { for (int i = 0; i < b; i++) { s.append('R'); } } res= s+""; return ; }else if(osl && osr){ if (arr[le] < arr[r]) { s.append('L'); solve(le+1,r,arr[le],s); } else { s.append('R'); solve(le,r-1,arr[r],s); } } else if (osl) { s.append('L'); solve(le+1,r,arr[le],s); } else if (osr) { s.append('R'); solve(le,r-1,arr[r],s); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); StringBuilder out = new StringBuilder(); int n = in.nextInt(); arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } solve(0,n-1,-1,new StringBuilder()); System.out.println(res.length()); System.out.println(res); } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
de681fa2c16182b93bbc2e43dd4eb4e1
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.math.*; import java.util.*; //good question public class Main { public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; for( int i=0;i<n;i++) { a[i]=sc.nextInt(); } ArrayList<Character> adj=new ArrayList<>(); int prev=-1; int incR[] = new int[n]; int incL[] = new int[n]; incL[0] = 1; incR[n-1] = 1; for(int i = 1; i < n; i++) { if(a[i] < a[i-1]) incL[i] = 1+incL[i-1]; else incL[i] = 1; } for(int i = n-2; i >= 0; i--) { if(a[i] < a[i+1]) incR[i] = 1+incR[i+1]; else incR[i] = 1; } int l = 0, r = n-1; while(true) { if(l > r) break; if(a[l] < a[r] && a[l] > prev) { adj.add('L'); prev = a[l]; l++; } else if(a[l] > a[r] && a[r] > prev) { if(a[r] <= prev) break; adj.add('R'); prev = a[r]; r--; } else { int goR = incR[l]; int goL = incL[r]; if(a[l] <= prev) goR = -1; if(a[r] <= prev) goL = -1; int numLeft = r-l+1; if(goR > goL) { for(int i = 0; i < Math.min(numLeft, goR); i++) { adj.add('L'); } } else { for(int i = 0; i < Math.min(numLeft, goL); i++) { adj.add('R'); } } break; } } System.out.println(adj.size()); for( int i=0;i<adj.size();i++) { System.out.print(adj.get(i)); } } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
426c4276e77b8c3eb9eb2160c441677a
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
//Author: Patel Rag import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); int n = fr.nextInt(); int[] dat = new int[n]; for(int i = 0; i < n; i++) dat[i] = fr.nextInt(); Vector<Integer> ans = new Vector<Integer>(); StringBuilder out = new StringBuilder();; int l = 0; int r = n - 1; while(r >= l) { if(dat[l] < dat[r]) { if(ans.isEmpty() || ans.lastElement() < dat[l]) { ans.add(dat[l]); out.append('L'); l++; } else if(ans.lastElement() < dat[r]) { ans.add(dat[r]); out.append('R'); r--; } else { break; } } else if(dat[l] > dat[r]) { if(ans.isEmpty() || ans.lastElement() < dat[r]) { ans.add(dat[r]); out.append('R'); r--; } else if(ans.lastElement() < dat[l]) { ans.add(dat[l]); out.append('L'); l++; } else { break; } } else if(ans.isEmpty() || ans.lastElement() < dat[l]) { Vector<Integer> v1 = new Vector<Integer>(); Vector<Integer> v2 = new Vector<Integer>(); StringBuilder s1 = new StringBuilder(); StringBuilder s2 = new StringBuilder(); v1.add(dat[l]); s1.append('L'); l++; v2.add(dat[r]); s2.append('R'); r--; while(l < n) { if(v1.lastElement() < dat[l]) { v1.add(dat[l]); s1.append('L'); l++; } else { break; } } while(r > -1) { if(v2.lastElement() < dat[r]) { v2.add(dat[r]); s2.append('R'); r--; } else { break; } } if(v1.size() >= v2.size()) { out.append(s1); ans.addAll(v1); } else { out.append(s2); ans.addAll(v2); } break; } else { break; } } System.out.println(out.length()); System.out.println(new String(out)); } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
917e4c22cf4374683af7a937b4306692
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import java.util.*; import java.io.*; public class IncreasingSubsequenceHard { // https://codeforces.com/contest/1157/problem/C2 public static void main(String[] args) throws IOException, FileNotFoundException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader("IncreasingSubsequenceHard")); int n = Integer.parseInt(in.readLine()); StringTokenizer st = new StringTokenizer(in.readLine()); int[] arr = new int[n]; for (int i=0; i<n; i++) arr[i] = Integer.parseInt(st.nextToken()); ArrayList<Character> ans = new ArrayList<>(); int leftpos=0; int rightpos=n-1; int lastval=0; boolean did_something=true; while (did_something) { did_something=false; if (leftpos > rightpos) break; if (arr[leftpos] == arr[rightpos]) break; if (arr[leftpos] < arr[rightpos] && arr[leftpos] > lastval) { lastval = arr[leftpos]; ans.add('L'); leftpos++; did_something=true; } else if (arr[leftpos] > arr[rightpos] && arr[rightpos] > lastval) { lastval = arr[rightpos]; ans.add('R'); rightpos--; did_something=true; } else if (lastval >= arr[leftpos] && lastval < arr[rightpos]) { lastval = arr[rightpos]; ans.add('R'); rightpos--; did_something=true; } else if (lastval >= arr[rightpos] && lastval < arr[leftpos]) { lastval = arr[leftpos]; ans.add('L'); leftpos++; did_something=true; } } if (leftpos == rightpos && arr[leftpos] > lastval) { ans.add('L'); } if (leftpos<rightpos && arr[leftpos] == arr[rightpos] && arr[leftpos] > lastval) { int max=1; boolean leftside=true; int last = arr[leftpos]; int leftcount=1; for (int i=leftpos+1; i<rightpos; i++) { if (arr[i] > last) { leftcount++; last = arr[i]; } else break; } last = arr[rightpos]; int rightcount=1; for (int i=rightpos-1; i>leftpos; i--) { if (arr[i] > last) { rightcount++; last = arr[i]; } else break; } if (leftcount >= rightcount) { max = leftcount; } else { max = rightcount; leftside = false; } if (leftside) { for (int i=0; i<max; i++) { ans.add('L'); } } else { for (int i=0; i<max; i++) { ans.add('R'); } } } System.out.println(ans.size()); for (int i=0; i<ans.size(); i++) { System.out.print(ans.get(i)); } } } // static int ans; // public static void function (int[] arr, int leftpos, int rightpos, int curlength, int lastval) { // ans = Math.max(ans, curlength); // if (leftpos > rightpos) return; // if (arr[leftpos] <= lastval && arr[rightpos] <= lastval) { // return; // } // boolean did_something=true; // while (did_something) { // did_something=false; // if (leftpos > rightpos) break; // if (arr[leftpos] == arr[rightpos]) break; // if (arr[leftpos] < arr[rightpos] && arr[leftpos] > lastval) { // lastval = arr[leftpos]; // curlength++; // leftpos++; // did_something=true; // } // else if (arr[leftpos] > arr[rightpos] && arr[rightpos] > lastval) { // lastval = arr[rightpos]; // curlength++; // rightpos--; // did_something=true; // } // else if (lastval >= arr[leftpos] && lastval < arr[rightpos]) { // lastval = arr[rightpos]; // curlength++; // rightpos--; // did_something=true; // } // else if (lastval >= arr[rightpos] && lastval < arr[leftpos]) { // lastval = arr[leftpos]; // curlength++; // leftpos++; // did_something=true; // } // } // if (leftpos == rightpos && arr[leftpos] > lastval) { // curlength++; // ans = Math.max(ans, curlength); // return; // } // ans = Math.max(ans, curlength); // // if (arr[leftpos] == arr[rightpos] && arr[leftpos] > lastval) { // function(arr, leftpos+1, rightpos, curlength+1, arr[leftpos]); // function(arr, leftpos, rightpos-1, curlength+1, arr[leftpos]); // } // }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
cce06d9fc9ad1e83b85bf6178e0d5394
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
// Change Of Plans BABY.... Change Of Plans // import java.io.*; import java.util.*; import static java.lang.Math.*; public class increasingSubSequence { static void MainSolution() { n = ni(); int ar[] = new int[n]; for (int i = 0; i < n; i++) ar[i] = ni(); int l = 0, r = n - 1; ArrayList<Integer> ans = new ArrayList<>(); ans.add(0); StringBuilder sb = new StringBuilder(); while (l <= r) { if (ar[l] < ar[r]) { if (ar[l] > ans.get(ans.size() - 1)) { ans.add(ar[l]); l++; sb.append('L'); } else if (ar[r] > ans.get(ans.size() - 1)) { ans.add(ar[r]); r--; sb.append('R'); } else break; } else if (ar[r] < ar[l]) { if (ar[r] > ans.get(ans.size() - 1)) { ans.add(ar[r]); r--; sb.append('R'); } else if (ar[l] > ans.get(ans.size() - 1)) { ans.add(ar[l]); l++; sb.append('L'); } else break; } else if (ar[l] == ar[r] && ar[l] > ans.get(ans.size() - 1)) { int temp1 = 1, temp2 = 1; for (int i = l; i <= r - 1; i++) { if (ar[i] < ar[i + 1]) temp1++; else break; } for (int i = r; i > l; i--) { if (ar[i] < ar[i - 1]) temp2++; else break; } if (temp1 > temp2) { for (int i = 0; i < temp1; i++) { sb.append('L'); } } else { for (int i = 0; i < temp2; i++) { sb.append('R'); } } break; } else break; } pl(sb.length()); pl(sb); } /*----------------------------------------------------------------------------------------------------------------*/ //THE DON'T CARE ZONE BEGINS HERE...\\ static int mod9 = 1000000007; static int n, m, l, k, t, mod = 998244353; static AwesomeInput input = new AwesomeInput(System.in); static PrintWriter pw = new PrintWriter(System.out, true); static class AwesomeInput { private InputStream letsDoIT; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private AwesomeInput(InputStream incoming) { this.letsDoIT = incoming; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = letsDoIT.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } private long ForLong() { 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; } private String ForString() { 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 { boolean isSpaceChar(int ch); } } // functions to take input// static int ni() { return (int) input.ForLong(); } static String ns() { return input.ForString(); } static long nl() { return input.ForLong(); } static double nd() throws IOException { return Double.parseDouble(new BufferedReader(new InputStreamReader(System.in)).readLine()); } //functions to give output static void pl() { pw.println(); } static void p(Object o) { pw.print(o + " "); } static void pws(Object o) { pw.print(o + ""); } static void pl(Object o) { pw.println(o); } public static void main(String[] args) { //threading has been used to increase the stack size. new Thread(null, null, "Vengeance", 1 << 25) //the last parameter is stack size desired. { public void run() { try { double s = System.currentTimeMillis(); MainSolution(); //pl(("\nExecution Time : " + ((double) System.currentTimeMillis() - s) / 1000) + " s"); pw.flush(); pw.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
1ff4a0448b1350a35b61e2c88c81bf62
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
/** * @author cplayer on 2018/6/23. * @version 1.0 */ import java.util.*; import java.io.*; import java.lang.*; public class Main { public static void main(String[] args) { try { InputReader in; PrintWriter out; boolean useOutput = false; if (System.getProperty("ONLINE_JUDGE") == null) useOutput = true; if (useOutput) { FileInputStream fin = new FileInputStream(new File("src/data.in")); in = new InputReader(fin); FileOutputStream fout = new FileOutputStream(new File("src/data.out")); out = new PrintWriter(fout); } else { InputStream inputStream = System.in; in = new InputReader(inputStream); OutputStream outputStream = System.out; out = new PrintWriter(outputStream); } Solver solver = new Solver(in, out); solver.solve(); out.close(); } catch (Exception e) { e.printStackTrace(); } } static class Solver { private InputReader cin; private PrintWriter cout; Solver (InputReader cin, PrintWriter cout) { this.cin = cin; this.cout = cout; } public void solve () { try { int n = cin.nextInt(); int arr[] = new int[n]; int left, right; for (int i = 0; i < n; ++i) { arr[i] = cin.nextInt(); } List<Integer> steps = new LinkedList<>(); int curElement = 0; left = 0; right = n - 1; while (left <= right) { int leftEle = arr[left], rightEle = arr[right]; if (curElement < leftEle && curElement < rightEle) { if (leftEle == rightEle) { int leftLen = 1, rightLen = 1; while (left + leftLen <= right && arr[left + leftLen] > arr[left + leftLen - 1]) leftLen++; while (right - rightLen >= left && arr[right - rightLen] > arr[right - rightLen + 1]) rightLen++; if (leftLen > rightLen) { steps.add(0); curElement = arr[left]; left++; } else { curElement = arr[right]; steps.add(1); right--; } } else if (leftEle < rightEle) { steps.add(0); curElement = arr[left]; left++; } else { curElement = arr[right]; steps.add(1); right--; } } else if (curElement >= leftEle && curElement < rightEle) { steps.add(1); curElement = arr[right]; right--; } else if (curElement < leftEle && curElement >= rightEle) { steps.add(0); curElement = arr[left]; left++; } else { break; } } cout.println(steps.size()); StringBuilder sb = new StringBuilder(); for (int i : steps) { char curstep = i == 0 ? 'L' : 'R'; sb.append(curstep); } cout.println(sb.toString()); } catch (RuntimeException e) { e.printStackTrace(); return; } catch (Exception e) { e.printStackTrace(); return; } } } 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 int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
2b4030e4e1725c365d9195aa33fba536
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class A { public static void main(String args[]){ Scanner in = new Scanner(System.in); int n = in.nextInt(); Deque<Integer> q = new LinkedList<Integer>(); for(int i=0;i<n;i++){ int x = in.nextInt(); q.add(x); } int l1=0,r1=0; char ch[]=new char[n]; int j=0; int l = -1; int cnt=0; while(!q.isEmpty()){ int fst = q.getFirst(); int lst = q.getLast(); if(lst==fst && q.size()>1&&lst>l){ int ls = -1; Iterator it = q.iterator(); Iterator itr = q.descendingIterator(); while(it.hasNext()){ int x=(Integer)it.next(); if(x>ls){ l1++; ls=x; } else break; } ls=-1; while(itr.hasNext()){ int x=(Integer)itr.next(); // System.out.print(x+" "); if(x>ls){ r1++; ls=x; } else break; } break; } else{ if(fst<=l && lst<=l) break; if(fst>l && lst>l){ if(fst<lst){ l=fst; cnt++; ch[j++]='L'; q.removeFirst(); } else{ cnt++; l=lst; ch[j++]='R'; q.removeLast(); } } else if(fst>l){ l=fst; cnt++; ch[j++]='L'; q.removeFirst(); } else if(lst>l){ l=lst; cnt++; ch[j++]='R'; q.removeLast(); } } } //System.out.println(l1 + " " + r1); System.out.println(cnt+Math.max(r1,l1)); for(int i=0;i<cnt;i++){ System.out.print(ch[i]); } if(l1>r1){ for(int i=0;i<l1;i++){ System.out.print('L'); } } else{ for(int i=0;i<r1;i++){ System.out.print('R'); } } } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
1c6a6e64e9e3a5e8672d322afe19cba2
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import java.util.Scanner; public class CFP { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int start = 0; int end = scan.nextInt(); int[] sequence = new int[end--]; for (int i=0; i<sequence.length; i++) { sequence[i] = scan.nextInt(); } char[] answer = new char[sequence.length+1]; int last = 0; int i; for (i=0; i<sequence.length; i++) { if (sequence[start] < sequence[end]) { if (sequence[start] > last) { last = sequence[start++]; answer[i] = 'L'; } else if (sequence[end] > last) { last = sequence[end--]; answer[i] = 'R'; } else { break; } } else if (sequence[end] < sequence[start]) { if (sequence[end] > last) { last = sequence[end--]; answer[i] = 'R'; } else if (sequence[start] > last) { last = sequence[start++]; answer[i] = 'L'; } else { break; } } else { if (sequence[start] > last) { int left = 1; int right = 1; if (start != end) { while (sequence[start+left] > sequence[start+left-1]) { left++; } while (sequence[end-right] > sequence[end-right+1]) { right++; } } if (left > right) { int limit = i+left; for (; i<limit; i++) { answer[i] = 'L'; } } else { int limit = i+right; for (; i<limit; i++) { answer[i] = 'R'; } } } break; } } System.out.println(i); System.out.println(String.copyValueOf(answer, 0, i)); } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
a8b3f06ba0f4435605cb5f143933241d
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; import java.math.BigInteger; public class C2 { public static void main(String[] args) throws Exception { FastScanner scanner = new FastScanner(); int n = scanner.nextInt(); int[] seq = scanner.nextIntArray(); int index = 0; char[] lr = new char[n]; int left = 0; int right = n - 1; int last = -1; while (left <= right) { // System.out.println(seq[left] + " " + seq[right] + " " + left + " " + right); if (seq[left] == seq[right] && left != right && seq[left] > last) { // System.out.println(seq[left] + " " + seq[right]); int v1, v2; v1 = v2 = 0; for (int i = left + 1; i <= right; i++) { if (seq[i] > seq[i - 1]) v1++; else break; } for (int i = right - 1; i >= left; i--) { if (seq[i + 1] < seq[i]) v2++; else break; } if (v1 > v2) { lr[index++] = 'L'; for (int i = 0; i < v1; i++) { lr[index++] = 'L'; } } else { lr[index++] = 'R'; for (int i = 0; i < v2; i++) { lr[index++] = 'R'; } } break; } int el; if (min(seq[left], seq[right]) > last) { el = min(seq[left], seq[right]); } else if (max(seq[left], seq[right]) > last){ el = max(seq[left], seq[right]); } else break; last = el; if (el == seq[left]) { left++; lr[index++] = 'L'; } else { right--; lr[index++] = 'R'; } } System.out.println(index); for (int i = 0; i < index; i++) { System.out.print(lr[i]); } System.out.println(); } private static class FastScanner { private BufferedReader br; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public int[] nextIntArray() throws IOException { String line = br.readLine(); String[] strings = line.trim().split("\\s+"); int[] array = new int[strings.length]; for (int i = 0; i < array.length; i++) array[i] = Integer.parseInt(strings[i]); return array; } public int nextInt() throws IOException { return Integer.parseInt(br.readLine()); } } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
fc99faf81aa6e32c896ae0e79a8666a7
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class test { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); InputReader in = new InputReader(inputStream); // // for(int i=4;i<=4;i++) { // String f = i+".in"; // InputStream uinputStream = new FileInputStream("leftout.in"); // InputStream uinputStream = new FileInputStream(f); // InputReader in = new InputReader(uinputStream); // PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("leftout.out"))); Task t = new Task(); t.solve(in, out); out.close(); // } } static class Task { public void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;i++) { arr[i] = in.nextInt(); } StringBuilder sb = new StringBuilder(); int l=0;int r=n-1;int pre=0; while(l<r&&arr[l]!=arr[r]) { if(arr[l]<arr[r]) { if(arr[l]>pre) { sb.append("L"); pre = arr[l++]; }else if(arr[r]>pre) { sb.append("R"); pre = arr[r--]; }else { break; } }else { if(arr[r]>pre) { sb.append("R"); pre = arr[r--]; }else if(arr[l]>pre){ sb.append("L"); pre = arr[l++]; } else { break; } } } if(l==r) { if(arr[l]>pre) sb.append("R"); } else{ int c1=0; int c2=0; if(arr[l]>pre) { c1++; for(int i=l+1;i<=r;i++) { if(arr[i]>arr[i-1]) c1++; else break; } } if(arr[r]>pre) { c2++; for(int i=r-1;i>=l;i--) { if(arr[i+1]<arr[i]) c2++; else break; } } if(c1>=c2) { for(int i=0;i<c1;i++) sb.append("L"); }else { for(int i=0;i<c2;i++) sb.append("R"); } } out.println(sb.length()); out.println(sb.toString()); } } class BIT{ int arr[]; int n; public BIT(int a) { n=a; arr = new int[n]; } int sum(int p) { int s=0; while(p>0) { s+=arr[p]; p-=p&(-p); } return s; } void add(int p, int v) { while(p<n) { arr[p]+=v; p+=p&(-p); } } } // static class DSU{ // int[] arr; // int[] sz; // public DSU(int n) { // arr = new int[n]; // sz = new int[n]; // for(int i=0;i<n;i++) arr[i] = i; // Arrays.fill(sz, 1); // } // public int find(int a) { // if(arr[a]!=a) arr[a] = find(arr[a]); // return arr[a]; // } // public void union(int a, int b) { // int x = find(a); // int y = find(b); // if(x==y) return; // arr[x] = y; // sz[y] += sz[x]; // } // public int size(int x) { // return sz[find(x)]; // } // } static class MinHeap<Key> implements Iterable<Key> { private int maxN; private int n; private int[] pq; private int[] qp; private Key[] keys; private Comparator<Key> comparator; public MinHeap(int capacity){ if (capacity < 0) throw new IllegalArgumentException(); this.maxN = capacity; n=0; pq = new int[maxN+1]; qp = new int[maxN+1]; keys = (Key[]) new Object[capacity+1]; Arrays.fill(qp, -1); } public MinHeap(int capacity, Comparator<Key> c){ if (capacity < 0) throw new IllegalArgumentException(); this.maxN = capacity; n=0; pq = new int[maxN+1]; qp = new int[maxN+1]; keys = (Key[]) new Object[capacity+1]; Arrays.fill(qp, -1); comparator = c; } public boolean isEmpty() { return n==0; } public int size() { return n; } public boolean contains(int i) { if (i < 0 || i >= maxN) throw new IllegalArgumentException(); return qp[i] != -1; } public int peekIdx() { if (n == 0) throw new NoSuchElementException("Priority queue underflow"); return pq[1]; } public Key peek(){ if(isEmpty()) throw new NoSuchElementException("Priority queue underflow"); return keys[pq[1]]; } public int poll(){ if(isEmpty()) throw new NoSuchElementException("Priority queue underflow"); int min = pq[1]; exch(1,n--); down(1); assert min==pq[n+1]; qp[min] = -1; keys[min] = null; pq[n+1] = -1; return min; } public void update(int i, Key key) { if (i < 0 || i >= maxN) throw new IllegalArgumentException(); if (!contains(i)) { this.add(i, key); }else { keys[i] = key; up(qp[i]); down(qp[i]); } } private void add(int i, Key x){ if (i < 0 || i >= maxN) throw new IllegalArgumentException(); if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue"); n++; qp[i] = n; pq[n] = i; keys[i] = x; up(n); } private void up(int k){ while(k>1&&less(k,k/2)){ exch(k,k/2); k/=2; } } private void down(int k){ while(2*k<=n){ int j=2*k; if(j<n&&less(j+1,j)) j++; if(less(k,j)) break; exch(k,j); k=j; } } public boolean less(int i, int j){ if (comparator == null) { return ((Comparable<Key>) keys[pq[i]]).compareTo(keys[pq[j]]) < 0; } else { return comparator.compare(keys[pq[i]], keys[pq[j]]) < 0; } } public void exch(int i, int j){ int swap = pq[i]; pq[i] = pq[j]; pq[j] = swap; qp[pq[i]] = i; qp[pq[j]] = j; } @Override public Iterator<Key> iterator() { // TODO Auto-generated method stub return null; } } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int zcurChar; private int znumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (znumChars == -1) throw new InputMismatchException(); if (zcurChar >= znumChars) { zcurChar = 0; try { znumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (znumChars <= 0) return -1; } return buf[zcurChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } 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 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 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 nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class Dumper { static void print_int_arr(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_char_arr(char[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_double_arr(double[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_2d_arr(int[][] arr, int x, int y) { for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); System.out.println("---------------------"); } static void print_2d_arr(boolean[][] arr, int x, int y) { for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); System.out.println("---------------------"); } static void print(Object o) { System.out.println(o.toString()); } static void getc() { System.out.println("here"); } } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
4b53170e371c1d185c6d841dbe053183
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Ribhav */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); C2IncreasingSubsequenceHardVersion solver = new C2IncreasingSubsequenceHardVersion(); solver.solve(1, in, out); out.close(); } static class C2IncreasingSubsequenceHardVersion { public void solve(int testNumber, FastReader s, PrintWriter out) { int n = s.nextInt(), k = 0; int[] arr = s.nextIntArray(n); int[] a = new int[n]; a[n - 1] = 1; for (int i = n - 2; i >= 0; i--) { a[i] = 1; if (arr[i] < arr[i + 1]) { a[i] += a[i + 1]; } } int[] b = new int[n]; b[0] = 1; for (int i = 1; i < n; i++) { b[i] = 1; if (arr[i] < arr[i - 1]) { b[i] += b[i - 1]; } } int l = 0, r = n - 1, curr = 0; StringBuilder sb = new StringBuilder(); while (true) { if (l < n && r >= 0 && arr[l] > curr && arr[r] > curr) { if (arr[l] < arr[r]) { curr = arr[l]; sb.append('L'); l++; } else if (arr[l] > arr[r]) { curr = arr[r]; sb.append('R'); r--; } else { if (a[l] > b[r]) { curr = arr[l]; sb.append('L'); l++; } else { curr = arr[r]; sb.append('R'); r--; } } } else if (l < n && arr[l] > curr) { curr = arr[l]; sb.append('L'); l++; } else if (r >= 0 && arr[r] > curr) { curr = arr[r]; sb.append('R'); r--; } else { break; } k++; } out.println(k); out.println(sb); // out.println(ans.length() + "\n" + ans.reverse().toString()); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
51ce32fa4279cd380db75c9c07cc3800
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
// Utilities import java.io.*; import java.util.*; public class Main { static int N; static Deque<Integer> dq = new ArrayDeque<Integer>(); static int max = -1; static Queue<Character> resList = new LinkedList<Character>(); static int length = 0; public static void main(String[] args) throws IOException { N = in.iscan(); for (int i = 0; i < N; i++) { dq.addLast(in.iscan()); } while (!dq.isEmpty()) { if (dq.peekFirst() < dq.peekLast()) { if (dq.peekFirst() > max) { max = dq.pollFirst(); length++; resList.add('L'); } else if (dq.peekLast() > max){ max = dq.pollLast(); length++; resList.add('R'); } else { break; } } else if (dq.peekFirst() > dq.peekLast()){ if (dq.peekLast() > max) { max = dq.pollLast(); length++; resList.add('R'); } else if (dq.peekFirst() > max) { max = dq.pollFirst(); length++; resList.add('L'); } else { break; } } else { // dq.peekFirst() == dq.peekLast() if (dq.peekFirst() <= max) { break; } Deque<Integer> clone = new ArrayDeque<Integer>(dq); Queue<Integer> q1 = new LinkedList<Integer>(); int last = -1; while (!clone.isEmpty()) { if (clone.peekFirst() > last) { last = clone.peekFirst(); q1.add(clone.pollFirst()); } else { break; } } clone = new ArrayDeque<Integer>(dq); Queue<Integer> q2 = new LinkedList<Integer>(); last = -1; while (!clone.isEmpty()) { if (clone.peekLast() > last) { last = clone.peekLast(); q2.add(clone.pollLast()); } else { break; } } if (q1.size() >= q2.size()) { length += q1.size(); for (int j = 0; j < q1.size(); j++) { resList.add('L'); } } else { length += q2.size(); for (int j = 0; j < q2.size(); j++) { resList.add('R'); } } break; } } out.println(length); while (!resList.isEmpty()) { out.print(resList.poll()); } out.println(); out.close(); } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static int gcd (int a, int b) { return b == 0 ? a : gcd (b, a % b); } public static int lcm (int a, int b) { return a * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static int fast_pow (int b, int x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
adde15f4ffa3d1d374e8a558db94e104
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import java.util.Scanner; public class CodeForces555C2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } StringBuilder sb = new StringBuilder(); int maxValue = 0; for (int i = 0, j = n - 1; i <= j; ) { if (a[i] < a[j]) { if (a[i] > maxValue) { sb.append("L"); maxValue = a[i]; i++; } else if (a[j] > maxValue) { sb.append("R"); maxValue = a[j]; j--; } else { break; } } else if (a[i] > a[j]) { if (a[j] > maxValue) { sb.append("R"); maxValue = a[j]; j--; } else if (a[i] > maxValue) { sb.append("L"); maxValue = a[i]; i++; } else { break; } } else { if (i == j) { if (a[i] > maxValue) { sb.append("L"); } break; } else { if (a[i] <= maxValue) { break; } int k, m; for (k = i; k < j; k++) { if (a[k + 1] <= a[k]) { break; } } for (m = j; m > i; m--) { if (a[m - 1] <= a[m]) { break; } } if (k - i > j - m) { for (int x = 0; x <= k - i; x++) { sb.append("L"); } } else { for (int x = 0; x <= j - m; x++) { sb.append("R"); } } break; } } } System.out.println(sb.length() + "\n" + sb); } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
f15e90ffbb02ce79605a592134e81ca8
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
256 megabytes
import java.util.*; public class Codechef { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int p = n; int[] seq = new int[n]; int i = 0; StringBuilder str=new StringBuilder(""); int prev = 0; int m=0; int a=0; int b = 0; int v = 0; int q = 0; for(i=0;i<n;i++) { seq[i] = sc.nextInt(); } while(n-m>1) { if(prev<seq[m] || prev<seq[n-1]) { if(prev < seq[m] && prev < seq[n-1]) { if(seq[m] == seq[n-1]) { // System.out.println("equal"); if(seq[m] > seq[m+1] && seq[n-2] < seq[m]) { str.append("L"); break; } else if(seq[m] < seq[m+1] && seq[m] < seq[n-2]) { v = m; q = n; while(seq[v]<seq[v+1]) { a = a+1; v++; } while(seq[q-1]<seq[q-2]) { b++; q--; } if(a>b) { prev = seq[m]; str.append("L"); m=m+1; } else { str.append("R"); prev = seq[n-1]; n=n-1; } } else { if(seq[m] >= seq[m+1]) { str.append("R"); prev = seq[n-1]; n=n-1; } else { prev = seq[m]; str.append("L"); m=m+1; } } } else { if(seq[m]<seq[n-1]) { prev = seq[m]; str.append("L"); m=m+1; } else { str.append("R"); prev = seq[n-1]; n = n-1; } } } else { if(prev >= seq[m]) { str.append("R"); prev = seq[n-1]; n =n-1; } else { // System.out.println("her"); str.append("L"); prev = seq[m]; m=m+1; } } } else { break; } } if(n-m==1 && seq[m] == p) { if(prev<seq[m]) { // System.out.println("P"); str.append("L"); } } System.out.println(str.length()); System.out.println(str); } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
8226046b0849cfb5a38a5a7c4792c3a4
train_003.jsonl
1556289300
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).
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 Main { public static void main (String[] args) throws java.lang.Exception { Scanner s=new Scanner(System.in); int n=s.nextInt(); int[] a=new int[n]; int temp=0; ArrayList<Character> c = new ArrayList<Character>(); int j=0; int i=0; int k=0; int count=0; for(int z=0;z<n;z++) { a[z]=s.nextInt(); } while(i<n-1-k) { if(a[i]>temp){ if(a[i]==a[n-1-k]) { count=1; // System.out.println("wow"+a[i]); int l1=0; int l2=0; while(i<(n-1)) { if(a[i+1]>a[i]) l1++; else if(a[i]==a[i+1]){ break; } else break; i++; } while(k<n-1) { if(a[n-k-1]<a[n-k-2]) l2++; else if(a[n-k-2]==a[n-k-1]){ break; } else break; k++; } // System.out.println("one"+l1); // System.out.println("two"+l2); if(l1>l2) { for(int q=0;q<=l1;q++){ // System.out.println("wow"); c.add('L'); j++; } } else { for(int q=0;q<=l2;q++){ c.add('R'); j++; } } break; } } if(a[i]<a[n-1-k]){ if(a[i]>temp){ // System.out.println("wow1"); temp=a[i]; c.add('L'); i++; j++; } else if(a[n-1-k]>temp){ temp=a[n-k-1]; c.add('R'); k++; j++; } else break; } else{ if(a[n-1-k]>temp){ temp=a[n-k-1]; c.add('R'); k++; j++; } else if(a[i]>temp) { // System.out.println("wow2"); temp=a[i]; c.add('L'); i++; j++; } else break; } } if(count==0){ if(i==n-k-1&&a[i]>temp){ //System.out.println("wow"); c.add('L'); j++; } } System.out.println(j); for(int z=0;z<j;z++){ System.out.print(c.get(z)); } } }
Java
["5\n1 2 4 3 2", "7\n1 3 5 6 5 4 2", "3\n2 2 2", "4\n1 2 4 3"]
2 seconds
["4\nLRRR", "6\nLRLRRR", "1\nR", "4\nLLRR"]
NoteThe first example is described in the problem statement.
Java 8
standard input
[ "greedy" ]
1ae1e051b6c8240eb27c64ae05c342cf
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,700
In the first line of the output print $$$k$$$ β€” the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.
standard output
PASSED
12e0484ac6051c56e6d1d8d930ac969b
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.regex.PatternSyntaxException; public class PartialTeacher { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Scanner nex = new Scanner (new InputStreamReader(System.in)); int numOfStudents = Integer.parseInt(in.readLine()); int[] toffes = new int[numOfStudents]; // initialization: for (int i = 0; i < toffes.length; i++) { toffes[i] = 1; } // String divisionForEachStd = in.readLine(); char [] divisionForEachStd = in.readLine().toCharArray(); // int studentI=0; for (int i = 0; i < divisionForEachStd.length ; i++) { if (divisionForEachStd[i] == 'L') { if(toffes[i+1]>=toffes[i]) toffes[i] = toffes[i+1]+1; // now check for all the previous erntries if (i > 0) { for (int j = i - 1; j >= 0; j--) { if(divisionForEachStd[j]=='L'){ if(toffes[j+1]>=toffes[j]) toffes[j]= toffes[j+1]+1; } if(divisionForEachStd[j]=='='){ toffes[j]=toffes[j+1]; } } } } if (divisionForEachStd[i]=='R'){ if(toffes[i+1]<=toffes[i]) toffes[i+1]=toffes[i]+1; } if(divisionForEachStd[i]=='='){ // toffes[i+1]=toffes[i]=Math.max(toffes[i], toffes[i+1]); toffes[i+1]=toffes[i]; } } for (int i=0; i < toffes.length;i++){ System.out.print(toffes[i]+" "); } } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
e2c9a761006908ab898e44294671b8b7
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
//package manthan; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static String nextToken() throws IOException{ while (st==null || !st.hasMoreTokens()){ String s = bf.readLine(); if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } static int nextInt() throws IOException{ return Integer.parseInt(nextToken()); } static String nextStr() throws IOException{ return nextToken(); } static double nextDouble() throws IOException{ return Double.parseDouble(nextToken()); } public static void main(String[] args) throws IOException{ int n = nextInt(); byte s[] = nextStr().getBytes(); int a[] = new int[n]; a[0] = 1; for (int i=0; i<n-1; i++){ if (s[i]=='L'){ if (a[i] == 1) a[i+1] = 0; else a[i+1] = 1; } else if (s[i] == 'R') a[i+1] = a[i]+1; else a[i+1] = a[i]; if (a[i+1] == 0){ a[i+1] = 1; for (int j=i; j>=0; j--) if (s[j]=='L' && a[j]<=a[j+1]) a[j] = a[j+1]+1; else if (s[j]=='=' && a[j]!=a[j+1]) a[j] = a[j+1]; } } int min = 1; for (int i=0; i<n; i++) min = Math.min(min, a[i]); int d = 1-min; for (int i=0; i<n; i++){ out.print(a[i]+d); out.print(' '); } out.flush(); } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
d7de555121418904c5a9d470edbd41f1
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.io.*; import java.util.*; /** * Manthan 2011, A * @author Roman Kosenko <madkite@gmail.com> */ public class PartialTeacher { public static int[] solve(char[] signature) { int result[] = new int[signature.length + 1], v = 1; for(int i = signature.length; i > 0; i--) { switch(signature[i - 1]) { case 'L': result[i] = v++; break; case '=': result[i] = v; break; case 'R': result[i] = v; v = 1; break; } } result[0] = v; for(int i = 0; i < signature.length; i++) { switch(signature[i]) { case 'R': result[i + 1] = Math.max(result[i + 1], result[i] + 1); break; case '=': result[i + 1] = result[i + 1] = result[i]; break; } } return result; } public static void main(String[] args) throws IOException { File file = new File("input.txt"); if(file.exists()) System.setIn(new FileInputStream(file)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String s = br.readLine(); assert s.length() == n - 1 && s.matches("[LR=]+"); System.out.println(Arrays.toString(solve(s.toCharArray())).replaceAll("[\\[\\],]", "")); } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
8622c9533b1dc09e59e3b6c06fbc83df
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class C_61A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s = sc.next(); int []a = new int [n]; Arrays.fill(a, 1); for(int j = 0; j<=n; j++) for (int i = 0; i < n-1; i++) { char c = s.charAt(i); if (c == '='){ a[i] = a[i+1] = Math.max(a[i], a[i+1]); }else{ if (c == 'R'){ if (a[i] >= a[i+1]) a[i+1] = a[i]+1; } if (c == 'L'){ if (a[i] <= a[i+1]) a[i] = a[i+1]+1; } } } for (int i = 0; i < a.length; i++) { System.out.print(a[i]+" "); } } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
1f60b6a222e6ab842b06897c360ddf17
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.util.Arrays; /** * Created by IntelliJ IDEA. * User: piyushd * Date: 3/13/11 * Time: 9:43 PM * To change this template use File | Settings | File Templates. */ public class Task1 { void run(){ int n = nextInt(); String comp = next(); int[] a = new int[n]; Arrays.fill(a, 1); for (int i = 0; i < n; i++) { for (int j = 0; j < n - 1; j++) { if (comp.charAt(j) == 'L' && a[j] <= a[j + 1]) { a[j] = a[j + 1] + 1; } else if (comp.charAt(j) == 'R' && a[j + 1] <= a[j]) { a[j + 1] = a[j] + 1; } else if (comp.charAt(j) == '=') { a[j + 1] = a[j] = Math.max(a[j], a[j + 1]); } } } for (int i = 0; i < n; i++) System.out.print(a[i] + " "); System.out.println(); } int nextInt(){ try{ int c = System.in.read(); if(c == -1) return c; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return c; } if(c == '-') return -nextInt(); int res = 0; do{ res *= 10; res += c - '0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c = System.in.read(); if(c == -1) return -1; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return -1; } if(c == '-') return -nextLong(); long res = 0; do{ res *= 10; res += c-'0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(Character.isWhitespace(c)) c = System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(c == '\r' || c == '\n') c = System.in.read(); do{ res.append((char)c); c = System.in.read(); }while(c != '\r' && c != '\n'); return res.toString(); }catch(Exception e){ return null; } } public static void main(String[] args){ new Task1().run(); } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
fed975ba7f4a2267edd8cdd1342c8cc1
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.util.Arrays; /** * Created by IntelliJ IDEA. * User: piyushd * Date: 3/13/11 * Time: 9:43 PM * To change this template use File | Settings | File Templates. */ public class Task1 { void run(){ int n = nextInt(); String comp = next(); int[] a = new int[n]; Arrays.fill(a, 1); for(int i = 0; i < n; i++){ for(int j = 0; j < n - 1; j++){ if(comp.charAt(j) == 'L' && a[j] <= a[j + 1]){ a[j] = a[j + 1] + 1; }else if(comp.charAt(j) == 'R' && a[j + 1] <= a[j]){ a[j + 1] = a[j] + 1; }else if(comp.charAt(j) == '='){ a[j + 1] = a[j] = Math.max(a[j], a[j + 1]); } } } for(int i = 0; i < n; i++) System.out.print(a[i] + " "); System.out.println(); } int nextInt(){ try{ int c = System.in.read(); if(c == -1) return c; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return c; } if(c == '-') return -nextInt(); int res = 0; do{ res *= 10; res += c - '0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c = System.in.read(); if(c == -1) return -1; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return -1; } if(c == '-') return -nextLong(); long res = 0; do{ res *= 10; res += c-'0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(Character.isWhitespace(c)) c = System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(c == '\r' || c == '\n') c = System.in.read(); do{ res.append((char)c); c = System.in.read(); }while(c != '\r' && c != '\n'); return res.toString(); }catch(Exception e){ return null; } } public static void main(String[] args){ new Task1().run(); } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
b3dfb23e540a09f59cc76350652fa818
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class CF1 { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); int []A = new int[n]; Arrays.fill(A,1); String s = in.readLine(); //System.out.println(s.length()); for (int j = 0; j < n; j++) { for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == 'L' && A[i] <= A[i + 1]) A[i]++; if (s.charAt(i) == 'R' && A[i] >= A[i + 1]) A[i + 1]++; if (s.charAt(i) == '=') { A[i] = A[i + 1] = Math.max(A[i], A[i + 1]); } } } for (int i = 0; i < A.length-1; i++) { System.out.print(A[i]+" "); } System.out.println(A[A.length-1]); } } /*import java.io.*; import java.util.*; public class CF1 { public static void main(String[] args) throws IOException { BufferedReader scan = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.valueOf(scan.readLine()); int[] a = new int[1005]; a[1] = 1; int max = 1; int min = 1; String str = scan.readLine(); int sum = 1; for (int i=0;i<=n-2;i++) { if (str.charAt(i)=='=') a[i+2] = a[i+1]; else if (str.charAt(i)=='L') a[i+2] = a[i+1] - 1; else a[i+2] = a[i+1] + 1; if (a[i+2]>max) max = a[i+2]; if (a[i+2]<min) min = a[i+2]; sum = sum + a[i+2]; } int addnum = -min+1; System.out.print(a[1]+addnum); for (int i=2;i<=n;i++) { System.out.print(" "); System.out.print(a[i]+addnum); } System.out.println(); } }*/
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
cab0851d0881422d90f52d4ade6a260a
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import static java.lang.Math.*; import static java.lang.System.currentTimeMillis; import static java.lang.System.exit; import static java.lang.System.arraycopy; import static java.util.Arrays.sort; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) { } new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); private void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(); char[] s = nextLine().toCharArray(); int[] num = new int[n]; fill(num, 1); for (int i = 1; i < n; i++) { if (s[i - 1] == '=') num[i] = num[i - 1]; if (s[i - 1] == 'R') num[i] = num[i - 1] + 1; if (s[i - 1] == 'L' && num[i - 1] <= num[i]) { int j = i; while (j > 0 && s[j - 1] != 'R') { if (s[j - 1] == 'L') if (num[j - 1] > num[j]) break; else num[j - 1] = num[j] + 1; else num[j - 1] = num[j]; j--; } } } for (int i = 0; i < n; i++) { out.print(num[i] + " "); } out.println(); in.close(); out.close(); } void chk(boolean b) { if (b) return; System.out.println(new Error().getStackTrace()[1]); exit(999); } void deb(String fmt, Object... args) { System.out.printf(Locale.US, fmt + "%n", args); } String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
802fb8391e19cd3dfa807db3087f8444
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class p67a { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); char[] x = in.next().toCharArray(); int[] res = new int[n]; Arrays.fill(res, 1); while(true) { boolean change = false; for (int i = 0; i < x.length; i++) { if(x[i] == '=' && res[i] != res[i+1] ) { res[i] = res[i+1] = Math.max(res[i], res[i+1]); change = true; continue; } if(x[i] == 'R' && res[i] >= res[i+1]) { res[i+1] = res[i]+1; change = true; } if(x[i] == 'L' && res[i+1] >= res[i]) { res[i] = res[i+1]+1; change = true; } } if(!change) { break; } } for (int i = 0; i < res.length; i++) { System.out.print(res[i]+" "); } } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
f3f04bf9fc5c9db0ff53321c55f03160
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class Solution { static int[] a; static String s; public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(in.nextLine()); s = in.nextLine(); a = new int[n]; a[0] = 1; for (int i = 0; i < n - 1; i++) { char c = s.charAt(i); switch (c) { case 'L': a[i + 1] = 1; norm(i + 1); break; case 'R': a[i + 1] = a[i] + 1; break; default: a[i + 1] = a[i]; } } for (int i = 0; i < n; i++) out.print(a[i] + " "); out.close(); } private static void norm(int init) { int curr = init; while (curr > 0 && !isOk(curr)) { curr--; a[curr]++; } } private static boolean isOk(int i) { switch (s.charAt(i - 1)) { case 'L': return a[i] < a[i - 1]; case 'R': return a[i] > a[i - 1]; default: return a[i] == a[i - 1]; } } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
5f13c4e07ff9bad88053897b34f93408
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.io.BufferedInputStream; import java.util.Random; import java.util.Scanner; public class PartialTeacher { public static void main(String[] args) { Scanner scn = new Scanner(new BufferedInputStream(System.in)); int n = scn.nextInt(); String s = scn.next(); int[] res = solve(n, s); for(int t: res) { System.out.print(t + " "); } } private static int[] solve(int n, String s) { int[] res = new int[n]; res[0] = 1; for(int i = 0; i < n-1; ++i) { if (s.charAt(i) == '=') { res[i+1] = res[i]; continue; } if (s.charAt(i) == 'L') { res[i+1] = 1; if (res[i] == 1) { int j = i; while (j >= 0 && s.charAt(j) != 'R' && res[j] <= res[j+1]) { res[j] = res[j] + 1; --j; } } } if (s.charAt(i) == 'R') { res[i+1] = res[i] + 1; } } return res; } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
da7824c4ba6bf630b28b35a753967832
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) {} new Main().run(); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); int N; char[] a; int[] ans; void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); N = nextInt(); a = nextToken().toCharArray(); ans = new int [N]; fill(ans, 1); for (;;) { boolean changed = false; for (int i = 1; i < N; i++) { int cmp = a[i - 1]; if (cmp == 'L') { if (ans[i - 1] <= ans[i]) { ans[i - 1] = ans[i] + 1; changed = true; break; } } else if (cmp == '=') { if (ans[i - 1] < ans[i]) { ans[i - 1]++; changed = true; break; } else if (ans[i - 1] > ans[i]) { int max = max(ans[i - 1], ans[i]); ans[i] = max; ans[i - 1] = max; changed = true; break; } } else { if (ans[i - 1] >= ans[i]) { ans[i] = ans[i - 1] + 1; changed = true; break; } } } if (!changed) break; } for (int i = 0; i < N; i++) { if (i > 0) out.print(' '); out.print(ans[i]); } out.println(); out.close(); } /*************************************************************** * Input **************************************************************/ String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
c36d22639814bcb0c6d89637ebc7e326
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Manthan2011_A implements Runnable { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws IOException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } @Override public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } public static void main(String[] args) { new Thread(new Manthan2011_A()).start(); } void solve() throws IOException { int n = readInt(); String s = readString(); int[] b = new int[n-1]; for (int i = 0; i < n-1; i++) { if (s.charAt(i) == 'L') b[i] = -1; if (s.charAt(i) == 'R') b[i] = 1; if (s.charAt(i) == '=') b[i] = 0; } int[] a = new int[n]; a[0] = 1; for (int i = 1; i < n; i++) { if (b[i-1] == 1) { a[i] = a[i-1] + 1; continue; } if (b[i-1] == -1) { a[i] = 1; for (int j = i-1; j >= 0; j--) { if (a[j] == a[j+1] && b[j] == -1) a[j]++; else if (b[j] == 0) a[j] = a[j+1]; else break; } continue; } if (b[i-1] == 0) { a[i] = a[i-1]; continue; } throw new RuntimeException(); } for (int i = 0; i < n; i++) { out.print(a[i] + " "); } } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
84435dcea44c96a50c171482834b0776
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; import java.util.Scanner; public class Main { private static StreamTokenizer in; private static PrintWriter out; private static BufferedReader inB; private static int nextInt() throws Exception{ in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception{ in.nextToken(); return in.sval; } static{ out = new PrintWriter(System.out); inB = new BufferedReader(new InputStreamReader(System.in)); in = new StreamTokenizer(inB); } public static void main(String[] args)throws Exception { int n = Integer.parseInt(inB.readLine()); char[] c = inB.readLine().toCharArray(); int[] L = new int[n], R = new int[n]; int count = 0; for(int i = n-2; i>=0; i--) { if(c[i] == 'R') { count = 0; L[i] = 0; } else if(c[i] == '=') { L[i] = L[i+1]; } else L[i] = ++count; } count = 0; for(int i = 0; i<n-1; i++) { if(c[i] == 'L') { count = 0; R[i+1] = 0; } else if(c[i] == '=') { R[i+1] = R[i]; } else R[i+1] = ++count; } for(int i = 0 ;i<n; i++) { out.print(Math.max(L[i], R[i]) + 1 + " "); } out.println(); out.flush(); } ///////////////////////////////////////////////////////////////// private static void println(Object o) throws Exception { System.out.println(o); } private static void exit(Object o) throws Exception { println(o); exit(); } private static void exit() { System.exit(0); } ////////////////////////////////////////////////////////////////// }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
23c662b9c4006f4d9034098da566cede
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package a; /** * * @author ΠšΠ°Ρ‚Π΅Ρ€ΠΈΠ½Π° */ import java.io.*; import java.util.*; public class Main { public static void main(String args[]) throws IOException { boolean online = System.getProperty("ONLINE_JUDGE") != null; Scanner in = online ? new Scanner(System.in) : new Scanner(new FileReader("input.txt")); PrintWriter out = online ? new PrintWriter(System.out) : new PrintWriter(new FileWriter("output.txt")); int n = in.nextInt(); String s = in.next(); char a[] = new char[n]; int l[] = new int[n]; int r[] = new int[n]; for (int i=0; i<n-1; i++) a[i] = s.charAt(i); l[0] = 1; for (int i=0; i<n-1; i++) switch (a[i]) { case 'R': l[i+1] = l[i] + 1; break; case 'L': l[i+1] = 1; break; case '=': l[i+1] = l[i]; break; } r[n-1] = 1; for (int i=n-2; i>=0; i--) switch (a[i]) { case 'R': r[i] = 1; break; case 'L': r[i] = r[i+1]+1; break; case '=': r[i] = r[i+1]; break; } for(int i=0;i<n;i++) out.print(Math.max(l[i], r[i]) + " "); out.flush(); return; } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
1c3b515bad842bdbfaf588f5e84342c1
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.io.*; import java.util.*; public class Cf_Man_A { public static void main( String[ ] args ) throws Throwable { BufferedReader bIn = new BufferedReader ( new InputStreamReader( System.in ) ); PrintStream out = new PrintStream( System.out ); int n = Integer.parseInt( bIn.readLine( ) ); char lr[ ] = bIn.readLine( ).toCharArray( ); int a[ ] = new int[ n ]; Arrays.fill( a, 1 ); boolean f = true; while ( f ) { f = false; for ( int i = 0; i < n - 1; ++i ) { if ( lr[ i ] == 'L' ) { if ( a[ i ] <= a[ i + 1 ] ) { a[ i ] = a[ i + 1 ] + 1; f = true; } } else if ( lr[ i ] == 'R' ) { if ( a[ i ] >= a[ i + 1 ] ) { a[ i + 1 ] = a[ i ] + 1; f = true; } } else { if ( a[ i ] != a[ i + 1 ] ) { a[ i ] = a[ i + 1 ] = Math.max( a[ i ], a[ i + 1 ] ); f = true; } } } } for ( int i = 0; i < n; ++i ) { out.print( a[ i ] + " " ); } } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
cfcae6c38eef841577e29484fb647005
train_003.jsonl
1300033800
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.jar.JarEntry; /** * @author Vitaly Zubchevskiy * Created at 19:31 13.03.11 */ public class A { public static void main(String[] args) throws IOException { BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(is.readLine().trim()); String s = is.readLine().toUpperCase(); char[] chars = s.toCharArray(); int iris[] = new int[n]; int prev = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] == 'R') { setBack(chars, iris, prev, i); prev = i + 1; } } setBack(chars, iris, prev, chars.length); for (int i = 0; i < n; i++) { System.out.print(iris[i]); if (i < n - 1) System.out.print(" "); } System.out.println(); } private static void setBack(char[] chars, int[] iris, int start, int end) { iris[end] = 1; for(int j = end -1; j >= start; j--) { if(chars[j] == '=') iris[j] = iris[j+1]; else iris[j] = iris[j+1] + 1; } if (start != 0 && chars[start - 1] == 'R') { int diff = iris[start - 1] - iris[start] + 1; if (diff > 0) { int j = start; do iris[j++] += diff; while(j-1 < chars.length && chars[j-1] == '='); } } } }
Java
["5\nLRLR", "5\n=RRR"]
1 second
["2 1 2 1 2", "1 1 2 3 4"]
null
Java 6
standard input
[ "dp", "implementation", "greedy", "graphs" ]
8c2a6a29dc238b55d0bc99d7e203f1bf
The first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
1,800
Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
standard output
PASSED
b5d600ea8d4b419f38bfbfb9b4f8bf52
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
public class Easy { public static void main(String[]args) { java.util.Scanner input = new java.util.Scanner(System.in); int size = input.nextInt(); String[] s = new String[size]; for(int i=0 ; i<size ; i++) { s[i] = input.next(); } if(size==0 || size==1) { System.out.println("YES"); System.exit(0); } for(int i=((int)size/2)-1 ; i<size ; i++) { if(s[i].equals(s[size-1-i]) || s[i].equals(reverse(s[size-1-i]))) continue; else { System.out.println("NO"); System.exit(0); } } System.out.println("YES"); } public static String reverse(String x) { StringBuilder s = new StringBuilder(x); return s.reverse().toString(); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
0d6519ab6b1b729ae9b95364bbb122ac
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.Stack; import javafx.util.Pair; public class Ahmed { public static void main(String[] args) { Scanner input=new Scanner (System.in); int n=input.nextInt(); char [][]x=new char[n][n]; boolean c=true; for(int i=0;i<n;i++){ String s=input.next(); for(int j=0;j<n;j++){ x[i][j]=s.charAt(j); } } if (n==1){System.out.print("YES");} else{ for(int i=0;i<n;i++){ int count=0; for(int j=0;j<n;j++){ if(i==0&&j==0){ if(x[i+1][j]=='o'){ count++; } if(x[i][j+1]=='o'){ count++; } } else if(i==n-1&&j==n-1){ if (x[i-1][j]=='o'){ count++; } if(x[i][j-1]=='o'){ count++; } } else if(i==n-1&&j!=n-1&j!=0){ if (x[i-1][j]=='o'){ count++; } if(x[i][j-1]=='o'){ count++; } if(x[i][j+1]=='o'){ count++; } } else if(j==n-1&&i!=n-1&&i!=0){ if (x[i-1][j]=='o'){ count++; } if(x[i+1][j]=='o'){ count++; } if(x[i][j-1]=='o'){ count++; } } else if(i==0&j!=n-1&&j!=0){ if(x[i+1][j]=='o'){ count++; } if(x[i][j-1]=='o'){ count++; } if(x[i][j+1]=='o'){ count++; } } else if(j==0&&i!=0&&i!=n-1){ if (x[i-1][j]=='o'){ count++; } if(x[i+1][j]=='o'){ count++; } if(x[i][j+1]=='o'){ count++; } } else if(i==0&&j==n-1){ if(x[i+1][j]=='o'){ count++; } if(x[i][j-1]=='o'){ count++; } } else if(i==n-1&&j==0){ if (x[i-1][j]=='o'){ count++; } if(x[i][j+1]=='o'){ count++; } } else { if (x[i-1][j]=='o'){ count++; } if(x[i+1][j]=='o'){ count++; } if(x[i][j-1]=='o'){ count++; } if(x[i][j+1]=='o'){ count++; } } if(count%2!=0){c=false; break;} } if(!c){break;} } if(c){System.out.print("YES");} else{System.out.print("NO");} } } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
746fea820c1558db9f4f139c2bd52dcd
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
//package codeforces.codeforces.A; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String str="",s=""; for(int i=0;i<n;i++) { str=sc.next(); s+=str; } StringBuilder sb = new StringBuilder(s); sb=sb.reverse(); String st = sb.toString(); if(st.equals(s)) System.out.println("YES"); else System.out.println("NO"); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
5f76bd05516f5160dd998959abdff30e
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class ApplemanAndEasyTask { public static void main(String[] args) throws Exception { BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); int loop = Integer.parseInt(b.readLine()); char[][] c1 = new char[loop][loop]; for(int i = 0;i < c1.length;i++) { c1[i] = b.readLine().toCharArray(); } String str = "YES"; Label: { for (int i = 0; i < c1.length; i++) { for (int j = 0; j < c1[i].length; j++) { int count = 0; count = (i - 1 >= 0) ? (c1[i - 1][j] == 'o') ? ++count : count : count; count = (j - 1 >= 0) ? (c1[i][j - 1] == 'o') ? ++count : count : count; count = (j + 1 < c1[i].length) ? (c1[i][j + 1] == 'o') ? ++count : count : count; count = (i + 1 < c1.length) ? (c1[i + 1][j] == 'o') ? ++count : count : count; if (count % 2 != 0) { str = "NO"; break Label; } } } } System.out.println(str); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
ea786552b15507ec05b7151497abcde5
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.util.Scanner; public class WizardDuel { static int[] dx = { 1, 0, 0, -1 }; static int[] dy = { 0, 1, -1, 0 }; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); char[][] a = new char[n][n]; for (int i = 0; i < n; i++) { a[i] = sc.next().toCharArray(); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int sum = 0; for (int k = 0; k < 4; k++) { int x = dx[k] + j; int y = dy[k] + i; if (x >= 0 && y >= 0 && x < n && y < n) if (a[x][y] == 'o') sum++; } if (sum % 2 != 0 ) { System.out.println("NO"); return; } } } System.out.println("YES"); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
9418586f9db72139f520c9249f3ae396
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.util.Scanner; public class main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); char[][] a = new char[n][n]; for (int i = 0; i < n; i++) { String s = in.next(); for (int j = 0; j < n; j++) {//System.out.println(s.charAt(j)); a[i][j] = s.charAt(j); } } String ans = "YES"; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int c = 0; if (j != 0) { if (a[i][j - 1] == 'o') { c++; } } if (j != (n - 1)) { if (a[i][j + 1] == 'o') { c++; } } if (i != 0) { if (a[i - 1][j] == 'o') { c++; } } if (i != (n - 1)) { if (a[i + 1][j] == 'o') { c++; } } if(c%2 != 0){ans = "NO";break;} } } System.out.println(ans); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
5bd272a1ddfd964fc3e5604967fe275d
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.util.*; public class Alphabetanalyser { public static void main(String args[]){ Scanner in=new Scanner(System.in); int n=in.nextInt(); char array[][]=new char[n][n]; for(int i=0;i<n;i++){ String temp=in.next(); array[i]=temp.toCharArray(); } boolean flag=true; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ boolean forward=true; boolean backward=true; boolean upward=true; boolean downward=true; int count=0; if(i==0){ upward=false; } if(j==0){ backward=false; } if(i==n-1){ downward=false; } if(j==n-1){ forward=false; } if(forward){ if(j+1<n){ if(array[i][j+1]=='o') count++;} } if(backward){ if(array[i][j-1]=='o'){ count++;} } if(upward){ if(array[i-1][j]=='o') count++; } if(downward){ if(i+1<n){ if(array[i+1][j]=='o') count++;} } if(count%2!=0){ flag=false; break; } } if(!flag) break; } if(flag) System.out.println("YES"); else System.out.println("NO"); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
b3b182a43a165206d46414355ab8f10f
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.util.Scanner; public class JavaApplication79 { public static void main(String[] args) { Scanner s = new Scanner (System.in); boolean b=true; String x; int n=s.nextInt(),count=0; String ar[][]=new String [n][n]; for (int i = 0; i < n; i++) {x=s.next(); for (int j = 0; j < n; j++) { ar[i][j]=""+x.charAt(j); }} for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) {count=0; if ((i-1)>=0){if (ar[i-1][j].equalsIgnoreCase("o"))count++;} if ((i+1)<n){if (ar[i+1][j].equalsIgnoreCase("o"))count++;} if((j-1)>=0){if (ar[i][j-1].equalsIgnoreCase("o"))count++;} if ((j+1)<n){if(ar[i][j+1].equalsIgnoreCase("o"))count++;} if(count%2!=0){b=false;} } } if(b)System.out.println("YES"); else System.out.println("NO"); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
05d2276cc77eb958af234aa608919ba3
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static class ProblemSolver{ public void solveTheProblem(InputReader in,PrintWriter out){ //Take the necessary inputs int n=in.nextInt(); String[] board=new String[n]; for(int i=0;i<n;++i)board[i]=in.next(); //Evaluation and display of the result for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ int count=0; if(isFeasible(i-1, n)){ if(board[i-1].charAt(j)=='o')++count; } if(isFeasible(i+1, n)){ if(board[i+1].charAt(j)=='o')++count; } if(isFeasible(j-1, n)){ if(board[i].charAt(j-1)=='o')++count; } if(isFeasible(j+1, n)){ if(board[i].charAt(j+1)=='o')++count; } if(count%2!=0){ out.print("NO"); return; } } } out.print("YES"); } boolean isFeasible(int i,int n){ return (i>=0 && i<=n-1)?true:false; } } //Default template for all the codes 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()); } } //Main method for all the codes public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); ProblemSolver problemSolver = new ProblemSolver(); problemSolver.solveTheProblem(in, out); out.close(); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
73a62fd8885dea2e4f6714347463f162
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.util.*; public class tata { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.nextLine()); String[] board = new String[n]; for(int i=0;i<n;++i)board[i]=sc.nextLine(); for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ int count=0; if(isFeasible(i-1, n)){ if(board[i-1].charAt(j)=='o')++count; } if(isFeasible(i+1, n)){ if(board[i+1].charAt(j)=='o')++count; } if(isFeasible(j-1, n)){ if(board[i].charAt(j-1)=='o')++count; } if(isFeasible(j+1, n)){ if(board[i].charAt(j+1)=='o')++count; } if(count%2!=0){ System.out.print("NO"); return; } } } System.out.print("YES"); } static boolean isFeasible(int i,int n){ return (i>=0 && i<=n-1)?true:false; } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
0182d78222170976160fc2161eaf9114
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Locale; import java.util.StringTokenizer; public class A{ static StringTokenizer st; static BufferedReader br; static PrintWriter pw; static class Sort implements Comparable<Sort> { int x, y; public int compareTo(Sort arg0) { if (this.x != arg0.x) return this.x - arg0.x; else return this.y - arg0.y; } } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter( System.out))); int n = nextInt(); char a[][] = new char[n + 2][n + 2]; for (int i = 1; i <= n; i++) { String s = next(); for (int j = 1; j <= n; j++) a[i][j] = s.charAt(j - 1); } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { int cnt = 0; if (a[i + 1][j] == 'o') cnt++; if (a[i - 1][j] == 'o') cnt++; if (a[i][j + 1] == 'o') cnt++; if (a[i][j - 1] == 'o') cnt++; if (cnt % 2 == 1) { pw.print("NO"); pw.close(); return; } } } pw.print("YES"); pw.close(); } private static boolean f(BigInteger n) { BigInteger m = n.subtract(BigInteger.ONE); if (m.nextProbablePrime().equals(n)) return true; return false; } private static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } private static BigInteger npr(BigInteger n) { return n.nextProbablePrime(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
2bf1e7632df0fa0f60668a6a437c3717
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main{ public static void main(String []args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(in.readLine()); int counter = 0 ; String A[]=new String[t]; int x; boolean T = true; for (int i = 0 ; i < t ;i++) A[i]=in.readLine(); for (int i=0;i<t;i++) { for (int j = 0;j<t;j++) { { if(j<A.length-1) { if(A[i].charAt(j+1)=='o')counter++; } if(i<t-1) { if(A[i+1].charAt(j)=='o')counter++; } if (i>0) { if(A[i-1].charAt(j)=='o')counter++; } if(j>0) { if(A[i].charAt(j-1)=='o')counter++; } } if(counter%2!=0)T=false; counter=0; } } System.out.println((T)?"YES":"NO"); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
29700db7dda2dc8407c9e98db09f91fa
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main{ public static void main(String []args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(in.readLine()); int counter = 0 ; String A[]=new String[t]; int x; boolean T = true; for (int i = 0 ; i < t ;i++) A[i]=in.readLine(); for (int i=0;i<t;i++) { for (int j = 0;j<t;j++) { if(A[i].charAt(j)=='x' || A[i].charAt(j)=='o') { if(j<A.length-1) { if(A[i].charAt(j+1)=='o')counter++; } if(i<t-1) { if(A[i+1].charAt(j)=='o')counter++; } if (i>0) { if(A[i-1].charAt(j)=='o')counter++; } if(j>0) { if(A[i].charAt(j-1)=='o')counter++; } } if(counter%2!=0)T=false; counter=0; } } System.out.println((T)?"YES":"NO"); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
85eeff00e1d273ade017f9d2c8208252
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc=new Scanner(System.in); String s=sc.nextLine(); int n=Integer.parseInt(s); char[][] a=new char[n+1][n+1]; for(int i=0;i<n;i++) { String data=""; data=sc.next(); for(int j=0;j<n;j++) { a[i][j]=data.charAt(j); } } int cnt=0; for(int i=0;i<n;++i) { for(int j=0;j<n;++j) { if ((i-1)>=0 && a[i-1][j]=='o') cnt++; //right if ((j+1)<n && a[i][j+1]=='o') cnt++; //left if ((j-1)>=0 && a[i][j-1]=='o' ) cnt++; //bottom if ((i+1)<n && a[i+1][j]=='o') cnt++; if (cnt%2!=0) { System.out.println("NO"); return; } } } System.out.println("YES"); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
3bdecadc032e3b6859be4618fc2f18f4
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); char[][] arr = new char[t][t]; for (int i = 0; i < arr.length; i++) { String s = sc.next(); arr[i] = s.toCharArray(); } int count =0; boolean b = true; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { if(i != 0){ if(arr[i-1][j]=='o') count++; } if(j != 0){ if(arr[i][j-1]=='o') count++; } if(i != arr.length-1){ if(arr[i+1][j]=='o') count++; } if(j != arr.length-1){ if(arr[i][j+1]=='o') count++; } if(count%2 != 0){ b = false ; break; } } } if(b){ System.out.println("YES");} else System.out.println("NO"); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
f0e4569695bf82575ae40e4c4a18887d
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc= new Scanner (System.in); int n=sc.nextInt(); sc.nextLine(); char[] c; char[][] mat=new char[n][n]; if(n==1){ sc.nextLine(); System.out.println("YES"); return; } for(int i=0;i<n;i++){ c=sc.nextLine().toCharArray(); for(int j=0;j<n;j++){ mat[i][j]=c[j]; } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ //1ra if(i==0 && j==0){ if((mat[i+1][j]=='o' && mat[i][j+1]=='o') || (mat[i+1][j]=='x' && mat[i][j+1]=='x')){ continue; }else{ System.out.println("NO"); return; } } //2da if(i==0 && j!=0 && j!=n-1){ if((mat[i+1][j]=='o' && mat[i][j+1]=='o' && mat[i][j-1]=='x') || (mat[i][j-1]=='o' && mat[i][j+1]=='o' && mat[i+1][j]=='x') || (mat[i+1][j]=='o' && mat[i][j-1]=='o' && mat[i][j+1]=='x') || (mat[i+1][j]=='x' && mat[i][j+1]=='x' && mat[i][j-1]=='x')){ continue; }else{ System.out.println("NO"); return; } } //3ra if(i==0 && j==n-1){ if((mat[i+1][j]=='o' && mat[i][j-1]=='o') || (mat[i+1][j]=='x' && mat[i][j-1]=='x')){ continue; }else{ System.out.println("NO"); return; } } //4ta if(j==0 && i!=0 && i!=n-1){ if((mat[i-1][j]=='o' && mat[i][j+1]=='o' && mat[i+1][j]=='x') || (mat[i-1][j]=='o' && mat[i+1][j]=='o' && mat[i][j+1]=='x') || (mat[i+1][j]=='o' && mat[i][j+1]=='o'&& mat[i-1][j]=='x') || (mat[i-1][j]=='x' && mat[i][j+1]=='x' && mat[i+1][j]=='x') ){ continue; }else{ System.out.println("NO"); return; } } //5ta if(j==n-1 && i!=0 && i!=n-1){ if((mat[i-1][j]=='o' && mat[i][j-1]=='o' && mat[i+1][j]=='x') || (mat[i-1][j]=='o' && mat[i+1][j]=='o' && mat[i][j-1]=='x') || (mat[i+1][j]=='o' && mat[i][j-1]=='o' && mat[i-1][j]=='x') || (mat[i-1][j]=='x' && mat[i][j-1]=='x' && mat[i+1][j]=='x') ){ continue; }else{ System.out.println("NO"); return; } } //6ta if(i==n-1 && j==0){ if((mat[i-1][j]=='o' && mat[i][j+1]=='o') || (mat[i-1][j]=='x' && mat[i][j+1]=='x')){ continue; }else{ System.out.println("NO"); return; } } //7ma if(i==n-1 && j!=0 && j !=n-1){ if((mat[i][j-1]=='o' && mat[i-1][j]=='o' && mat[i][j+1]=='x') || (mat[i][j-1]=='o' && mat[i][j+1]=='o' && mat[i-1][j]=='x') || (mat[i-1][j]=='o' && mat[i][j+1]=='o' && mat[i][j-1]=='x') || (mat[i][j-1]=='x' && mat[i-1][j]=='x' && mat[i][j+1]=='x') ){ continue; }else{ System.out.println("NO"); return; } } //8va if(i==n-1 && j==n-1){ if((mat[i-1][j]=='o' && mat[i][j-1]=='o') || (mat[i-1][j]=='x' && mat[i][j-1]=='x')){ continue; }else{ System.out.println("NO"); return; } } //9na int cont=0; if(mat[i][j-1]=='o'){ cont++; } if(mat[i-1][j]=='o'){ cont++; } if(mat[i][j+1]=='o'){ cont++; } if(mat[i+1][j]=='o'){ cont++; } if(cont%2!=0){ System.out.println("NO"); return; } } } System.out.println("YES"); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
18aa0f11931fe9ca0277e383b0e34285
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.util.*; public class CF462A { public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); String s = ""; for (int i = 0; i < n; i++) s += scan.next(); String reverse = new StringBuilder(s).reverse().toString(); System.out.println((s.equals(reverse)) ? "YES" : "NO"); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
4b6ce01222750b9245bc08fdc6a07fb7
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.util.Scanner; public class Appleman{ public static void main(String args[]){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); char[][] matrix = new char[n+2][n+2]; matrix[0] = new char[n+2]; matrix[n+1] = new char[n+1]; for(int i=1;i<=n;i++){ matrix[i][0] = 'z'; matrix[i][n+1] = 'z'; int j=1; char[] next = scan.next().toCharArray(); for(char c : next){ matrix[i][j++] = c; } } for(int x=1;x<=n;x++){ for(int y=1;y<=n;y++){ int sum = 0; sum += matrix[x-1][y] == 'o' ? 1 : 0; sum += matrix[x+1][y]== 'o' ? 1 : 0; sum += matrix[x][y-1]== 'o' ? 1 : 0; sum += matrix[x][y+1]== 'o' ? 1 : 0; if(sum %2 != 0){ System.out.println("NO"); return; } } } System.out.println("YES"); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
1caa06340d960590bebea4182ca018cf
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.util.*; public class Problems { private static Scanner input; public static void main(String[] args) { int n,i,j,counter=0,flag=1; input = new Scanner(System.in); n=input.nextInt(); char[][] word=new char[n][n]; String[] board=new String[n]; for(i=0;i<n;i++) { board[i]=input.next(); for(j=0;j<n;j++) { word[i][j]=board[i].charAt(j); } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { counter=0; if(i+1!=n&&word[i+1][j]=='o') counter++; if(i-1>=0&&word[i-1][j]=='o') counter++; if(j+1!=n&&word[i][j+1]=='o') counter++; if(j-1>=0&&word[i][j-1]=='o') counter++; if(counter%2!=0) { flag=0; break; } } } if(flag==1) System.out.println("YES"); else System.out.println("NO"); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
30093203ce19fe679aa8f17912883cfe
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Integer.*;; public class A { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int n = parseInt(in.readLine()); char[][] arr = new char[n][n]; for (int i = 0; i < n; i++) { arr[i] = in.readLine().toCharArray(); } pw.println(solve(arr, n)); pw.close(); } static String solve(char[][] arr, int n) { int[] dy = {1, 0, -1, 0}; int[] dx = {0, 1, 0, -1}; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int res = 0; for (int k = 0; k < 4; k++) { int ni = i + dy[k]; int nj = j + dx[k]; if (ni >= 0 && ni < n && nj >= 0 && nj < n) { if (arr[ni][nj] == 'o') res++; } } if (res % 2 == 1) return "NO"; //if (res % 2 != 0) return "NO"; } } return "YES"; } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
1f42113e0904783d9e15a0c2199966a8
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.util.Scanner; public class ApplemanandEasyTask { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Character[][] arr = new Character[105][105]; for(int i = 0; i < n; i++) { String s = sc.next(); for(int j = 0; j < n; j++) { arr[i + 1][j + 1] = s.charAt(j); } } boolean b = true; for(int i=1; i<=n; i++) { for (int j = 1; j <= n; j++) { int cnt=0; if(j > 1 && arr[i][j-1]=='o') cnt++; if(j < n && arr[i][j+1]=='o') cnt++; if(i > 1 && arr[i-1][j]=='o') cnt++; if(i < n && arr[i + 1][j] == 'o') cnt++; if(cnt==1||cnt==3) { b = false; break; } } } System.out.print((b) ? "YES" : "NO"); } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
ede44cb9c23a89e5a8ef036fdffb8ce9
train_003.jsonl
1409061600
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
256 megabytes
import java.util.*; public class Main { public static void main(String[]args) { Scanner input=new Scanner (System.in); while(input.hasNext()) { int n=input.nextInt(); String z[]=new String[n]; for(int x=0;x<n;z[x]=input.next(),x++); boolean a=true; for(int y=0;y<n;y++) { for(int x=0,w=0;x<n;x++,w=0) { if(y>0&&z[y-1].charAt(x)=='o'&&++w==w); if(x>0&&z[y].charAt(x-1)=='o'&&++w==w); if(y<n-1&&z[y+1].charAt(x)=='o'&&++w==w); if(x<n-1&&z[y].charAt(x+1)=='o'&&++w==w); if(w%2!=0) a=false; } if(!a) break; } if(a) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"]
1 second
["YES", "NO"]
null
Java 8
standard input
[ "implementation", "brute force" ]
03fcf7402397b94edd1d1837e429185d
The first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
1,000
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
standard output
PASSED
d957337f41e791b78d1372a8cdad9c35
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.math.BigInteger; import java.time.chrono.MinguoChronology; import java.util.*; import javax.xml.bind.SchemaOutputResolver; public class Main { private static int maxn=100005; private static int one=1; public static int solve(Vector<Integer> a,int bit) { if(a.size()==0||bit<0) return 0; Vector<Integer>l = new Vector<Integer>(),r =new Vector<Integer>(); for(Integer u:a) { if(((u.intValue()>>bit)&(1))==one) { r.add(u); } else l.add(u); } //System.out.println(bit+" "+l.size()+" "+r.size()); if(l.size()==0) return solve(r, bit-1); if(r.size()==0) return solve(l, bit-1); return Math.min(solve(l, bit-1), solve(r, bit-1))+(1<<bit); } public static void main(String args[]) { Scanner in=new Scanner(System.in); int n=in.nextInt(); Vector<Integer>a = new Vector<Integer>(); for(int i=1;i<=n;i++) { a.add(in.nextInt()); } System.out.println(solve(a, 30)); } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
028c2310e7081a74200700ca366f6d03
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; import java.math.*; import static java.lang.Integer.*; import static java.lang.Double.*; import java.lang.Math.*; public class dr_evil_underscores { public static void main(String[] args) throws Exception { new dr_evil_underscores().run(); } public static FastIO file = new FastIO(); public static int n; public static ArrayList<Integer> a; public static int log2(int n) { int ans = 0; while (n>0) {++ans; n >>= 1;} return ans; } public static int solve(ArrayList<Integer> cr, int bit) { if (cr.isEmpty() || bit < 0) return 0; ArrayList<Integer> a1 = new ArrayList<>(), a2 = new ArrayList<>(); for (int x : cr) { if ((1<<bit&x) == 0) a1.add(x); else a2.add(x); } if (a1.isEmpty()) return solve(a2, bit-1); if (a2.isEmpty()) return solve(a1, bit-1); return Math.min(solve(a1, bit-1), solve(a2, bit-1)) + (1<<bit); } public void run() throws Exception { n = file.nextInt(); a = new ArrayList<Integer>(n); for (int i = 0; i < n; i++) a.add(file.nextInt()); println(solve(a, 30)); file.out.flush(); file.out.close(); } public static long mod(long n, long mod) { return (n % mod + mod) % mod; } public static long pow(long n, long p, long mod) { if (p == 0L) return mod(1L, mod); if (p == 1L) return mod(n, mod); long t = mod(pow(n, p >> 1, mod), mod); if (p % 2L == 0L) { return mod(t * t, mod); } t = mod(t * t, mod); t = mod(t * n, mod); return mod(t, mod); } public static long pow(long n, long p) { return pow(n, p, Long.MAX_VALUE); } public static long gcd(long x, long y) { if (x == 0) return y; return gcd(y % x, x); } public static long lcm(long x, long y) { return x / gcd(x, y) * y; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static class Pair<A, B> implements Comparable { public A fi; public B se; public Pair(A fi, B se) { this.fi = fi; this.se = se; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> p = (Pair<?, ?>) o; if (!fi.equals(p.fi)) return false; return se.equals(p.se); } @Override public int hashCode() { return 31 * fi.hashCode() + se.hashCode(); } @Override public String toString() { return fi.toString() + " " + se.toString(); } public static <A, B> Pair<A, B> of(A a, B b) { return new Pair<A, B>(a, b); } public int compareTo(Object o) { Pair<?, ?> p = (Pair<?, ?>) o; if (fi.equals(p.fi)) return ((Comparable) se).compareTo(p.se); return ((Comparable) fi).compareTo(p.fi); } } public static void print(Object o) { file.out.print(o); } public static void println(Object o) { file.out.println(o); } public static void printf(String s, Object... o) { file.out.printf(s, o); } public static class FastIO { BufferedReader br; StringTokenizer st; PrintWriter out; public FastIO() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } 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; } void print(Object o) { out.print(o); } void println(Object o) { out.println(o); } void printf(String s, Object... o) { out.printf(s, o); } } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
505322c1a9cc645297e2cd511e1163f8
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { static ArrayList<Integer>adj[]; static PrintWriter out=new PrintWriter(System.out); public static int mod = 1000000007; static int notmemo[][][]; static int k; static int x; static long a[]; public static void main(String[] args) throws Exception { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; ArrayList<Integer> l=new ArrayList<Integer>(); for (int i = 0; i < a.length; i++) { a[i]=sc.nextInt(); l.add(a[i]); } out.println(sum(l,30)); out.flush(); } public static int sum(ArrayList<Integer> l2,int bit) { if(bit==-1) { return 0; } ArrayList<Integer> on=new ArrayList<>(); ArrayList<Integer> off=new ArrayList<>(); for(int x:l2) { if(((x>>bit)&(1))==0) { off.add(x); } else { on.add(x); } } if(on.size()==0) { return sum(off,bit-1); } else if(off.size()==0) { return sum(on,bit-1); } return Math.min(sum(off,bit-1),sum(on,bit-1))+(1<<bit); } static class incpair implements Comparable<incpair> { int a; long b; int idx; incpair(int a, long dirg,int i) {this.a = a; b = dirg; idx=i; } public int compareTo(incpair e){ return (int) (b - e.b); } } static class decpair implements Comparable<decpair> { int a; long b;int idx; decpair(int a, long dirg,int i) {this.a = a; b = dirg; idx=i;} public int compareTo(decpair e){ return (int) (e.b- b); } } static long b[]; public static long dp(int i, int k) { if(i==n) { return 0; } if(memo[i][k]!=-1) { return (int) memo[i][k]; } long max=0; for (int j = 0; j <=k; j++) { max=Math.max(max, dp(i+1,k-j)|(allpowers[j]*a[i])); max=Math.max(max, (a[i])|dp(i+1,k)); } return (long) (memo[i][k]=max); } public static long revdp(int i, int k) { if(i==n) { return 0; } if(memo[i][k]!=-1) { return (long) memo[i][k]; } long max=0; for (int j = 0; j <=k; j++) { max=Math.max(max, dp(i+1,k-j)|(allpowers[j]*b[i])); max=Math.max(max, (b[i])|dp(i+1,k)); } return (long) (memo[i][k]=max); } static long allpowers[]; static class Quad implements Comparable<Quad>{ int u; int v; char state; int turns; public Quad(int i, int j, char c, int k) { u=i; v=j; state=c; turns=k; } public int compareTo(Quad e){ return (int) (turns - e.turns); } } static long dirg[][]; static Edge[] driver; static int n; static class Edge implements Comparable<Edge> { int node; long cost; Edge(int a, long dirg) { node = a; cost = dirg; } public int compareTo(Edge e){ return (int) (cost - e.cost); } } static long manhatandistance(long x,long x2,long y,long y2) { return Math.abs(x-x2)+Math.abs(y-y2); } static long fib[]; static long fib(int n) { if(n==1||n==0) { return 1; } if(fib[n]!=-1) { return fib[n]; } else return fib[n]= ((fib(n-2)%mod+fib(n-1)%mod)%mod); } static class Pair implements Comparable<Pair>{ int skill; int idx; Pair(int a, int b){ skill=a; idx=b; } public int compareTo(Pair p) { return p.skill-this.skill; } } static long[][] comb; static long nCr1(int n , int k) { if(n < k) return 0; if(k == 0 || k == n) return 1; if(comb[n][k] != -1) return comb[n][k]; if(n - k < k) return comb[n][k] = nCr1(n, n - k); return comb[n][k] = (nCr1(n - 1, k - 1) + nCr1(n - 1, k))%mod; } static class Triple implements Comparable<Triple>{ int u; int v; long totalcost; public Triple(int a,int b,long l) { u=a; v=b; totalcost=l; } @Override public int compareTo(Triple o) { return Long.compare( totalcost,o.totalcost); } } static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N)) { TreeSet<Long> factors = new TreeSet<Long>(); //take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while(p * p <= N) { while(N % p == 0) { factors.add((long) p); N /= p; } if(primes.size()>idx+1) p = primes.get(++idx); else break; } 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 boolean visited[]; /**static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>(); q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0; while(!q.isEmpty()) { int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) { maxcost=Math.max(maxcost, v.cost); if(!visited[v.v]) { visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost, v.cost); } } } return maxcost; }**/ public static boolean FindAllElements(int n, int k) { int sum = k; int[] A = new int[k]; Arrays.fill(A, 0, k, 1); for (int i = k - 1; i >= 0; --i) { while (sum + A[i] <= n) { sum += A[i]; A[i] *= 2; } } if(sum==n) { return true; } else return false; } static long[][] memo; static boolean vis2[][]; static class SegmentTree { // 1-based DS, OOP int N; //the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N<<1]; build(1,1,N); } void build(int node, int b, int e) // O(n) { if(b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node<<1,b,mid); build(node<<1|1,mid+1,e); sTree[node] = sTree[node<<1]+sTree[node<<1|1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] += val; while(index>1) { index >>= 1; sTree[index] = sTree[index<<1] + sTree[index<<1|1]; } } void update_range(int i, int j, int val) // O(log n) { update_range(1,1,N,i,j,val); } void update_range(int node, int b, int e, int i, int j, int val) { if(i > e || j < b) return; if(b >= i && e <= j) { sTree[node] += (e-b+1)*val; lazy[node] += val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node<<1,b,mid,i,j,val); update_range(node<<1|1,mid+1,e,i,j,val); sTree[node] = sTree[node<<1] + sTree[node<<1|1]; } } void propagate(int node, int b, int mid, int e) { lazy[node<<1] += lazy[node]; lazy[node<<1|1] += lazy[node]; sTree[node<<1] += (mid-b+1)*lazy[node]; sTree[node<<1|1] += (e-mid)*lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1,1,N,i,j); } int query(int node, int b, int e, int i, int j) // O(log n) { if(i>e || j <b) return 0; if(b>= i && e <= j) return sTree[node]; int mid = b + e >> 1; propagate(node, b, mid, e); int q1 = query(node<<1,b,mid,i,j); int q2 = query(node<<1|1,mid+1,e,i,j); return q1 + q2; } } static boolean f2=false; static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) //C(p x r) = A(p x q) x (q x r) -- O(p x q x r) { long[][] C = new long[p][r]; for(int i = 0; i < p; ++i) { for(int j = 0; j < r; ++j) { for(int k = 0; k < q; ++k) { C[i][j] = (C[i][j]+(a2[i][k]%mod * b[k][j]%mod))%mod; C[i][j]%=mod; } } } return C; } static ArrayList<Pair> a1[]; static int memo1[]; static boolean vis[]; static TreeSet<Integer> set=new TreeSet<Integer>(); static long modPow(long ways, long count, long mod) // O(log e) { ways %= mod; long res = 1; while(count > 0) { if((count & 1) == 1) res = (res * ways) % mod; ways = (ways * ways) % mod; count >>= 1; } return res%mod; } static long gcd(long ans,long b) { if(b==0) { return ans; } return gcd(b,ans%b); } static int[] isComposite; static int[] valid; static ArrayList<Integer> primes; static ArrayList<Integer> l; 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>(); l=new ArrayList<>(); valid=new int[N+1]; 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); l.add(i); valid[i]=1; for (int j = i*2; j <=N; j +=i) { // j = i * 2 will not affect performance too much, may alter in modified sieve isComposite[j] = 1; } } for(int i=0 ; i<primes.size() ; i++) { for(int j:primes) { if(primes.get(i)*j>N) { break; } valid[primes.get(i)*j]=1; } } } public static long[] schuffle(long[] a2) { for (int i = 0; i < a2.length; i++) { int x=(int)(Math.random()*a2.length); long temp=a2[x]; a2[x]=a2[i]; a2[i]=temp; } return a2; } static int V; static long INF=(long) 1E18; static class Edge2 { int node; long cost; long next; Edge2(int a, int c,Long long1) { node = a; cost = long1; next=c;} } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
f1bc496890db0137718bbd2115536ef0
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; import static java.lang.Math.min; public class Main { static final int mod = (int)1e9+7; public static void main(String[] args) throws Exception { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); ArrayList<Integer> al = new ArrayList(); for(int i = 0; i < n; i++) { al.add(in.nextInt()); } out.println(solve(30, al)); out.flush(); } static int solve(int k, ArrayList<Integer> al) { if(k < 0) { return 0; } ArrayList<Integer> off = new ArrayList(); ArrayList<Integer> on = new ArrayList(); for(int i : al) { if(((i >> k) & 1) == 1) { on.add(i); } else { off.add(i); } } if(on.size() == 0) { return solve(k - 1, off); } if(off.size() == 0) { return solve(k - 1, on); } return (1 << k) + min(solve(k - 1, off), solve(k - 1, on)); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if(st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
8a5f48b0bb71550546b58add30ad5741
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; /** * @author Mubtasim Shahriar */ public class DrEvil { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader sc = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); // int t = sc.nextInt(); int t = 1; while(t--!=0) { solver.solve(sc, out); } out.close(); } static class Solver { public void solve(InputReader sc, PrintWriter out) { int n = sc.nextInt(); ArrayList<Integer> al = new ArrayList(); for(int i = 0; i < n; i++) al.add(sc.nextInt()); out.println(solveit(al,30)); } private int solveit(ArrayList<Integer> al, int bit) { if(bit<0) return 0; ArrayList<Integer> l = new ArrayList(), r = new ArrayList(); for(Integer i : al) { if(((i>>bit)&1)==0) l.add(i); else r.add(i); } if(l.size()==0) return solveit(r,bit-1); if(r.size()==0) return solveit(l,bit-1); return Math.min(solveit(l,bit-1), solveit(r,bit-1)) + (1<<bit); } } static class InputReader { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int peek() { if (numChars == -1) { return -1; } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) { return -1; } } return buf[curChar]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) { s = readLine0(); } return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) { return readLine(); } else { return readLine0(); } } public BigInteger readBigInteger() { try { return new BigInteger(nextString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) { read(); } return value == -1; } public String next() { return nextString(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] nextIntArray(int n){ int[] array=new int[n]; for(int i=0;i<n;++i)array[i]=nextInt(); return array; } public int[] nextSortedIntArray(int n){ int array[]=nextIntArray(n); Arrays.sort(array); return array; } public int[] nextSumIntArray(int n){ int[] array=new int[n]; array[0]=nextInt(); for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt(); return array; } public long[] nextLongArray(int n){ long[] array=new long[n]; for(int i=0;i<n;++i)array[i]=nextLong(); return array; } public long[] nextSumLongArray(int n){ long[] array=new long[n]; array[0]=nextInt(); for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt(); return array; } public long[] nextSortedLongArray(int n){ long array[]=nextLongArray(n); Arrays.sort(array); return array; } } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
786f1347d4703e7867307a7de4b133c7
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); new Main().run(in, out); out.close(); } int N; void run(FastScanner in, PrintWriter out) { N = in.nextInt(); HashSet<Integer> s = new HashSet<>(); int pos = 0; for (int i = 0; i < N; i++) { int a = in.nextInt(); s.add(a); if (a != 0) pos = Math.max(pos, Integer.numberOfTrailingZeros(Integer.highestOneBit(a))); } out.println(go(pos, s)); } public static final int ONE = 0b1; public static final int ZERO = 0b10; public static final int MIXED = 0b11; int go(int index, Set<Integer> s) { if (index < 0) return 0; HashSet<Integer> zeroStart = new HashSet<>(); HashSet<Integer> oneStart = new HashSet<>(); int mask = 1<<index; int state = 0; for (int num : s) { if ((num & mask) > 0) { state |= ONE; oneStart.add(num); } else { state |= ZERO; zeroStart.add(num); } } if (state == MIXED) { return (1<<index) | Math.min(go(index-1, oneStart), go(index-1, zeroStart)); } else if (state == ZERO) { return go(index-1, zeroStart); } else { return go(index-1, oneStart); } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
aa7f9569f9bee610a394056d6b2ef482
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.*; import java.util.*; public class d { public static void main(String[] args) { new d(); } FS in = new FS(); PrintWriter out = new PrintWriter(System.out); int n; int[] a; d() { n = in.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); /* suffMax = new int[2][31]; // [j][i] = max value of bits with exp < i s.t. k == state of bit for (int i = 30; i >= 0; i--) { for (int j = 0; j < n; j++) { if (((1 << i) & a[j]) > 0) suffMax[1][i] = max(suffMax[1][i], a[j] % (1 << i)); else { suffMax[0][i] = max(suffMax[0][i], a[j] % (1 << i)); } } } */ /* while (b > 0) { ArrayList<Integer> zero = new ArrayList<>(); ArrayList<Integer> one = new ArrayList<>(); for (int i : alive) { boolean st = ((1 << b) & i) > 0 ? true : false; if (st) one.add(i); else zero.add(i); } if (one.size() == alive.size()) x += (1 << b); else if (!(zero.size() == alive.size())) { // this is a bad if (suffMax[0][b] < suffMax[1][b]) alive = zero; else // reiterating that this a big phat hmm alive = one; x += (1 << b); } b--; } */ ArrayList<Integer> alive = new ArrayList<>(); for (int i = 0; i < n; i++) alive.add(a[i]); int x = minmax(30, alive); out.println(x); out.close(); } int minmax(int bit, ArrayList<Integer> set) { if (bit == -1) return 0; ArrayList<Integer> one = new ArrayList<Integer>(); ArrayList<Integer> zero = new ArrayList<Integer>(); for (int i : set) { boolean st = ((1 << bit) & i) > 0 ? true : false; if (st) one.add(i); else zero.add(i); } int ans = 0; if (one.size() == set.size()) ans = minmax(bit - 1, one); else if (zero.size() == set.size()) ans = minmax(bit - 1, zero); else { int L = minmax(bit - 1, zero); int R = minmax(bit - 1, one); ans = (1 << bit) + min(L, R); } return ans; } int abs(int x) { if (x < 0) return -x; return x; } long abs(long x) { if (x < 0) return -x; return x; } int min(int a, int b) { if (a < b) return a; return b; } int max(int a, int b) { if (a > b) return a; return b; } long min(long a, long b) { if (a < b) return a; return b; } long max(long a, long b) { if (a > b) return a; return b; } int gcd(int a, int b) { while (b > 0) { a = b^(a^(b = a)); b %= a; } return a; } long gcd(long a, long b) { while (b > 0) { a = b^(a^(b = a)); b %= a; } return a; } long lcm(int a, int b) { return (((long) a) * b) / gcd(a, b); } long lcm(long a, long b) { return (a * b) / gcd(a, b); } void sort(int[] arr) { int sz = arr.length, j; Random r = new Random(); for (int i = 0; i < sz; i++) { j = r.nextInt(i + 1); arr[i] = arr[j]^(arr[i]^(arr[j] = arr[i])); } Arrays.sort(arr); } class FS { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) {} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
b188a85df76807d012d12c762043ab1b
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.*; import java.util.*; 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[] arr = in.nextIntArr(n); List<Integer> list = new ArrayList<>(); for (int i = 0; i < arr.length; i++) { list.add(arr[i]); } int res = getRes(list, 0); out.println(res); out.close(); } private static int getRes(List<Integer> list, int index) { if (index == 31) { return 0; } int mask = (1 << (30 - index)); List<Integer> zeros = new ArrayList<>(); List<Integer> ones = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { int val = list.get(i); if ((val & mask) == 0) { zeros.add(val); } else { ones.add(val); } } if (zeros.size() == 0) { return getRes(ones, index + 1); } if (ones.size() == 0) { return getRes(zeros, index + 1); } int resZero = mask + getRes(zeros, index + 1); int resOnes = mask + getRes(ones, index + 1); return Math.min(resZero, resOnes); } private static void print2Arr(int[][] arr, PrintWriter out) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) { out.print(arr[i][j] + " "); } out.println(); } } private static void printArr(int[] arr, PrintWriter out) { for (int i = 0; i < arr.length; i++) { out.print(arr[i] + " "); } out.println(); } 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\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
c59a897940ecc681ddb62d8f79580f1a
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class ProblemD { public static InputStream inputStream = System.in; public static OutputStream outputStream = System.out; public static void main(String[] args) { MyScanner scanner = new MyScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); int n = scanner.nextInt(); List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(scanner.nextInt()); } out.println(solve(list, 30)); out.flush(); } private static int solve(List<Integer> list, int index) { if (index == -1) { return 0; } List<Integer> zeros = new ArrayList<>(); List<Integer> ones = new ArrayList<>(); for (int x : list) { if ((x & (1 << index)) == 0) { zeros.add(x); } else { ones.add(x); } } if (zeros.isEmpty()) { return solve(ones, index - 1); } else if (ones.isEmpty()) { return solve(zeros, index - 1); } int x = (1 << index) + solve(ones, index - 1); int y = (1 << index) + solve(zeros, index - 1); return Math.min(x, y); } private static class MyScanner { private BufferedReader bufferedReader; private StringTokenizer stringTokenizer; private MyScanner(InputStream inputStream) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); } private String next() { while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) { try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return stringTokenizer.nextToken(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } private String nextLine() { String str = ""; try { str = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } private static class Pair<F, S> { private F first; private S second; public Pair() {} public Pair(F first, S second) { this.first = first; this.second = second; } } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
e46bad849253458e9068a83d99bf1bb9
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static PrintWriter out = new PrintWriter(System.out); static Scanner sc = new Scanner(System.in); static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { Main main = new Main(); main.solve(); out.flush(); } void solve(){ int n = sc.nextInt(); Set<Integer> dic = new HashSet<>(n); for(int i=0;i<n;i++) dic.add(sc.nextInt()); int ans = helper(29,dic); out.println(ans); } int helper(int idx, Set<Integer> dic){ if(idx<0) return 0; int mask = 1<<idx, n=dic.size(); Set<Integer> ones = new HashSet<>(n/2+1), zeros = new HashSet<>(n/2+1); for(int num:dic){ if((num&mask)>0) ones.add(num); else zeros.add(num); } if(ones.size()==n||zeros.size()==n) return helper(idx-1,dic); else{ int ans = mask; return ans+Math.min(helper(idx-1,zeros), helper(idx-1,ones)); } } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
3bd67b51d12a563ddbd12730a6dc0652
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { InputStream is; PrintWriter out; String INPUT = ""; //class Declaration static class pair implements Comparable < pair > { long x; long y; pair(long i, long j) { x = i; y = j; } public int compareTo(pair p) { if (this.x != p.x) { return Long.compare(this.x,p.x); } else { return Long.compare(this.y,p.y); } } public int hashCode() { return (x + " " + y).hashCode(); } public String toString() { return x + " " + y; } public boolean equals(Object o) { pair x = (pair) o; return (x.x == this.x && x.y == this.y); } } // int[] dx = {0,0,1,-1}; // int[] dy = {1,-1,0,0}; // int[] ddx = {0,0,1,-1,1,-1,1,-1}; // int[] ddy = {1,-1,0,0,1,-1,-1,1}; final int inf = (int) 1e9 + 9; final long biginf = (long)1e18 + 7 ; final long mod = (long)1e9+7; int[] arr ; int[][] dp ; ArrayList<Integer> al ; void solve() throws Exception { int n=ni(); ArrayList<Integer> al = new ArrayList<>(); for(int i=0;i<n;++i) al.add(ni()); pn(recur(30,al)); } int recur(int bit,ArrayList<Integer> al){ if(bit < 0) return 0; int ans = 0; ArrayList<Integer> set = new ArrayList<>(); ArrayList<Integer> unset = new ArrayList<>(); for(int x: al){ if((x & (1<<bit)) > 0) set.add(x); else unset.add(x); } if(set.size()>0 && unset.size() > 0){ ans = (1<<bit) + Math.min(recur(bit-1,set), recur(bit-1,unset)); } else{ ans = recur(bit -1 , al); } return ans ; } long pow(long a, long b) { long result = 1; while (b > 0) { if (b % 2 == 1) result = (result * a) % mod; b /= 2; a = (a * a) % mod; } return result; } long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); // System.err.println(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } //output methods private void dbg(Object... o){ System.err.println(Arrays.deepToString(o));} void p(Object... o){for(Object oo:o)out.print(oo+" ");} void pn(Object... o){for(int i = 0; i< o.length; i++)out.print(o[i]+(i+1 < o.length?" ":"\n"));} void pni(Object... o){for(Object oo:o)out.print(oo+" ");out.println();out.flush();} //input methods private int[][] ng(int n, int e, int[] from, int[] to, boolean f){ int[][] g = new int[n+1][];int[]cnt = new int[n+1]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i<= n; i++)g[i] = new int[cnt[i]]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = to[i]; if(f)g[to[i]][--cnt[to[i]]] = from[i]; } return g; } private int[][][] nwg(int n, int e, int[] from, int[] to, boolean f){ int[][][] g = new int[n+1][][];int[]cnt = new int[n+1]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0}; if(f) g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1}; } return g; } 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(); } } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
2b66e52507f4c6199f51cc68fb10db85
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ public Solution(){ Scanner sc = new Scanner(System.in); int tests = 1; for(int t=1; t<=tests; t++){ int n = sc.nextInt(); int[] arr = new int[n]; for(int i=0; i<n; i++){ arr[i] = sc.nextInt(); } Node root = new Node(); for(int i=0; i<n; i++){ insert(root, arr[i]); } int res = getMinXor(root, 29); System.out.println(res); } } public int getMinXor(Node root, int level){ int bit = -1; int sum = 1<<level; if(root.children[0] == null || root.children[1] == null){ sum = 0; } if(root.children[0] == null && root.children[1] == null){ return 0; } int val = Integer.MAX_VALUE; if(root.children[0] != null){ int xorZ = sum + getMinXor(root.children[0], level-1); val = Math.min(val, xorZ); } if(root.children[1] != null){ int xorO = sum + getMinXor(root.children[1], level-1); val = Math.min(val, xorO); } return val; } public void insert(Node root, int num){ for(int i=29; i>=0; i--){ int n = num>>i; int bit = n%2; if(root.children[bit] == null){ root.children[bit] = new Node(); } root = root.children[bit]; } } public static void main(String[] args){ new Solution(); } } class Node{ public Node[] children; public Node(){ children = new Node[2]; } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
aa2adaf5d806ccb41e5fa50bba316478
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Set; public class Main { InputStream is; PrintWriter out; String INPUT = ""; private static final long M = 1000000007L; void solve() { StringBuffer sb = new StringBuffer(); int N = ni(); long[] a = nl(N); Arrays.sort(a); dfs(a, 1L << 30, 0, N - 1, 0); out.println(ans); } long ans = Long.MAX_VALUE; private void dfs(long[] a, long f, int l, int r, long max) { if (f == 0) { ans = Math.min(max, ans); return; } int m = l; for (; m <= r; m++) if ((a[m] & f) != 0) break; // tr(f, l, r, m); if (m == l || m > r) dfs(a, f >> 1, l, r, max); else { dfs(a, f >> 1, l, m - 1, max | f); dfs(a, f >> 1, m, r, max | f); } } private long gcd(long a, long b) { while (a != 0) { long tmp = b % a; b = a; a = tmp; } return b; } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private boolean vis[]; 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) { if (!(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 long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private String[] nas(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = ns(); return a; } private Integer[] na2(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = Math.abs(ni()); return a; } private int[][] na(int n, int m) { int[][] a = new int[n][]; for (int i = 0; i < n; i++) a[i] = na(m); return a; } private Integer[][] na2(int n, int m) { Integer[][] a = new Integer[n][]; for (int i = 0; i < n; i++) a[i] = na2(m); 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 static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
9201237a27a6274158225bd3d7c65826
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return a==0?b:b>=a?gcd(b%a,a):gcd(b,a); } class Trie{ Trie[] nodes=new Trie[2]; } int ret=Integer.MAX_VALUE; void work() { int n=in.nextInt(); Trie root=new Trie(); for(int i=0;i<n;i++) { int num=in.nextInt(); Trie node=root; for(int j=31;j>=0;j--) { int b=(num>>j)&1; if(node.nodes[b]==null) { node.nodes[b]=new Trie(); } node=node.nodes[b]; } } dfs(root,0); out.println(ret); } private void dfs(Trie node,int cur) { if(node.nodes[0]==null&&node.nodes[1]==null) { ret=Math.min(ret, cur); return; } if(node.nodes[0]!=null&&node.nodes[1]!=null) { cur=(cur<<1)+1; }else { cur<<=1; } if(node.nodes[0]!=null) { dfs(node.nodes[0],cur); } if(node.nodes[1]!=null) { dfs(node.nodes[1],cur); } } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { while(st==null || !st.hasMoreElements())//ε›žθ½¦οΌŒη©Ίθ‘Œζƒ…ε†΅ { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
e0a7dbd2fbfeebcb1a775706ec453654
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.*; import java.util.*; public class evilXOR { public static void main(String s[]) throws Exception { Reader r = new Reader(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = r.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) arr[i]=r.nextInt(); Set<Integer> pos=new HashSet<Integer>(); for(int i=0;i<n;i++) pos.add(i); int res=minMax(arr,pos,31); System.out.println(res); } static int minMax(int[] arr,Set<Integer> pos,int index){ Set<Integer> one=new HashSet<Integer>(); Set<Integer> zero=new HashSet<Integer>(); Iterator<Integer> it=pos.iterator(); while(it.hasNext()) { int p=it.next(); if((arr[p]&(1<<index))>0) one.add(p); else zero.add(p); } if(index==0){ if(one.size()==0 || zero.size()==0) return 0; else return 1; } int res=0; if(one.size()==0||zero.size()==0){ res=one.size()==0?minMax(arr,zero,index-1):minMax(arr,one,index-1); }else { res=(1<<index)+Math.min(minMax(arr,one,index-1),minMax(arr,zero,index-1)); } return res; } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
36a0a7837aecfca0d1107d206a55e29f
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.*; import java.nio.CharBuffer; import java.util.NoSuchElementException; public class P1285D { public static void main(String[] args) { SimpleScanner scanner = new SimpleScanner(System.in); PrintWriter writer = new PrintWriter(System.out); final int MAX_BIT = 30; int n = scanner.nextInt(); Node root = new Node(); for (int i = 0; i < n; ++i) { int a = scanner.nextInt(); search(a, root, MAX_BIT - 1); } writer.println(root.ans); writer.close(); } private static void search(int v, Node node, int bit) { if ((v & (1 << bit)) == 0) { if (node.l == null) node.l = new Node(); if (bit > 0) search(v, node.l, bit - 1); } else { if (node.r == null) node.r = new Node(); if (bit > 0) search(v, node.r, bit - 1); } if (node.r == null) node.ans = node.l.ans; else if (node.l == null) node.ans = node.r.ans; else node.ans = Math.min(node.l.ans, node.r.ans) | (1 << bit); } private static class Node { private Node l, r; private int ans; } private static class SimpleScanner { private static final int BUFFER_SIZE = 10240; private Readable in; private CharBuffer buffer; private boolean eof; private 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(); } private void checkEof() { if (eof) throw new NoSuchElementException(); } private char nextChar() { checkEof(); char b = read(); checkEof(); return b; } private 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(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
54443f5d350201bc2979f9f1da0dc1f4
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static int solve(SortedSet<Integer> set, int idx, int or) { SortedSet<Integer> set1 = set.headSet(or | (1 << idx)); SortedSet<Integer> set2 = set.tailSet(or | (1 << idx)); if (idx == 0) { return set1.isEmpty() || set2.isEmpty() ? 0 : 1; } if (set1.isEmpty()) { return solve(set2, idx - 1, or | (1 << idx)); } else if (set2.isEmpty()) { return solve(set1, idx - 1, or); } int res1 = solve(set1, idx - 1, or); int res2 = solve(set2, idx - 1, or | (1 << idx)); return Math.min(res1, res2) | (1 << idx); } public static void main(String[] args) { InputReader in = new InputReader(); int N = in.nextInt(); SortedSet<Integer> set = new TreeSet<>(); while (N-- > 0) { int x = in.nextInt(); set.add(x); } System.out.println(solve(set, 29, 0)); } static class InputReader { public BufferedReader reader; public StringTokenizer st; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
987eaed4ea9eecba7a6bf843d29e85bc
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class DEU_1285D { public static void main(String[]args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); ArrayList<Integer> a = new ArrayList<Integer>(); int high = -1, count = 0; for (int i = 0; i < n; i++) { a.add(in.nextInt()); high = Math.max(a.get(i), high); } //while((high >> count) > 0) count++; System.out.println(minmax(a,30)); //System.out.println((3>>1)&1); } public static int minmax(ArrayList<Integer> a,int i){ if(a.size() == 0 || i < 0) return 0; ArrayList<Integer> p1 = new ArrayList<Integer>(); ArrayList<Integer> p2 = new ArrayList<Integer>(); for(int j = 0; j < a.size(); j++){ if((a.get(j) & (1 << (i)))!= 0) p1.add(a.get(j)); else p2.add(a.get(j)); } if(p1.size() == 0) return minmax(p2,i-1); if(p2.size() == 0) return minmax(p1,i-1); return (1<<(i))+Math.min(minmax(p1,i-1),minmax(p2,i-1)); } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
bd2a7b5d8a2d56bdb46c315e4039ba92
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.lang.*; import java.util.*; import java.io.*; public class Main { void solve() { int n=ni(); trie=new int[40*n+1][2]; for(int i=1;i<=n;i++) add(ni()); int ans=dfs(0,29); pw.println(ans); } int trie[][]; int C=0; void add(int x){ int curr=0; for(int b=29;b>=0;b--){ int req=((x>>b)&1); if(trie[curr][req]==0){ trie[curr][req]=++C; } curr=trie[curr][req]; } } int dfs(int curr,int b){ if(trie[curr][0]==0 && trie[curr][1]==0) return 0; if(trie[curr][0]==0) return dfs(trie[curr][1],b-1); else if(trie[curr][1]==0) return dfs(trie[curr][0],b-1); if(b==0) return 1<<b; return (1<<b)+Math.min(dfs(trie[curr][0],b-1),dfs(trie[curr][1],b-1)); } long M =(long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o)); } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
2eb0773c9eeb5f4be9166f5d72789f44
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Collection; import java.util.InputMismatchException; import java.io.IOException; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DrEvilUnderscores solver = new DrEvilUnderscores(); solver.solve(1, in, out); out.close(); } static class DrEvilUnderscores { final int BITS = 29; int n; EzIntList a; int solve(int idx, EzIntList nums) { if (idx == -1) { return 0; } EzIntList one = new EzIntArrayList(), zero = new EzIntArrayList(); for (int i = 0; i < nums.size(); i++) { int x = nums.get(i); if ((x & (1 << idx)) != 0) { one.add(x); } else { zero.add(x); } } int ans = Integer.MAX_VALUE; if (zero.isEmpty() || one.isEmpty()) { ans = Math.min(ans, solve(idx - 1, nums)); } else { ans = Math.min(ans, (1 << idx) | solve(idx - 1, one)); ans = Math.min(ans, (1 << idx) | solve(idx - 1, zero)); } return ans; } public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.ni(); a = new EzIntArrayList(n); for (int i = 0; i < n; i++) { a.add(in.ni()); } int ans = solve(BITS, a); out.println(ans); } } static final class PrimitiveHashCalculator { private PrimitiveHashCalculator() { } public static int getHash(int x) { return x; } } static interface EzIntList extends EzIntCollection { int size(); boolean isEmpty(); EzIntIterator iterator(); boolean add(int element); boolean equals(Object object); int hashCode(); String toString(); int get(int index); } static interface EzIntIterator { boolean hasNext(); int next(); } static interface EzIntCollection { int size(); EzIntIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static class InputReader { private final InputStream is; private final byte[] inbuf = new byte[1024]; private int lenbuf = 0; private int ptrbuf = 0; public InputReader(InputStream stream) { is = stream; } 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++]; } public 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(); } } } static class EzIntArrayList implements EzIntList, EzIntStack { private static final int DEFAULT_CAPACITY = 10; private static final double ENLARGE_SCALE = 2.0; private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5; private static final int HASHCODE_MULTIPLIER = 0x01000193; private int[] array; private int size; public EzIntArrayList() { this(DEFAULT_CAPACITY); } public EzIntArrayList(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } array = new int[capacity]; size = 0; } public EzIntArrayList(EzIntCollection collection) { size = collection.size(); array = new int[size]; int i = 0; for (EzIntIterator iterator = collection.iterator(); iterator.hasNext(); ) { array[i++] = iterator.next(); } } public EzIntArrayList(int[] srcArray) { size = srcArray.length; array = new int[size]; System.arraycopy(srcArray, 0, array, 0, size); } public EzIntArrayList(Collection<Integer> javaCollection) { size = javaCollection.size(); array = new int[size]; int i = 0; for (int element : javaCollection) { array[i++] = element; } } public int size() { return size; } public boolean isEmpty() { return size == 0; } public EzIntIterator iterator() { return new EzIntArrayListIterator(); } public boolean add(int element) { if (size == array.length) { enlarge(); } array[size++] = element; return true; } public int get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index " + index + " is out of range, size = " + size); } return array[index]; } private void enlarge() { int newSize = Math.max(size + 1, (int) (size * ENLARGE_SCALE)); int[] newArray = new int[newSize]; System.arraycopy(array, 0, newArray, 0, size); array = newArray; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntArrayList that = (EzIntArrayList) o; if (size != that.size) { return false; } for (int i = 0; i < size; i++) { if (array[i] != that.array[i]) { return false; } } return true; } public int hashCode() { int hash = HASHCODE_INITIAL_VALUE; for (int i = 0; i < size; i++) { hash = (hash ^ PrimitiveHashCalculator.getHash(array[i])) * HASHCODE_MULTIPLIER; } return hash; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < size; i++) { sb.append(array[i]); if (i < size - 1) { sb.append(", "); } } sb.append(']'); return sb.toString(); } private class EzIntArrayListIterator implements EzIntIterator { private int curIndex = 0; public boolean hasNext() { return curIndex < size; } public int next() { if (curIndex == size) { throw new NoSuchElementException("Iterator doesn't have more elements"); } return array[curIndex++]; } } } static interface EzIntStack extends EzIntCollection { int size(); EzIntIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
31da00c0c4f452a3eac1430f79371972
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.List; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; public class DrEvilUnderscore { int n; List<Long> a; final int BITS = 29; // smallest max using bits <= idx. long solve(int idx, List<Long> nums) { if (idx == -1) { return 0; } List<Long> one = new ArrayList<>(), zero = new ArrayList<>(); for (long x : nums) { if ((x & (1 << idx)) != 0) { one.add(x); } else { zero.add(x); } } long ans = Long.MAX_VALUE; if (zero.isEmpty() || one.isEmpty()) { ans = min(ans, solve(idx - 1, nums)); } else { ans = min(ans, (1 << idx) | solve(idx - 1, one)); ans = min(ans, (1 << idx) | solve(idx - 1, zero)); } return ans; } void solve() { n = ni(); a = new ArrayList<>(n); for (int i = 0; i < n; i++) { a.add(nl()); } long ans = solve(BITS, a); out.println(ans); } /*==================================================================================================================*/ // Startup String INPUT = ""; void run() { is = System.in; out = new PrintWriter(System.out); long s = System.currentTimeMillis(); int tt = 1; // tt = ni(); for (int i = 1; i <= tt; i++) { solve(); } out.flush(); tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new DrEvilUnderscore().run(); } // IntList // Input/output InputStream is; PrintWriter out; 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(); } } // Debug private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
80498d360925c48c76b07c342de64a89
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class D1285_DrEvilUnderScore { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); List<Integer> list = new ArrayList<>(); for(int i = 0; i < n; i++) { list.add(s.nextInt()); } System.out.println(postorderDfs(list, 30)); } private static int postorderDfs(List<Integer> list, int bit) { if(list.isEmpty() || bit < 0) { return 0; } List<Integer> set = new ArrayList<>(); List<Integer> reset = new ArrayList<>(); for(int i : list) { if(((1 << bit) & i) == 0) { reset.add(i); } else { set.add(i); } } if(set.isEmpty()) return postorderDfs(reset, bit-1); if(reset.isEmpty()) return postorderDfs(set, bit-1); return Math.min(postorderDfs(set, bit-1), postorderDfs(reset, bit-1)) + (1 << bit); } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
455cdd625632e87997d90b97c45d14f6
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.List; //javac Main.java & java Main showTrace:1 runOnEditor:0 inputFromLocal:1 outputToLocal:0 //javac Main.java ; java Main showTrace:1 runOnEditor:1 inputFromLocal:0 outputToLocal:0 public class Main extends Core { protected static final int MOD = (int) 1E9 + 7; public Main(String[] args) { super(args); } public static void main(String[] args) { new Main(args); } @Override protected void solve() throws Exception { int N = ni(); int[] arr = ni(N); List<Integer> indices = new ArrayList<>(); for (int i = 0; i < N; ++i) { indices.add(i); } println(maxValueFrom(31, indices, arr)); } int maxValueFrom(int colIndex, List<Integer> indices, int[] arr) { if (colIndex < 0) { return 0; } List<Integer> zeroIndices = new ArrayList<>(); List<Integer> oneIndices = new ArrayList<>(); // Check bit at colIndex is 0 or 1 to divide 2 index-groups for (int index : indices) { if ((arr[index] & (1 << colIndex)) > 0) { oneIndices.add(index); } else { zeroIndices.add(index); } } if (zeroIndices.size() == 0 || oneIndices.size() == 0) { return maxValueFrom(colIndex - 1, indices, arr); } int childZeroResult = maxValueFrom(colIndex - 1, zeroIndices, arr); int childOneResult = maxValueFrom(colIndex - 1, oneIndices, arr); // Have 2 cases here, xor at colIndex with 0 or 1 to get min of max-results. return Math.min( Math.max(childZeroResult, (1 << colIndex) + childOneResult), Math.max(childOneResult, (1 << colIndex) + childZeroResult) ); } } abstract class Core { protected abstract void solve() throws Exception; private static final int BUFFER_SIZE = (1 << 13); private static final int WHITE_SPACE = 32; private static final byte[] IN_BUFFER = new byte[BUFFER_SIZE]; private static final byte[] OUT_BUFFER = new byte[BUFFER_SIZE]; private int inNextByte; private int inNextIndex; private int inReadByteCount; private int outNextIndex; private InputStream in = System.in; private OutputStream out = System.out; private PrintStream info = System.err; private boolean showTrace; private boolean runOnEditor; private boolean inputFromLocal; private boolean outputToLocal; protected Core(String[] args) { try { start(args); } catch (Exception e) { e.printStackTrace(); } } private void start(String[] args) throws Exception { if (args != null) { if (args.length > 0) { showTrace = "1".equals(args[0].split(":")[1]); } if (args.length > 1) { runOnEditor = "1".equals(args[1].split(":")[1]); } if (args.length > 2) { inputFromLocal = "1".equals(args[2].split(":")[1]); } if (args.length > 3) { outputToLocal = "1".equals(args[3].split(":")[1]); } } if (inputFromLocal) { String fs = File.separator; String root = new File("").getAbsolutePath(); String inPath = String.format("%s%s%s", root, fs, "in.txt"); if (runOnEditor) { inPath = String.format("%s%s%s%s%s%s%s", root, fs, "src", fs, "testdata", fs, "in.txt"); } if (showTrace) { info.println("Input: " + inPath); } in = new FileInputStream(inPath); } else if (showTrace) { info.println("Input: Console"); } if (outputToLocal) { String fs = File.separator; String root = new File("").getAbsolutePath(); String outPath = String.format("%s%s%s", root, fs, "out.txt"); if (runOnEditor) { outPath = String.format("%s%s%s%s%s%s%s", root, fs, "src", fs, "testdata", fs, "out.txt"); } if (showTrace) { info.println("Output: " + outPath); } out = new FileOutputStream(outPath); } else if (showTrace) { info.println("Output: Console"); } long start = 0; if (showTrace) { start = System.currentTimeMillis(); } nextByte(); solve(); in.close(); flushOutBuf(); if (showTrace) { info.printf("\nSolve completed in %.3f [s]\n", (System.currentTimeMillis() - start) / 1000.0); } } private int nextByte() throws IOException { if (inNextIndex >= inReadByteCount) { inReadByteCount = in.read(IN_BUFFER, 0, BUFFER_SIZE); if (inReadByteCount == -1) { return (inNextByte = -1); } inNextIndex = 0; } return (inNextByte = IN_BUFFER[inNextIndex++]); } protected final char nc() throws IOException { while (inNextByte <= WHITE_SPACE) { nextByte(); } char res = (char) inNextByte; nextByte(); return res; } protected final int ni() throws IOException { int res = 0; while (inNextByte <= WHITE_SPACE) { nextByte(); } boolean minus = (inNextByte == '-'); if (minus) { nextByte(); } if (inNextByte < '0' || inNextByte > '9') { throw new RuntimeException("Invalid integer value format to read"); } do { res = (res << 1) + (res << 3) + inNextByte - '0'; } while (nextByte() >= '0' && inNextByte <= '9'); return minus ? -res : res; } protected final long nl() throws IOException { long res = 0; while (inNextByte <= WHITE_SPACE) { nextByte(); } boolean minus = (inNextByte == '-'); if (minus) { nextByte(); } if (inNextByte < '0' || inNextByte > '9') { throw new RuntimeException("Invalid long value format to read"); } do { res = (res << 1) + (res << 3) + inNextByte - '0'; } while (nextByte() >= '0' && inNextByte <= '9'); return minus ? -res : res; } protected final double nd() throws IOException { double pre = 0.0, suf = 0.0, div = 1.0; while (inNextByte <= WHITE_SPACE) { nextByte(); } boolean minus = (inNextByte == '-'); if (minus) { nextByte(); } if (inNextByte < '0' || inNextByte > '9') { throw new RuntimeException("Invalid double value format to read"); } do { pre = 10 * pre + (inNextByte - '0'); } while (nextByte() >= '0' && inNextByte <= '9'); if (inNextByte == '.') { while (nextByte() >= '0' && inNextByte <= '9') { suf += (inNextByte - '0') / (div *= 10); } } return minus ? -(pre + suf) : (pre + suf); } protected final String ns() throws IOException { while (inNextByte <= WHITE_SPACE) { nextByte(); } StringBuilder sb = new StringBuilder(); while (inNextByte > WHITE_SPACE) { sb.append((char) inNextByte); nextByte(); } return sb.toString(); } protected final char[] nc(int n) throws IOException { char[] a = new char[n]; for (int i = 0; i < n; ++i) { a[i] = nc(); } return a; } protected final char[][] nc(int r, int c) throws IOException { char[][] a = new char[r][c]; for (int i = 0; i < r; ++i) { a[i] = nc(c); } return a; } protected final int[] ni(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = ni(); } return a; } protected final int[][] ni(int r, int c) throws IOException { int[][] a = new int[r][c]; for (int i = 0; i < r; ++i) { a[i] = ni(c); } return a; } protected final long[] nl(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; ++i) { a[i] = nl(); } return a; } protected final long[][] nl(int r, int c) throws IOException { long[][] a = new long[r][c]; for (int i = 0; i < r; ++i) { a[i] = nl(c); } return a; } protected final double[] nd(int n) throws IOException { double[] a = new double[n]; for (int i = 0; i < n; ++i) { a[i] = nd(); } return a; } protected final double[][] nd(int r, int c) throws IOException { double[][] a = new double[r][c]; for (int i = 0; i < r; ++i) { a[i] = nd(c); } return a; } protected final String[] ns(int n) throws IOException { String[] a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = ns(); } return a; } protected final String[][] ns(int r, int c) throws IOException { String[][] a = new String[r][c]; for (int i = 0; i < r; ++i) { a[i] = ns(c); } return a; } private final void flushOutBuf() { try { if (outNextIndex <= 0) { return; } out.write(OUT_BUFFER, 0, outNextIndex); out.flush(); outNextIndex = 0; } catch (Exception e) { e.printStackTrace(); } } protected final void print(String s) { if (s == null) { s = "null"; } for (int i = 0, N = s.length(); i < N; ++i) { OUT_BUFFER[outNextIndex++] = (byte) s.charAt(i); if (outNextIndex >= BUFFER_SIZE) { flushOutBuf(); } } } protected final void println(String s) { print(s); print('\n'); } protected final void print(Object obj) { if (obj == null) { print("null"); } else { print(obj.toString()); } } protected final void println(Object obj) { print(obj); print('\n'); } protected final void print(String format, Object... args) { if (args != null) { format = String.format(format, args); } print(format); } protected final void println(String format, Object... args) { if (args != null) { format = String.format(format, args); } println(format); } protected final void debug(String format, Object... args) { if (args != null) { format = String.format(format, args); } info.print(format); } protected final void debugln(String format, Object... args) { if (args != null) { format = String.format(format, args); } info.println(format); } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
b5351349698db1f4aaf518226db2320c
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.List; //javac Main.java & java Main showTrace:1 runOnEditor:0 inputFromLocal:1 outputToLocal:0 //javac Main.java ; java Main showTrace:1 runOnEditor:1 inputFromLocal:0 outputToLocal:0 public class Main extends Core { protected static final int MOD = (int) 1E9 + 7; public Main(String[] args) { super(args); } public static void main(String[] args) { new Main(args); } @Override protected void solve() throws Exception { int N = ni(); int[] arr = ni(N); solve(N, arr); } void solve(int N, int[] arr) { List<Integer> indices = new ArrayList<>(); for (int i = 0; i < N; ++i) { indices.add(i); } println(maxValueFrom(31, indices, arr)); } int maxValueFrom(int colIndex, List<Integer> indices, int[] arr) { if (colIndex < 0) { return 0; } List<Integer> zeroIndices = new ArrayList<>(); List<Integer> oneIndices = new ArrayList<>(); // Check bit at colIndex is 0 or 1 to divide 2 index-groups for (int index : indices) { if ((arr[index] & (1 << colIndex)) > 0) { oneIndices.add(index); } else { zeroIndices.add(index); } } if (zeroIndices.size() == 0 || oneIndices.size() == 0) { return maxValueFrom(colIndex - 1, indices, arr); } int childZeroResult = maxValueFrom(colIndex - 1, zeroIndices, arr); int childOneResult = maxValueFrom(colIndex - 1, oneIndices, arr); // Have 2 cases here, xor at colIndex with 0 or 1 to get min of max-results. return Math.min( Math.max(childZeroResult, (1 << colIndex) + childOneResult), Math.max(childOneResult, (1 << colIndex) + childZeroResult) ); } } abstract class Core { protected abstract void solve() throws Exception; private static final int BUFFER_SIZE = (1 << 13); private static final int WHITE_SPACE = 32; private static final byte[] IN_BUFFER = new byte[BUFFER_SIZE]; private static final byte[] OUT_BUFFER = new byte[BUFFER_SIZE]; private int inNextByte; private int inNextIndex; private int inReadByteCount; private int outNextIndex; private InputStream in = System.in; private OutputStream out = System.out; private PrintStream info = System.err; private boolean showTrace; private boolean runOnEditor; private boolean inputFromLocal; private boolean outputToLocal; protected Core(String[] args) { try { start(args); } catch (Exception e) { e.printStackTrace(); } } private void start(String[] args) throws Exception { if (args != null) { if (args.length > 0) { showTrace = "1".equals(args[0].split(":")[1]); } if (args.length > 1) { runOnEditor = "1".equals(args[1].split(":")[1]); } if (args.length > 2) { inputFromLocal = "1".equals(args[2].split(":")[1]); } if (args.length > 3) { outputToLocal = "1".equals(args[3].split(":")[1]); } } if (inputFromLocal) { String fs = File.separator; String root = new File("").getAbsolutePath(); String inPath = String.format("%s%s%s", root, fs, "in.txt"); if (runOnEditor) { inPath = String.format("%s%s%s%s%s%s%s", root, fs, "src", fs, "testdata", fs, "in.txt"); } if (showTrace) { info.println("Input: " + inPath); } in = new FileInputStream(inPath); } else if (showTrace) { info.println("Input: Console"); } if (outputToLocal) { String fs = File.separator; String root = new File("").getAbsolutePath(); String outPath = String.format("%s%s%s", root, fs, "out.txt"); if (runOnEditor) { outPath = String.format("%s%s%s%s%s%s%s", root, fs, "src", fs, "testdata", fs, "out.txt"); } if (showTrace) { info.println("Output: " + outPath); } out = new FileOutputStream(outPath); } else if (showTrace) { info.println("Output: Console"); } long start = 0; if (showTrace) { start = System.currentTimeMillis(); } nextByte(); solve(); in.close(); flushOutBuf(); if (showTrace) { info.printf("\nSolve completed in %.3f [s]\n", (System.currentTimeMillis() - start) / 1000.0); } } private int nextByte() throws IOException { if (inNextIndex >= inReadByteCount) { inReadByteCount = in.read(IN_BUFFER, 0, BUFFER_SIZE); if (inReadByteCount == -1) { return (inNextByte = -1); } inNextIndex = 0; } return (inNextByte = IN_BUFFER[inNextIndex++]); } protected final char nc() throws IOException { while (inNextByte <= WHITE_SPACE) { nextByte(); } char res = (char) inNextByte; nextByte(); return res; } protected final int ni() throws IOException { int res = 0; while (inNextByte <= WHITE_SPACE) { nextByte(); } boolean minus = (inNextByte == '-'); if (minus) { nextByte(); } if (inNextByte < '0' || inNextByte > '9') { throw new RuntimeException("Invalid integer value format to read"); } do { res = (res << 1) + (res << 3) + inNextByte - '0'; } while (nextByte() >= '0' && inNextByte <= '9'); return minus ? -res : res; } protected final long nl() throws IOException { long res = 0; while (inNextByte <= WHITE_SPACE) { nextByte(); } boolean minus = (inNextByte == '-'); if (minus) { nextByte(); } if (inNextByte < '0' || inNextByte > '9') { throw new RuntimeException("Invalid long value format to read"); } do { res = (res << 1) + (res << 3) + inNextByte - '0'; } while (nextByte() >= '0' && inNextByte <= '9'); return minus ? -res : res; } protected final double nd() throws IOException { double pre = 0.0, suf = 0.0, div = 1.0; while (inNextByte <= WHITE_SPACE) { nextByte(); } boolean minus = (inNextByte == '-'); if (minus) { nextByte(); } if (inNextByte < '0' || inNextByte > '9') { throw new RuntimeException("Invalid double value format to read"); } do { pre = 10 * pre + (inNextByte - '0'); } while (nextByte() >= '0' && inNextByte <= '9'); if (inNextByte == '.') { while (nextByte() >= '0' && inNextByte <= '9') { suf += (inNextByte - '0') / (div *= 10); } } return minus ? -(pre + suf) : (pre + suf); } protected final String ns() throws IOException { while (inNextByte <= WHITE_SPACE) { nextByte(); } StringBuilder sb = new StringBuilder(); while (inNextByte > WHITE_SPACE) { sb.append((char) inNextByte); nextByte(); } return sb.toString(); } protected final char[] nc(int n) throws IOException { char[] a = new char[n]; for (int i = 0; i < n; ++i) { a[i] = nc(); } return a; } protected final char[][] nc(int r, int c) throws IOException { char[][] a = new char[r][c]; for (int i = 0; i < r; ++i) { a[i] = nc(c); } return a; } protected final int[] ni(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = ni(); } return a; } protected final int[][] ni(int r, int c) throws IOException { int[][] a = new int[r][c]; for (int i = 0; i < r; ++i) { a[i] = ni(c); } return a; } protected final long[] nl(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; ++i) { a[i] = nl(); } return a; } protected final long[][] nl(int r, int c) throws IOException { long[][] a = new long[r][c]; for (int i = 0; i < r; ++i) { a[i] = nl(c); } return a; } protected final double[] nd(int n) throws IOException { double[] a = new double[n]; for (int i = 0; i < n; ++i) { a[i] = nd(); } return a; } protected final double[][] nd(int r, int c) throws IOException { double[][] a = new double[r][c]; for (int i = 0; i < r; ++i) { a[i] = nd(c); } return a; } protected final String[] ns(int n) throws IOException { String[] a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = ns(); } return a; } protected final String[][] ns(int r, int c) throws IOException { String[][] a = new String[r][c]; for (int i = 0; i < r; ++i) { a[i] = ns(c); } return a; } protected final void flushOutBuf() { try { if (outNextIndex <= 0) { return; } out.write(OUT_BUFFER, 0, outNextIndex); out.flush(); outNextIndex = 0; } catch (Exception e) { e.printStackTrace(); } } protected final void print(String s) { if (s == null) { s = "null"; } for (int i = 0, N = s.length(); i < N; ++i) { OUT_BUFFER[outNextIndex++] = (byte) s.charAt(i); if (outNextIndex >= BUFFER_SIZE) { flushOutBuf(); } } } protected final void println(String s) { print(s); print('\n'); } protected final void print(Object obj) { if (obj == null) { print("null"); } else { print(obj.toString()); } } protected final void println(Object obj) { print(obj); print('\n'); } protected final void print(String format, Object... args) { if (args != null) { format = String.format(format, args); } print(format); } protected final void println(String format, Object... args) { if (args != null) { format = String.format(format, args); } println(format); } protected final void debug(String format, Object... args) { if (args != null) { format = String.format(format, args); } info.print(format); } protected final void debugln(String format, Object... args) { if (args != null) { format = String.format(format, args); } info.println(format); } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
80d55fa3942517a0199cc9e9acdf1159
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.List; //javac Main.java & java Main showTrace:1 runOnEditor:0 inputFromLocal:1 outputToLocal:0 //javac Main.java ; java Main showTrace:1 runOnEditor:1 inputFromLocal:0 outputToLocal:0 public class Main extends Core { protected static final int MOD = (int) 1E9 + 7; public Main(String[] args) { super(args); } public static void main(String[] args) { new Main(args); } @Override protected void solve() throws Exception { int N = ni(); int[] arr = ni(N); solve(N, arr); } void solve(int N, int[] arr) { List<Integer> indices = new ArrayList<>(); for (int i = 0; i < N; ++i) { indices.add(i); } println(maxValueFrom(31, indices, arr)); } int maxValueFrom(int colIndex, List<Integer> elmIndices, int[] arr) { if (colIndex < 0) { return 0; } List<Integer> zeroIndices = collectBits(0, colIndex, elmIndices, arr); List<Integer> oneIndices = collectBits(1, colIndex, elmIndices, arr); if (zeroIndices.size() == 0 || oneIndices.size() == 0) { return maxValueFrom(colIndex - 1, elmIndices, arr); } int zeroResult = maxValueFrom(colIndex - 1, zeroIndices, arr); int oneResult = maxValueFrom(colIndex - 1, oneIndices, arr); return Math.min( Math.max(zeroResult, (1 << colIndex) + oneResult), Math.max(oneResult, (1 << colIndex) + zeroResult) ); } void xorBitAt(int bitIndex, int[] arr) { int mask = 1 << bitIndex; for (int i = arr.length - 1; i >= 0; --i) { arr[i] ^= mask; } } List<Integer> collectBits(int bit, int bitIndex, List<Integer> indices, int[] arr) { List<Integer> result = new ArrayList<>(); for (int index : indices) { if (bit == bitAt(bitIndex, arr[index])) { result.add(index); } } return result; } int bitCount(int bit, int colIndex, List<Integer> indices, int[] arr) { int result = 0; for (int elmIndex : indices) { if (bit == bitAt(colIndex, arr[elmIndex])) { ++result; } } return result; } int bitAt(int bitIndex, int x) { return (x >> bitIndex) & 1; } } abstract class Core { protected abstract void solve() throws Exception; private static final int BUFFER_SIZE = (1 << 13); private static final int WHITE_SPACE = 32; private static final byte[] IN_BUFFER = new byte[BUFFER_SIZE]; private static final byte[] OUT_BUFFER = new byte[BUFFER_SIZE]; private int inNextByte; private int inNextIndex; private int inReadByteCount; private int outNextIndex; private InputStream in = System.in; private OutputStream out = System.out; private PrintStream info = System.err; private boolean showTrace; private boolean runOnEditor; private boolean inputFromLocal; private boolean outputToLocal; protected Core(String[] args) { try { start(args); } catch (Exception e) { e.printStackTrace(); } } private void start(String[] args) throws Exception { if (args != null) { if (args.length > 0) { showTrace = "1".equals(args[0].split(":")[1]); } if (args.length > 1) { runOnEditor = "1".equals(args[1].split(":")[1]); } if (args.length > 2) { inputFromLocal = "1".equals(args[2].split(":")[1]); } if (args.length > 3) { outputToLocal = "1".equals(args[3].split(":")[1]); } } if (inputFromLocal) { String fs = File.separator; String root = new File("").getAbsolutePath(); String inPath = String.format("%s%s%s", root, fs, "in.txt"); if (runOnEditor) { inPath = String.format("%s%s%s%s%s%s%s", root, fs, "src", fs, "testdata", fs, "in.txt"); } if (showTrace) { info.println("Input: " + inPath); } in = new FileInputStream(inPath); } else if (showTrace) { info.println("Input: Console"); } if (outputToLocal) { String fs = File.separator; String root = new File("").getAbsolutePath(); String outPath = String.format("%s%s%s", root, fs, "out.txt"); if (runOnEditor) { outPath = String.format("%s%s%s%s%s%s%s", root, fs, "src", fs, "testdata", fs, "out.txt"); } if (showTrace) { info.println("Output: " + outPath); } out = new FileOutputStream(outPath); } else if (showTrace) { info.println("Output: Console"); } long start = 0; if (showTrace) { start = System.currentTimeMillis(); } nextByte(); solve(); in.close(); flushOutBuf(); if (showTrace) { info.printf("\nSolve completed in %.3f [s]\n", (System.currentTimeMillis() - start) / 1000.0); } } private int nextByte() throws IOException { if (inNextIndex >= inReadByteCount) { inReadByteCount = in.read(IN_BUFFER, 0, BUFFER_SIZE); if (inReadByteCount == -1) { return (inNextByte = -1); } inNextIndex = 0; } return (inNextByte = IN_BUFFER[inNextIndex++]); } protected final char nc() throws IOException { while (inNextByte <= WHITE_SPACE) { nextByte(); } char res = (char) inNextByte; nextByte(); return res; } protected final int ni() throws IOException { int res = 0; while (inNextByte <= WHITE_SPACE) { nextByte(); } boolean minus = (inNextByte == '-'); if (minus) { nextByte(); } if (inNextByte < '0' || inNextByte > '9') { throw new RuntimeException("Invalid integer value format to read"); } do { res = (res << 1) + (res << 3) + inNextByte - '0'; } while (nextByte() >= '0' && inNextByte <= '9'); return minus ? -res : res; } protected final long nl() throws IOException { long res = 0; while (inNextByte <= WHITE_SPACE) { nextByte(); } boolean minus = (inNextByte == '-'); if (minus) { nextByte(); } if (inNextByte < '0' || inNextByte > '9') { throw new RuntimeException("Invalid long value format to read"); } do { res = (res << 1) + (res << 3) + inNextByte - '0'; } while (nextByte() >= '0' && inNextByte <= '9'); return minus ? -res : res; } protected final double nd() throws IOException { double pre = 0.0, suf = 0.0, div = 1.0; while (inNextByte <= WHITE_SPACE) { nextByte(); } boolean minus = (inNextByte == '-'); if (minus) { nextByte(); } if (inNextByte < '0' || inNextByte > '9') { throw new RuntimeException("Invalid double value format to read"); } do { pre = 10 * pre + (inNextByte - '0'); } while (nextByte() >= '0' && inNextByte <= '9'); if (inNextByte == '.') { while (nextByte() >= '0' && inNextByte <= '9') { suf += (inNextByte - '0') / (div *= 10); } } return minus ? -(pre + suf) : (pre + suf); } protected final String ns() throws IOException { while (inNextByte <= WHITE_SPACE) { nextByte(); } StringBuilder sb = new StringBuilder(); while (inNextByte > WHITE_SPACE) { sb.append((char) inNextByte); nextByte(); } return sb.toString(); } protected final char[] nc(int n) throws IOException { char[] a = new char[n]; for (int i = 0; i < n; ++i) { a[i] = nc(); } return a; } protected final char[][] nc(int r, int c) throws IOException { char[][] a = new char[r][c]; for (int i = 0; i < r; ++i) { a[i] = nc(c); } return a; } protected final int[] ni(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = ni(); } return a; } protected final int[][] ni(int r, int c) throws IOException { int[][] a = new int[r][c]; for (int i = 0; i < r; ++i) { a[i] = ni(c); } return a; } protected final long[] nl(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; ++i) { a[i] = nl(); } return a; } protected final long[][] nl(int r, int c) throws IOException { long[][] a = new long[r][c]; for (int i = 0; i < r; ++i) { a[i] = nl(c); } return a; } protected final double[] nd(int n) throws IOException { double[] a = new double[n]; for (int i = 0; i < n; ++i) { a[i] = nd(); } return a; } protected final double[][] nd(int r, int c) throws IOException { double[][] a = new double[r][c]; for (int i = 0; i < r; ++i) { a[i] = nd(c); } return a; } protected final String[] ns(int n) throws IOException { String[] a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = ns(); } return a; } protected final String[][] ns(int r, int c) throws IOException { String[][] a = new String[r][c]; for (int i = 0; i < r; ++i) { a[i] = ns(c); } return a; } protected final void flushOutBuf() { try { if (outNextIndex <= 0) { return; } out.write(OUT_BUFFER, 0, outNextIndex); out.flush(); outNextIndex = 0; } catch (Exception e) { e.printStackTrace(); } } protected final void print(String s) { if (s == null) { s = "null"; } for (int i = 0, N = s.length(); i < N; ++i) { OUT_BUFFER[outNextIndex++] = (byte) s.charAt(i); if (outNextIndex >= BUFFER_SIZE) { flushOutBuf(); } } } protected final void println(String s) { print(s); print('\n'); } protected final void print(Object obj) { if (obj == null) { print("null"); } else { print(obj.toString()); } } protected final void println(Object obj) { print(obj); print('\n'); } protected final void print(String format, Object... args) { if (args != null) { format = String.format(format, args); } print(format); } protected final void println(String format, Object... args) { if (args != null) { format = String.format(format, args); } println(format); } protected final void debug(String format, Object... args) { if (args != null) { format = String.format(format, args); } info.print(format); } protected final void debugln(String format, Object... args) { if (args != null) { format = String.format(format, args); } info.println(format); } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
df30f683013cf7bdf99eb5a65d8dde91
train_003.jsonl
1578665100
Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.List; //javac Main.java & java Main showTrace:1 runOnEditor:0 inputFromLocal:1 outputToLocal:0 //javac Main.java ; java Main showTrace:1 runOnEditor:1 inputFromLocal:0 outputToLocal:0 public class Main extends Core { protected static final int MOD = (int) 1E9 + 7; public Main(String[] args) { super(args); } public static void main(String[] args) { new Main(args); } @Override protected void solve() throws Exception { int N = ni(); int[] arr = ni(N); List<Integer> indices = new ArrayList<>(); for (int i = 0; i < N; ++i) { indices.add(i); } println(maxValueFrom(31, indices, arr)); } int maxValueFrom(int colIndex, List<Integer> indices, int[] arr) { if (colIndex < 0) { return 0; } List<Integer> zeroIndices = new ArrayList<>(); List<Integer> oneIndices = new ArrayList<>(); // Check bit at colIndex is 0 or 1 to divide 2 index-groups for (int index : indices) { if ((arr[index] & (1 << colIndex)) > 0) { oneIndices.add(index); } else { zeroIndices.add(index); } } if (zeroIndices.size() == 0 || oneIndices.size() == 0) { return maxValueFrom(colIndex - 1, indices, arr); } int childZeroResult = maxValueFrom(colIndex - 1, zeroIndices, arr); int childOneResult = maxValueFrom(colIndex - 1, oneIndices, arr); // Have 2 cases here, xor at colIndex with 0 or 1 to get min of max-results. return Math.min((1 << colIndex) + childOneResult, (1 << colIndex) + childZeroResult); } } abstract class Core { protected abstract void solve() throws Exception; private static final int BUFFER_SIZE = (1 << 13); private static final int WHITE_SPACE = 32; private static final byte[] IN_BUFFER = new byte[BUFFER_SIZE]; private static final byte[] OUT_BUFFER = new byte[BUFFER_SIZE]; private int inNextByte; private int inNextIndex; private int inReadByteCount; private int outNextIndex; private InputStream in = System.in; private OutputStream out = System.out; private PrintStream info = System.err; private boolean showTrace; private boolean runOnEditor; private boolean inputFromLocal; private boolean outputToLocal; protected Core(String[] args) { try { start(args); } catch (Exception e) { e.printStackTrace(); } } private void start(String[] args) throws Exception { if (args != null) { if (args.length > 0) { showTrace = "1".equals(args[0].split(":")[1]); } if (args.length > 1) { runOnEditor = "1".equals(args[1].split(":")[1]); } if (args.length > 2) { inputFromLocal = "1".equals(args[2].split(":")[1]); } if (args.length > 3) { outputToLocal = "1".equals(args[3].split(":")[1]); } } if (inputFromLocal) { String fs = File.separator; String root = new File("").getAbsolutePath(); String inPath = String.format("%s%s%s", root, fs, "in.txt"); if (runOnEditor) { inPath = String.format("%s%s%s%s%s%s%s", root, fs, "src", fs, "testdata", fs, "in.txt"); } if (showTrace) { info.println("Input: " + inPath); } in = new FileInputStream(inPath); } else if (showTrace) { info.println("Input: Console"); } if (outputToLocal) { String fs = File.separator; String root = new File("").getAbsolutePath(); String outPath = String.format("%s%s%s", root, fs, "out.txt"); if (runOnEditor) { outPath = String.format("%s%s%s%s%s%s%s", root, fs, "src", fs, "testdata", fs, "out.txt"); } if (showTrace) { info.println("Output: " + outPath); } out = new FileOutputStream(outPath); } else if (showTrace) { info.println("Output: Console"); } long start = 0; if (showTrace) { start = System.currentTimeMillis(); } nextByte(); solve(); in.close(); flushOutBuf(); if (showTrace) { info.printf("\nSolve completed in %.3f [s]\n", (System.currentTimeMillis() - start) / 1000.0); } } private int nextByte() throws IOException { if (inNextIndex >= inReadByteCount) { inReadByteCount = in.read(IN_BUFFER, 0, BUFFER_SIZE); if (inReadByteCount == -1) { return (inNextByte = -1); } inNextIndex = 0; } return (inNextByte = IN_BUFFER[inNextIndex++]); } protected final char nc() throws IOException { while (inNextByte <= WHITE_SPACE) { nextByte(); } char res = (char) inNextByte; nextByte(); return res; } protected final int ni() throws IOException { int res = 0; while (inNextByte <= WHITE_SPACE) { nextByte(); } boolean minus = (inNextByte == '-'); if (minus) { nextByte(); } if (inNextByte < '0' || inNextByte > '9') { throw new RuntimeException("Invalid integer value format to read"); } do { res = (res << 1) + (res << 3) + inNextByte - '0'; } while (nextByte() >= '0' && inNextByte <= '9'); return minus ? -res : res; } protected final long nl() throws IOException { long res = 0; while (inNextByte <= WHITE_SPACE) { nextByte(); } boolean minus = (inNextByte == '-'); if (minus) { nextByte(); } if (inNextByte < '0' || inNextByte > '9') { throw new RuntimeException("Invalid long value format to read"); } do { res = (res << 1) + (res << 3) + inNextByte - '0'; } while (nextByte() >= '0' && inNextByte <= '9'); return minus ? -res : res; } protected final double nd() throws IOException { double pre = 0.0, suf = 0.0, div = 1.0; while (inNextByte <= WHITE_SPACE) { nextByte(); } boolean minus = (inNextByte == '-'); if (minus) { nextByte(); } if (inNextByte < '0' || inNextByte > '9') { throw new RuntimeException("Invalid double value format to read"); } do { pre = 10 * pre + (inNextByte - '0'); } while (nextByte() >= '0' && inNextByte <= '9'); if (inNextByte == '.') { while (nextByte() >= '0' && inNextByte <= '9') { suf += (inNextByte - '0') / (div *= 10); } } return minus ? -(pre + suf) : (pre + suf); } protected final String ns() throws IOException { while (inNextByte <= WHITE_SPACE) { nextByte(); } StringBuilder sb = new StringBuilder(); while (inNextByte > WHITE_SPACE) { sb.append((char) inNextByte); nextByte(); } return sb.toString(); } protected final char[] nc(int n) throws IOException { char[] a = new char[n]; for (int i = 0; i < n; ++i) { a[i] = nc(); } return a; } protected final char[][] nc(int r, int c) throws IOException { char[][] a = new char[r][c]; for (int i = 0; i < r; ++i) { a[i] = nc(c); } return a; } protected final int[] ni(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = ni(); } return a; } protected final int[][] ni(int r, int c) throws IOException { int[][] a = new int[r][c]; for (int i = 0; i < r; ++i) { a[i] = ni(c); } return a; } protected final long[] nl(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; ++i) { a[i] = nl(); } return a; } protected final long[][] nl(int r, int c) throws IOException { long[][] a = new long[r][c]; for (int i = 0; i < r; ++i) { a[i] = nl(c); } return a; } protected final double[] nd(int n) throws IOException { double[] a = new double[n]; for (int i = 0; i < n; ++i) { a[i] = nd(); } return a; } protected final double[][] nd(int r, int c) throws IOException { double[][] a = new double[r][c]; for (int i = 0; i < r; ++i) { a[i] = nd(c); } return a; } protected final String[] ns(int n) throws IOException { String[] a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = ns(); } return a; } protected final String[][] ns(int r, int c) throws IOException { String[][] a = new String[r][c]; for (int i = 0; i < r; ++i) { a[i] = ns(c); } return a; } private final void flushOutBuf() { try { if (outNextIndex <= 0) { return; } out.write(OUT_BUFFER, 0, outNextIndex); out.flush(); outNextIndex = 0; } catch (Exception e) { e.printStackTrace(); } } protected final void print(String s) { if (s == null) { s = "null"; } for (int i = 0, N = s.length(); i < N; ++i) { OUT_BUFFER[outNextIndex++] = (byte) s.charAt(i); if (outNextIndex >= BUFFER_SIZE) { flushOutBuf(); } } } protected final void println(String s) { print(s); print('\n'); } protected final void print(Object obj) { if (obj == null) { print("null"); } else { print(obj.toString()); } } protected final void println(Object obj) { print(obj); print('\n'); } protected final void print(String format, Object... args) { if (args != null) { format = String.format(format, args); } print(format); } protected final void println(String format, Object... args) { if (args != null) { format = String.format(format, args); } println(format); } protected final void debug(String format, Object... args) { if (args != null) { format = String.format(format, args); } info.print(format); } protected final void debugln(String format, Object... args) { if (args != null) { format = String.format(format, args); } info.println(format); } }
Java
["3\n1 2 3", "2\n1 5"]
1 second
["2", "4"]
NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.
Java 8
standard input
[ "dp", "greedy", "bitmasks", "divide and conquer", "brute force", "dfs and similar", "trees", "strings" ]
d17d2fcfb088bf51e9c1f3fce4133a94
The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).
1,900
Print one integer β€” the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.
standard output
PASSED
9a113fa9330a577da22f339cd691a1e4
train_003.jsonl
1605796500
You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types: empty string; '(' + RBS + ')'; '[' + RBS + ']'; RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?
256 megabytes
import java.util.*; import java.io.*; public class sol { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String giveMeFile) throws IOException { File file = new File("input.txt"); br = new BufferedReader(new FileReader(file)); } 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 boolean[] SES(int n) { // SES Stands for SieveOfEratoSthenes boolean isPrime[] = new boolean[n + 1]; Arrays.fill(isPrime, true); isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i <= n; i++) { for (int j = 2 * i; j <= n; j += i) { isPrime[j] = false; } } return isPrime; } public static int gcd(int a, int b) { return a % b == 0 ? b : gcd(b, a % b); } public static long fastPower(long a, long b, long n) { long res = 1; while (b > 0) { if ((b & 1) != 0) { res = (res % n * a % n) % n; } a = (a % n * a % n) % n; b = b >> 1; // dividing by 2 } return res; } public static void main(String[] args) throws IOException { // ************** Providing input File // File file = new File("input.txt"); // BufferedReader br = new BufferedReader(new FileReader(file)); // *************** Input for Online Judges with Buffered Reader // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // ************* Input for Online Judges with Scanner class // Reading with Scanner class // Scanner sc = new Scanner(file); // sc.useDelimiter("\\Z"); // ***************** Printing Outout to output file. // PrintWriter printWriter = new PrintWriter(new BufferedWriter(new // FileWriter("output.txt"))); // printWriter.println("something here"); // printWriter.close(); --->> // only this close method will flush the output // from the buffer to the output file. FastReader read = new FastReader(); int t = read.nextInt(); while(t-- != 0) { String s = read.next(); int pair = 0; int ob = 0; int cb = 0; int os = 0; int cs = 0; for(int i = 0;i<s.length();i++) { if(s.charAt(i) == '(') { ob++; } else if(s.charAt(i) == '[') { os++; } else if(ob > 0 && s.charAt(i) == ')') { ob--; pair++; } else if(os > 0 && s.charAt(i) == ']') { os--; pair++; } } System.out.println(pair); } } }
Java
["5\n()\n[]()\n([)]\n)]([\n)[(]"]
1 second
["1\n2\n2\n0\n1"]
NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.
Java 8
standard input
[ "greedy" ]
db9cec57d8ed5e914818ce9b439eb0f9
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β€” the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
800
For each testcase print a single integerΒ β€” the maximum number of moves you can perform on a given string $$$s$$$.
standard output