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
f185fa29d22ea073af0e26359f51fb13
train_002.jsonl
1581257100
Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
256 megabytes
import java.io.*; import java.util.*; import java.util.ArrayList; import java.util.Scanner; public class P1299A { public static void main(String[] args) { InputReader sc = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int n = sc.nextInt(); BitCount [] bitCount = new BitCount[33]; List<Integer> arr = new ArrayList<>(); for(int i = 0;i<n;i++) { arr.add(sc.nextInt()); updateSetBits(bitCount, arr.get(i), i); } int maxPos = -1; //Get the first element position for(int i = 32;i>=0;i--) { if(!Objects.isNull(bitCount[i]) && bitCount[i].count == 1) { maxPos = bitCount[i].positions.get(0); break; } } if(maxPos == -1) arr.forEach(el -> System.out.print(el + " ")); else { int temp = arr.get(0); arr.set(0,arr.get(maxPos)); arr.set(maxPos, temp); arr.forEach(el -> System.out.print(el + " ")); } } private static void updateSetBits(BitCount[] bitCount, Integer number, Integer i) { while(number > 0) { int pow = (int) (Math.log(number)/Math.log(2)); if(Objects.isNull(bitCount[pow])) { bitCount[pow] = new BitCount(); } bitCount[pow].count++; bitCount[pow].positions.add(i); number-= (int) Math.pow(2,pow); } } private static class BitCount{ int count = 0; List<Integer> positions; public BitCount() { this.count = 0; this.positions = new ArrayList<>(); } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) { return -1; } } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["4\n4 0 11 6", "1\n13"]
1 second
["11 6 4 0", "13"]
NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer.
Java 11
standard input
[ "greedy", "math", "brute force" ]
14fd47f6f0fcbdb16dbd73dcca8a782f
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different.
1,500
Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
standard output
PASSED
ef762fb9c6514718984510c155dccc53
train_002.jsonl
1581257100
Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
256 megabytes
import java.io.*; import java.util.*; import java.util.ArrayList; import java.util.Scanner; public class P1299A { public static void main(String[] args) { InputReader sc = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int n = sc.nextInt(); BitCount [] bitCount = new BitCount[65]; List<Integer> arr = new ArrayList<>(); for(int i = 0;i<n;i++) arr.add(sc.nextInt()); //Get the positions of set bits for(int i = 0;i<n;i++) { updateSetBits(bitCount, arr.get(i), i); } int maxPos = -1; //Get the first element position for(int i = 64;i>=0;i--) { if(!Objects.isNull(bitCount[i]) && bitCount[i].count == 1) { maxPos = bitCount[i].positions.get(0); break; } } if(maxPos == -1) arr.forEach(el -> System.out.print(el + " ")); else { int temp = arr.get(0); arr.set(0,arr.get(maxPos)); arr.set(maxPos, temp); arr.forEach(el -> System.out.print(el + " ")); } } private static void updateSetBits(BitCount[] bitCount, Integer number, Integer i) { while(number > 0) { int pow = (int) (Math.log(number)/Math.log(2)); if(Objects.isNull(bitCount[pow])) { bitCount[pow] = new BitCount(); } bitCount[pow].count++; bitCount[pow].positions.add(i); number-= (int) Math.pow(2,pow); } } private static class BitCount{ int count = 0; List<Integer> positions; public BitCount() { this.count = 0; this.positions = new ArrayList<>(); } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) { return -1; } } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["4\n4 0 11 6", "1\n13"]
1 second
["11 6 4 0", "13"]
NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer.
Java 11
standard input
[ "greedy", "math", "brute force" ]
14fd47f6f0fcbdb16dbd73dcca8a782f
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different.
1,500
Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
standard output
PASSED
5e9f3d04ba9b1d69241d527998854f73
train_002.jsonl
1581257100
Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
256 megabytes
import java.io.*; import java.util.*; import java.util.ArrayList; import java.util.Scanner; public class P1299A { public static void main(String[] args) { InputReader sc = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int n = sc.nextInt(); BitCount [] bitCount = new BitCount[33]; List<Integer> arr = new ArrayList<>(); for(int i = 0;i<n;i++) { arr.add(sc.nextInt()); updateSetBits(bitCount, arr.get(i), i); } int maxPos = -1; //Get the first element position for(int i = 32;i>=0;i--) { if(!Objects.isNull(bitCount[i]) && bitCount[i].count == 1) { maxPos = bitCount[i].positions.get(0); break; } } if(maxPos == -1) { StringBuilder sb = new StringBuilder(); arr.forEach(el -> sb.append(el).append(" ")); System.out.print(sb); } else { int temp = arr.get(0); arr.set(0,arr.get(maxPos)); arr.set(maxPos, temp); StringBuilder sb = new StringBuilder(); arr.forEach(el -> sb.append(el).append(" ")); System.out.print(sb); } } private static void updateSetBits(BitCount[] bitCount, Integer number, Integer i) { while(number > 0) { int pow = (int) (Math.log(number)/Math.log(2)); if(Objects.isNull(bitCount[pow])) { bitCount[pow] = new BitCount(); } bitCount[pow].count++; bitCount[pow].positions.add(i); number-= (int) Math.pow(2,pow); } } private static class BitCount{ int count = 0; List<Integer> positions; public BitCount() { this.count = 0; this.positions = new ArrayList<>(); } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) { return -1; } } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["4\n4 0 11 6", "1\n13"]
1 second
["11 6 4 0", "13"]
NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer.
Java 11
standard input
[ "greedy", "math", "brute force" ]
14fd47f6f0fcbdb16dbd73dcca8a782f
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different.
1,500
Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
standard output
PASSED
b036a97025e9f9ddba22c05f82a09f63
train_002.jsonl
1581257100
Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
256 megabytes
import java.util.*; import java.util.ArrayList; import java.util.Scanner; public class P1299A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); BitCount [] bitCount = new BitCount[65]; List<Integer> arr = new ArrayList<>(); for(int i = 0;i<n;i++) arr.add(sc.nextInt()); //Get the positions of set bits for(int i = 0;i<n;i++) { updateSetBits(bitCount, arr.get(i), i); } int maxPos = -1; //Get the first element position for(int i = 64;i>=0;i--) { if(!Objects.isNull(bitCount[i]) && bitCount[i].count == 1) { maxPos = bitCount[i].positions.get(0); break; } } if(maxPos == -1) arr.forEach(el -> System.out.print(el + " ")); else { int temp = arr.get(0); arr.set(0,arr.get(maxPos)); arr.set(maxPos, temp); arr.forEach(el -> System.out.print(el + " ")); } } private static void updateSetBits(BitCount[] bitCount, Integer number, Integer i) { while(number > 0) { int pow = (int) (Math.log(number)/Math.log(2)); if(Objects.isNull(bitCount[pow])) { bitCount[pow] = new BitCount(); } bitCount[pow].count++; bitCount[pow].positions.add(i); number-= (int) Math.pow(2,pow); } } private static class BitCount{ int count = 0; List<Integer> positions; public BitCount() { this.count = 0; this.positions = new ArrayList<>(); } } }
Java
["4\n4 0 11 6", "1\n13"]
1 second
["11 6 4 0", "13"]
NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer.
Java 11
standard input
[ "greedy", "math", "brute force" ]
14fd47f6f0fcbdb16dbd73dcca8a782f
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different.
1,500
Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
standard output
PASSED
d1814c83a299eb5b0dae5eaaf3140b37
train_002.jsonl
1581257100
Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
256 megabytes
import java.io.*; import java.util.*; import java.util.ArrayList; import java.util.Scanner; public class P1299A { public static void main(String[] args) { //System.out.print((1<<2)); InputReader sc = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int n = sc.nextInt(); BitCount [] bitCount = new BitCount[31]; List<Integer> arr = new ArrayList<>(); for(int i = 0;i<n;i++) { arr.add(sc.nextInt()); updateSetBits(bitCount, arr.get(i), i); } int maxPos = -1; //Get the first element position for(int i = 30;i>=0;i--) { if(!Objects.isNull(bitCount[i]) && bitCount[i].count == 1) { maxPos = bitCount[i].position; break; } } if(maxPos == -1) { StringBuilder sb = new StringBuilder(); arr.forEach(el -> sb.append(el).append(" ")); System.out.print(sb); } else { int temp = arr.get(0); arr.set(0,arr.get(maxPos)); arr.set(maxPos, temp); StringBuilder sb = new StringBuilder(); arr.forEach(el -> sb.append(el).append(" ")); System.out.print(sb); } } private static void updateSetBits(BitCount[] bitCount, Integer number, Integer i) { while(number > 0) { int pow = (int) (Math.log(number)/Math.log(2)); if(Objects.isNull(bitCount[pow])) { bitCount[pow] = new BitCount(); } bitCount[pow].count++; bitCount[pow].position = i; //number-= (int) Math.pow(2,pow); number = (1<<(pow))^number; } } private static class BitCount{ int count = 0; int position; public BitCount() { this.count = 0; this.position = -1; } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) { return -1; } } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["4\n4 0 11 6", "1\n13"]
1 second
["11 6 4 0", "13"]
NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer.
Java 11
standard input
[ "greedy", "math", "brute force" ]
14fd47f6f0fcbdb16dbd73dcca8a782f
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different.
1,500
Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
standard output
PASSED
79a83a6e0f4a977406eac96d90efc4c9
train_002.jsonl
1581257100
Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
256 megabytes
import java.util.*; import java.util.ArrayList; import java.util.Scanner; public class P1299A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); BitCount [] bitCount = new BitCount[65]; List<Integer> arr = new ArrayList<>(); for(int i = 0;i<n;i++) arr.add(sc.nextInt()); //Get the positions of set bits for(int i = 0;i<n;i++) { updateSetBits(bitCount, arr.get(i), i); } int maxPos = -1; //Get the first element position for(int i = 64;i>=0;i--) { if(!Objects.isNull(bitCount[i]) && bitCount[i].count == 1) { maxPos = bitCount[i].positions.get(0); break; } } if(maxPos == -1) arr.forEach(el -> System.out.print(el + " ")); else { arr.add(0, arr.get(maxPos)); arr.remove(maxPos+1); arr.forEach(el -> System.out.print(el + " ")); } } private static void updateSetBits(BitCount[] bitCount, Integer number, Integer i) { while(number > 0) { int pow = (int) (Math.log(number)/Math.log(2)); if(Objects.isNull(bitCount[pow])) { bitCount[pow] = new BitCount(); } bitCount[pow].count++; bitCount[pow].positions.add(i); number-= (int) Math.pow(2,pow); } } private static class BitCount{ int count = 0; List<Integer> positions; public BitCount() { this.count = 0; this.positions = new ArrayList<>(); } } }
Java
["4\n4 0 11 6", "1\n13"]
1 second
["11 6 4 0", "13"]
NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer.
Java 11
standard input
[ "greedy", "math", "brute force" ]
14fd47f6f0fcbdb16dbd73dcca8a782f
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different.
1,500
Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
standard output
PASSED
3bd954cb98e1e8a965bcc1e0b3a89d41
train_002.jsonl
1581257100
Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
256 megabytes
import java.io.*; import java.util.*; import java.util.ArrayList; import java.util.Scanner; public class P1299A { public static void main(String[] args) { InputReader sc = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int n = sc.nextInt(); BitCount [] bitCount = new BitCount[65]; List<Integer> arr = new ArrayList<>(); for(int i = 0;i<n;i++) { arr.add(sc.nextInt()); updateSetBits(bitCount, arr.get(i), i); } int maxPos = -1; //Get the first element position for(int i = 64;i>=0;i--) { if(!Objects.isNull(bitCount[i]) && bitCount[i].count == 1) { maxPos = bitCount[i].positions.get(0); break; } } if(maxPos == -1) arr.forEach(el -> System.out.print(el + " ")); else { int temp = arr.get(0); arr.set(0,arr.get(maxPos)); arr.set(maxPos, temp); arr.forEach(el -> System.out.print(el + " ")); } } private static void updateSetBits(BitCount[] bitCount, Integer number, Integer i) { while(number > 0) { int pow = (int) (Math.log(number)/Math.log(2)); if(Objects.isNull(bitCount[pow])) { bitCount[pow] = new BitCount(); } bitCount[pow].count++; bitCount[pow].positions.add(i); number-= (int) Math.pow(2,pow); } } private static class BitCount{ int count = 0; List<Integer> positions; public BitCount() { this.count = 0; this.positions = new ArrayList<>(); } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) { return -1; } } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["4\n4 0 11 6", "1\n13"]
1 second
["11 6 4 0", "13"]
NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer.
Java 11
standard input
[ "greedy", "math", "brute force" ]
14fd47f6f0fcbdb16dbd73dcca8a782f
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different.
1,500
Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
standard output
PASSED
1ef372cf748bb6ad5853cfbbbfdd6f6b
train_002.jsonl
1581257100
Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
256 megabytes
import java.io.*; import java.util.*; import java.util.ArrayList; import java.util.Scanner; public class P1299A { public static void main(String[] args) { //System.out.print((1<<2)); InputReader sc = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int n = sc.nextInt(); BitCount [] bitCount = new BitCount[33]; List<Integer> arr = new ArrayList<>(); for(int i = 0;i<n;i++) { arr.add(sc.nextInt()); updateSetBits(bitCount, arr.get(i), i); } int maxPos = -1; //Get the first element position for(int i = 32;i>=0;i--) { if(!Objects.isNull(bitCount[i]) && bitCount[i].count == 1) { maxPos = bitCount[i].positions.get(0); break; } } if(maxPos == -1) { StringBuilder sb = new StringBuilder(); arr.forEach(el -> sb.append(el).append(" ")); System.out.print(sb); } else { int temp = arr.get(0); arr.set(0,arr.get(maxPos)); arr.set(maxPos, temp); StringBuilder sb = new StringBuilder(); arr.forEach(el -> sb.append(el).append(" ")); System.out.print(sb); } } private static void updateSetBits(BitCount[] bitCount, Integer number, Integer i) { while(number > 0) { int pow = (int) (Math.log(number)/Math.log(2)); if(Objects.isNull(bitCount[pow])) { bitCount[pow] = new BitCount(); } bitCount[pow].count++; bitCount[pow].positions.add(i); //number-= (int) Math.pow(2,pow); number = (1<<(pow))^number; } } private static class BitCount{ int count = 0; List<Integer> positions; public BitCount() { this.count = 0; this.positions = new ArrayList<>(); } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) { return -1; } } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["4\n4 0 11 6", "1\n13"]
1 second
["11 6 4 0", "13"]
NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer.
Java 11
standard input
[ "greedy", "math", "brute force" ]
14fd47f6f0fcbdb16dbd73dcca8a782f
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different.
1,500
Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
standard output
PASSED
3889c23a4b205bf90716153d7ef6701e
train_002.jsonl
1581257100
Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
256 megabytes
import javax.swing.*; import java.awt.desktop.SystemSleepEvent; import java.util.*; import java.io.*; public class Main { public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } } public class pair { int a; int b; pair(int p, int q) { a = p; b = q; } public int hashCode() { return new Integer(a).hashCode() * 31 + new Integer(b).hashCode(); } } public static int gcd(int a, int b) { if (a == 1 || b == 1) return 1; if (a == 0) return b; if (b == 0) return a; return gcd(b % a, a); } public static void main(String[] args) { FastReader s = new FastReader(); int n=s.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=s.nextInt(); String[] arr=new String[n]; String str; for(int i=0;i<n;i++) { arr[i] = Integer.toBinaryString(a[i]); arr[i] = r(arr[i]); //System.out.println(arr[i]); } int ans=0; for(int i=0;i<n;i++) { ans = Integer.parseInt(String.valueOf(ans)) | a[i]; //System.out.println(ans); } //System.out.println(Integer.toBinaryString(ans)); int l = String.valueOf(Integer.toBinaryString(ans)).length(); //System.out.println(l); int temp=0; for(int i=0;i<50;i++) { int ct=0; for(int j=0;j<n;j++) { //System.out.println(arr[j].charAt(i)); if(arr[j].charAt(i)=='1') { ct++; temp = j; } } if(ct==1) { break; } } //System.out.println(temp); int[] b=new int[n]; b[0] = a[temp]; int c=0; int ct=1; for(int i=0;i<n;i++) { if(c!=temp) { b[ct] = a[c]; ct++; } c++; } for(int i=0;i<n;i++) System.out.print(b[i] + " "); } public static String r(String x) { int l=x.length(); int temp = 50-l; String str = ""; for(int i=0;i<temp;i++) str = str + '0'; str = str + x; return str; } }
Java
["4\n4 0 11 6", "1\n13"]
1 second
["11 6 4 0", "13"]
NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer.
Java 11
standard input
[ "greedy", "math", "brute force" ]
14fd47f6f0fcbdb16dbd73dcca8a782f
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different.
1,500
Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
standard output
PASSED
a9ef5dfbcbefdb8a1cce7f7c09840562
train_002.jsonl
1581257100
Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.File; import java.util.ArrayList; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author lewin */ 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); AAnuHasAFunction solver = new AAnuHasAFunction(); solver.solve(1, in, out); out.close(); } static class AAnuHasAFunction { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] arr = in.readIntArray(n); int ALL = (1 << 31) - 1; for (int i = 0; i < n; i++) arr[i] ^= ALL; int[] prefand = new int[n]; int[] suffand = new int[n]; prefand[0] = arr[0]; for (int i = 1; i < n; i++) { prefand[i] = prefand[i - 1] & arr[i]; } suffand[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) { suffand[i] = suffand[i + 1] & arr[i]; } int best = -1; int idx = 0; for (int i = 0; i < n; i++) { int o = arr[i] ^ ALL; if (i > 0) o = o & prefand[i - 1]; if (i + 1 < n) o = o & suffand[i + 1]; if (o > best) { best = o; idx = i; } } int t = arr[idx]; arr[idx] = arr[0]; arr[0] = t; for (int i = 0; i < n; i++) arr[i] ^= ALL; int a = arr[0]; for (int i = 1; i < n; i++) { a = (a | arr[i]) - arr[i]; } Debug.print(a); out.println(arr); } } static class Debug { public static boolean DEBUG; static { try { DEBUG = System.getProperty("user.dir").contains("Dropbox"); } catch (Exception e) { DEBUG = false; } } private static ArrayList<String> getParams() { StackTraceElement[] t = Thread.currentThread().getStackTrace(); StackTraceElement up = t[3]; ArrayList<String> ret = new ArrayList<>(); String qqq = up.toString(); ret.add("." + up.getMethodName() + qqq.substring(qqq.indexOf("("), qqq.length())); try { BufferedReader br = new BufferedReader(new FileReader( new File("src/" + up.getClassName().replaceAll("\\.", "/") + ".java"))); int g = up.getLineNumber(); while (--g > 0) br.readLine(); String q = br.readLine(); String[] ss = q.split("Debug\\.print\\("); String[] qq = ss[1].substring(0, ss[1].lastIndexOf(")")).split(","); for (int i = 0; i < qq.length; i++) { ret.add(qq[i].trim()); } } catch (Exception e) { } for (int i = 0; i < 100; i++) ret.add("???"); return ret; } private static String toString(Object o) { if (o == null) { return "null"; } else if (o instanceof Object[]) { return Arrays.toString((Object[]) o); } else if (o instanceof char[]) { return new String((char[]) o); } else if (o instanceof int[]) { return Arrays.toString((int[]) o); } else if (o instanceof long[]) { return Arrays.toString((long[]) o); } else if (o instanceof double[]) { return Arrays.toString((double[]) o); } else if (o instanceof boolean[]) { return Arrays.toString((boolean[]) o); } else { return o.toString(); } } public static void print(Object x) { if (!DEBUG) return; ArrayList<String> s = getParams(); System.out.println(s.get(0) + ": " + s.get(1) + " = " + toString(x)); } } 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; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void println(int[] array) { print(array); writer.println(); } public void close() { writer.close(); } } }
Java
["4\n4 0 11 6", "1\n13"]
1 second
["11 6 4 0", "13"]
NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer.
Java 11
standard input
[ "greedy", "math", "brute force" ]
14fd47f6f0fcbdb16dbd73dcca8a782f
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different.
1,500
Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
standard output
PASSED
d2fd05296d016eb90e17c27a06a7827f
train_002.jsonl
1581257100
Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
256 megabytes
import java.util.*; import java.io.*; public class AnuIsBack{ public static void main(String[] args) throws IOException{ Reader in = new Reader(); int n = in.nextInt(); int[]a=new int[100005],b=new int[100005],l=new int[100005],r=new int[100005]; for (int i = 1; i <= n; i++) { a[i]=in.nextInt(); b[i]=~a[i]; } l[0]=r[n+1]=(~0); l[1]=b[1];for(int i=2;i<=n;++i)l[i]=l[i-1]&b[i]; r[n]=b[n];for(int i=n-1;i>0;--i)r[i]=r[i+1]&b[i]; int max=0; int ans=1; for (int i = 1; i <= n; i++) { if((l[i-1]&a[i]&r[i+1])>max){ans=i;max=(l[i-1]&a[i]&r[i+1]);} } System.out.print(a[ans]); for (int i = 1; i <= n; i++) { if(i!=ans){System.out.print(" "+a[i]);} } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["4\n4 0 11 6", "1\n13"]
1 second
["11 6 4 0", "13"]
NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer.
Java 11
standard input
[ "greedy", "math", "brute force" ]
14fd47f6f0fcbdb16dbd73dcca8a782f
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different.
1,500
Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
standard output
PASSED
21e9b2e502bf3c1106b878fa7481c164
train_002.jsonl
1581257100
Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
256 megabytes
import java.util.Scanner; public class Anu{ public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] A = new int[n]; boolean[] check = new boolean[30]; int[] store = new int[30]; boolean[] check2 = new boolean[30]; for (int i = 0; i < n; i++) { A[i]=in.nextInt(); for (int j = 0; j < 30; j++) { if(check2[j]){continue;} if((A[i]&(1<<j))>0){if(check[j]){check2[j]=true;}else{check[j]=true;store[j]=i;}} } } int first = -1; for (int i = 29; i >-1; i--) { if(check[i] && (!check2[i])){first=store[i];break;} } if(first==-1){for (int i = 0; i < n; i++) { System.out.print(A[i]+" "); }}else{ System.out.print(A[first]); for (int i = 0; i < n; i++) { if(i==first){continue;} System.out.print(" "+A[i]); } } in.close(); } }
Java
["4\n4 0 11 6", "1\n13"]
1 second
["11 6 4 0", "13"]
NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer.
Java 11
standard input
[ "greedy", "math", "brute force" ]
14fd47f6f0fcbdb16dbd73dcca8a782f
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different.
1,500
Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any.
standard output
PASSED
49b5624f28ce0560f840a8078cff4ec9
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
// -*- coding: utf-8 -*- //import java.awt.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream; if (args.length > 0 && args[0].equals("devTesting")) { try { inputStream = new FileInputStream(args[1]); } catch(FileNotFoundException e) { throw new RuntimeException(e); } } else { inputStream = System.in; } OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { int n, m; int[] p, s; void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); m = in.nextInt(); p = new int[n]; s = new int[m]; for (int i = 0; i < n; ++i) p[i] = in.nextInt(); for (int i = 0; i < m; ++i) s[i] = in.nextInt(); Map<Integer, Deque<Integer>> cp = new HashMap<>(); for (int i = 0; i < n; ++i) if (!cp.containsKey(p[i])) cp.put(p[i], new ArrayDeque<Integer>()); for (int i = 0; i < n; ++i) cp.get(p[i]).push(i); int adapters = 0, iter = 0, computers = 0; boolean okay = true; int[] b = new int[n], a = new int[m]; Arrays.fill(b, -1); BitSet check = new BitSet(); do { okay = true; for (int i = 0; i < m; ++i) if (!check.get(i) && cp.containsKey(s[i]) && !cp.get(s[i]).isEmpty()) { check.set(i); ++computers; b[cp.get(s[i]).pop()] = i; adapters += iter; a[i] = iter; } for (int i = 0; i < m; ++i) if (s[i] > 1) { okay = false; s[i] = (s[i] + 1) / 2; } ++iter; } while (!okay); int c = computers, u = adapters; out.println(c + " " + u); for (int i = 0; i < m; ++i) { if (i > 0) out.print(' '); out.print(a[i]); } out.println(); for (int i = 0; i < n; ++i) { if (i > 0) out.print(' '); out.print(b[i] + 1); } out.println(); } } 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) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public boolean hasInput() { try { if (tokenizer != null && tokenizer.hasMoreTokens()) { return true; } reader.mark(1); int ch = reader.read(); if (ch != -1) { reader.reset(); return true; } return false; } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
5206519817e48cbab8a3cf39c89100b1
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.util.*; import java.io.*; public class Main extends Reader { public static void main(String[] args) throws IOException { int n = ni(), m = ni(); int a[] = new int[n]; int aa[] = new int[n]; int bb[] = new int[m]; long b[] = new long[m]; Map<Integer, LinkedList<Integer>> map = new HashMap<>(); for (int i=0; i<n; i++) { int x = ni(); if (!map.containsKey(x)) map.put(x, new LinkedList<>()); map.get(x).add(i); } for (int i=0; i<m; i++) b[i] = nl() * m + i; Arrays.sort(b); int ans0 = 0, ans1 = 0; for (int i=0; i<m; i++) { int v = (int)(b[i]/m); int p = (int)(b[i]%m); int c = 0; while (v > 1 && !map.containsKey(v)) { v = (v+1)/2; c++; } if (map.containsKey(v)) { ans0++; ans1 += (bb[p] = c); LinkedList<Integer> tmp = map.get(v); aa[tmp.removeFirst()] = p + 1; if (tmp.isEmpty()) map.remove(v); } } System.out.println(ans0+" "+ans1); for (int i=0; i<m; i++) System.out.print(bb[i]+" "); System.out.println(); for (int i=0; i<n; i++) System.out.print(aa[i]+" "); } } class Reader { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer tokenizer = new StringTokenizer(""); /** call this method to change InputStream */ static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input) ); } /** get next word */ static String ns() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int ni() throws IOException { return Integer.parseInt( ns() ); } static double nd() throws IOException { return Double.parseDouble( ns() ); } static long nl() throws IOException { return Long.valueOf( ns() ); } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
1585661a8288f751e261aaf26f4d7a91
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.*; import java.util.*; public class E { public static void solution(BufferedReader reader, PrintWriter writer) throws IOException { In in = new In(reader); Out out = new Out(writer); int n = in.nextInt(), m = in.nextInt(); HashMap<Integer, LinkedList<Integer>> comp = new HashMap<Integer, LinkedList<Integer>>(); for (int i = 1; i <= n; i++) { int p = in.nextInt(); if (!comp.containsKey(p)) comp.put(p, new LinkedList<Integer>()); comp.get(p).add(i); } int[][] soc = new int[m][2]; for (int i = 0; i < m; i++) soc[i] = new int[] { in.nextInt(), i + 1 }; Arrays.sort(soc, new Comparator<int[]>() { @Override public int compare(int[] s1, int[] s2) { return Integer.compare(s1[0], s2[0]); } }); int c = 0, u = 0; int[] a = new int[m]; int[] b = new int[n]; next: for (int[] so : soc) { int cnt = 0; while (true) { if (comp.containsKey(so[0]) && !comp.get(so[0]).isEmpty()) { c++; u += cnt; a[so[1] - 1] = cnt; b[comp.get(so[0]).removeFirst() - 1] = so[1]; continue next; } if (so[0] == 1) break; so[0] = so[0] - so[0] / 2; cnt++; } } out.println(new int[] { c, u }); out.println(a); out.println(b); } protected static class Computer implements Comparable<Computer> { protected int id, p; public Computer(int id, int p) { super(); this.id = id; this.p = p; } @Override public int compareTo(Computer c) { if (p != c.p) return Integer.compare(p, c.p); return Integer.compare(id, c.id); } } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out))); solution(reader, writer); writer.close(); } protected static class In { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public In(BufferedReader reader) { this.reader = reader; } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } protected static class Out { private PrintWriter writer; public Out(PrintWriter writer) { this.writer = writer; } public void println(Object[] objects) { for (int i = 0; i < objects.length; i++) { writer.print(objects[i]); writer.print(' '); } writer.println(); } public void println(int[] array) { for (int i = 0; i < array.length; i++) { writer.print(array[i]); writer.print(' '); } writer.println(); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
07e4fcd193c553854bc190c3f85ab1ea
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.*; import java.util.*; public class E { public static void solution(BufferedReader reader, PrintWriter out) throws IOException { In in = new In(reader); int n = in.nextInt(), m = in.nextInt(); HashMap<Integer, LinkedList<Integer>> comp = new HashMap<Integer, LinkedList<Integer>>(); for (int i = 1; i <= n; i++) { int p = in.nextInt(); if (!comp.containsKey(p)) comp.put(p, new LinkedList<Integer>()); comp.get(p).add(i); } int[][] soc = new int[m][2]; for (int i = 0; i < m; i++) soc[i] = new int[] { in.nextInt(), i + 1 }; Arrays.sort(soc, new Comparator<int[]>() { @Override public int compare(int[] s1, int[] s2) { return Integer.compare(s1[0], s2[0]); } }); int c = 0, u = 0; int[] a = new int[m + 1]; int[] b = new int[n + 1]; next: for (int[] so : soc) { int cnt = 0; while (true) { if (comp.containsKey(so[0]) && !comp.get(so[0]).isEmpty()) { c++; u += cnt; a[so[1]] = cnt; b[comp.get(so[0]).removeFirst()] = so[1]; continue next; } if (so[0] == 1) break; so[0] = so[0] - so[0] / 2; cnt++; } } out.printf("%d %d\n", c, u); StringBuffer sb = new StringBuffer(); for (int i = 1; i <= m; i++) { sb.append(a[i]); sb.append(' '); } out.println(sb.toString()); sb = new StringBuffer(); for (int i = 1; i <= n; i++) { sb.append(b[i]); sb.append(' '); } out.println(sb.toString()); } protected static class Computer implements Comparable<Computer> { protected int id, p; public Computer(int id, int p) { super(); this.id = id; this.p = p; } @Override public int compareTo(Computer c) { if (p != c.p) return Integer.compare(p, c.p); return Integer.compare(id, c.id); } } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out))); solution(reader, out); out.close(); } protected static class In { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public In(BufferedReader reader) { this.reader = reader; } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
b3b8663f71491e0996bfad64923597eb
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.*; import java.util.*; public class E { public static void solution(BufferedReader reader, PrintWriter writer) throws IOException { In in = new In(reader); Out out = new Out(writer); int n = in.nextInt(), m = in.nextInt(); HashMap<Integer, LinkedList<Integer>> comp = new HashMap<Integer, LinkedList<Integer>>(); for (int i = 1; i <= n; i++) { int p = in.nextInt(); if (!comp.containsKey(p)) comp.put(p, new LinkedList<Integer>()); comp.get(p).add(i); } int[][] soc = new int[m][2]; for (int i = 0; i < m; i++) soc[i] = new int[] { in.nextInt(), i + 1 }; Arrays.sort(soc, new Comparator<int[]>() { @Override public int compare(int[] s1, int[] s2) { return Integer.compare(s1[0], s2[0]); } }); int c = 0, u = 0; int[] a = new int[m]; int[] b = new int[n]; next: for (int[] so : soc) { int cnt = 0; while (true) { if (comp.containsKey(so[0]) && !comp.get(so[0]).isEmpty()) { c++; u += cnt; a[so[1] - 1] = cnt; b[comp.get(so[0]).removeFirst() - 1] = so[1]; continue next; } if (so[0] == 1) break; so[0] = so[0] - so[0] / 2; cnt++; } } out.println(new int[] { c, u }); out.println(a); out.println(b); } protected static class Computer implements Comparable<Computer> { protected int id, p; public Computer(int id, int p) { super(); this.id = id; this.p = p; } @Override public int compareTo(Computer c) { if (p != c.p) return Integer.compare(p, c.p); return Integer.compare(id, c.id); } } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out))); solution(reader, writer); writer.close(); } protected static class In { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public In(BufferedReader reader) { this.reader = reader; } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } protected static class Out { private PrintWriter writer; public Out(PrintWriter writer) { this.writer = writer; } public void println(Object[] objects) { for (int i = 0; i < objects.length; i++) { writer.print(objects[i]); writer.print(' '); } writer.println(); } public void println(int[] array) { for (int i = 0; i < array.length; i++) { writer.print(array[i]); writer.print(' '); } writer.println(); } public void println(long[] array) { for (int i = 0; i < array.length; i++) { writer.print(array[i]); writer.print(' '); } writer.println(); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
4aa2754dd29e200219e615323d3c44c1
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.*; import java.util.*; public class E { public static void solution(BufferedReader reader, PrintWriter out) throws IOException { In in = new In(reader); int n = in.nextInt(), m = in.nextInt(); HashMap<Integer, LinkedList<Integer>> comp = new HashMap<Integer, LinkedList<Integer>>(); for (int i = 1; i <= n; i++) { int p = in.nextInt(); if (!comp.containsKey(p)) comp.put(p, new LinkedList<Integer>()); comp.get(p).add(i); } int[][] soc = new int[m][2]; for (int i = 0; i < m; i++) soc[i] = new int[] { in.nextInt(), i + 1 }; Arrays.sort(soc, new Comparator<int[]>() { @Override public int compare(int[] s1, int[] s2) { return Integer.compare(s1[0], s2[0]); } }); int c = 0, u = 0; int[] a = new int[m + 1]; int[] b = new int[n + 1]; next: for (int[] so : soc) { int cnt = 0; while (true) { if (comp.containsKey(so[0]) && !comp.get(so[0]).isEmpty()) { c++; u += cnt; a[so[1]] = cnt; b[comp.get(so[0]).removeFirst()] = so[1]; continue next; } if (so[0] == 1) break; so[0] = so[0] - so[0] / 2; cnt++; } } out.printf("%d %d\n", c, u); for (int i = 1; i <= m; i++) out.printf("%d ", a[i]); out.println(); for (int i = 1; i <= n; i++) out.printf("%d ", b[i]); out.println(); } protected static class Computer implements Comparable<Computer> { protected int id, p; public Computer(int id, int p) { super(); this.id = id; this.p = p; } @Override public int compareTo(Computer c) { if (p != c.p) return Integer.compare(p, c.p); return Integer.compare(id, c.id); } } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out))); solution(reader, out); out.close(); } protected static class In { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public In(BufferedReader reader) { this.reader = reader; } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
25dbb683039816d543266484e42da123
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.*; import java.util.*; public class E { public static void solution(BufferedReader reader, PrintWriter out) throws IOException { In in = new In(reader); int n = in.nextInt(), m = in.nextInt(); HashMap<Integer, LinkedList<Integer>> comp = new HashMap<Integer, LinkedList<Integer>>(); for (int i = 1; i <= n; i++) { int p = in.nextInt(); if (!comp.containsKey(p)) comp.put(p, new LinkedList<Integer>()); comp.get(p).add(i); } int[][] soc = new int[m][2]; for (int i = 0; i < m; i++) soc[i] = new int[] { in.nextInt(), i + 1 }; Arrays.sort(soc, new Comparator<int[]>() { @Override public int compare(int[] s1, int[] s2) { return Integer.compare(s1[0], s2[0]); } }); int c = 0, u = 0; int[] a = new int[m + 1]; int[] b = new int[n + 1]; next: for (int[] so : soc) { int cnt = 0; while (true) { if (comp.containsKey(so[0]) && !comp.get(so[0]).isEmpty()) { c++; u += cnt; a[so[1]] = cnt; b[comp.get(so[0]).removeFirst()] = so[1]; continue next; } if (so[0] == 1) break; so[0] = so[0] - so[0] / 2; cnt++; } } out.printf("%d %d\n", c, u); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= m; i++) { sb.append(a[i]); sb.append(' '); } out.println(sb.toString()); sb = new StringBuilder(); for (int i = 1; i <= n; i++) { sb.append(b[i]); sb.append(' '); } out.println(sb.toString()); } protected static class Computer implements Comparable<Computer> { protected int id, p; public Computer(int id, int p) { super(); this.id = id; this.p = p; } @Override public int compareTo(Computer c) { if (p != c.p) return Integer.compare(p, c.p); return Integer.compare(id, c.id); } } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out))); solution(reader, out); out.close(); } protected static class In { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public In(BufferedReader reader) { this.reader = reader; } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
7d8af37f9641afc5aaab1369f16620a0
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.*; import java.util.*; public class E { public static void solution(BufferedReader reader, PrintWriter out) throws IOException { In in = new In(reader); int n = in.nextInt(), m = in.nextInt(); HashMap<Integer, LinkedList<Integer>> comp = new HashMap<Integer, LinkedList<Integer>>(); for (int i = 1; i <= n; i++) { int p = in.nextInt(); if (!comp.containsKey(p)) comp.put(p, new LinkedList<Integer>()); comp.get(p).add(i); } int[][] soc = new int[m][2]; for (int i = 0; i < m; i++) soc[i] = new int[] { in.nextInt(), i + 1 }; Arrays.sort(soc, new Comparator<int[]>() { @Override public int compare(int[] s1, int[] s2) { return Integer.compare(s1[0], s2[0]); } }); int c = 0, u = 0; int[] a = new int[m + 1]; int[] b = new int[n + 1]; next: for (int[] so : soc) { int cnt = 0; while (true) { if (comp.containsKey(so[0]) && !comp.get(so[0]).isEmpty()) { c++; u += cnt; a[so[1]] = cnt; b[comp.get(so[0]).removeFirst()] = so[1]; continue next; } if (so[0] == 1) break; so[0] = so[0] - so[0] / 2; cnt++; } } out.printf("%d %d\n", c, u); for (int i = 1; i <= m; i++) { out.print(a[i]); out.print(' '); } out.println(); for (int i = 1; i <= n; i++) { out.print(b[i]); out.print(' '); } out.println(); } protected static class Computer implements Comparable<Computer> { protected int id, p; public Computer(int id, int p) { super(); this.id = id; this.p = p; } @Override public int compareTo(Computer c) { if (p != c.p) return Integer.compare(p, c.p); return Integer.compare(id, c.id); } } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out))); solution(reader, out); out.close(); } protected static class In { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public In(BufferedReader reader) { this.reader = reader; } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
59c516c688652310fd520d5e79668c4d
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.*; import java.util.*; /** * * @author Sourav Kumar Paul (spaul100) * NIT Silchar */ public class SolveE { public static Reader in; public static PrintWriter out; public static long mod = 1000000007; public static long inf = 100000000000000000l; public static long fac[],inv[]; public static int union[]; public static void solve(){ int n = in.nextInt(); int m = in.nextInt(); HashMap<Integer,Integer> cntPc = new HashMap<>(); int pc[] = new int[n]; int so[] = new int[m]; HashMap<Integer,Integer> uni = new HashMap<>(); ArrayList<Integer> list[] = new ArrayList[1000005]; for(int i=0; i<=1000000; i++) list[i] = new ArrayList<>(); int count =0; for(int i=0; i<n; i++) { pc[i] = in.nextInt(); int xx = (cntPc.containsKey(pc[i]))? cntPc.get(pc[i]) + 1 : 1; cntPc.put(pc[i], xx); if(cntPc.get(pc[i])==1) { count++; uni.put(pc[i],count); list[count].add(i); } else list[uni.get(pc[i])].add(i); } boolean used[] = new boolean[m]; int units[] = new int[m]; for(int i=0; i<m; i++) { so[i] = in.nextInt(); } int b[] = new int[n]; int ad =0; for(int i=0; i<33; i++) { for(int j=0; j<m; j++) { if(used[j]) continue; if(cntPc.containsKey(so[j]) && cntPc.get(so[j]) >0) { int cc = cntPc.get(so[j])-1; cntPc.put(so[j], cc); units[j] = i; used[j] = true; b[list[uni.get(so[j])].get(cc)] = j+1; ad +=i; } so[j] = (int)Math.ceil(so[j]/2.0); } } count = 0; for(int i=0; i<n; i++) if(b[i]>0) count++; out.println(count +" "+ad); for(int i=0; i<m; i++) out.print(units[i]+" "); out.println(); for(int i=0; i<n; i++) out.print(b[i]+" "); } /** * ############################### Template ################################ */ public static class Pair implements Comparable{ int y; long x; Pair(long x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Object o) { Pair pp = (Pair)o; if(pp.x == x) return 0; else if (x>pp.x) return 1; else return -1; } } public static void init() { for(int i=0; i<union.length; i++) union[i] = i; } public static int find(int n) { return (union[n]==n)?n:(union[n]=find(union[n])); } public static void unionSet(int i ,int j) { union[find(i)]=find(j); } public static boolean connected(int i,int j) { return union[i]==union[j]; } public static long gcd(long a, long b) { long x = Math.min(a,b); long y = Math.max(a,b); while(x!=0) { long temp = x; x = y%x; y = temp; } return y; } public static long modPow(long base, long exp, long mod) { base = base % mod; long result =1; while(exp > 0) { if(exp % 2== 1) { result = (result * base) % mod; exp --; } else { base = (base * base) % mod; exp = exp >> 1; } } return result; } public static void cal() { fac = new long[1000005]; inv = new long[1000005]; fac[0]=1; inv[0]=1; for(int i=1; i<=1000000; i++) { fac[i]=(fac[i-1]*i)%mod; inv[i]=(inv[i-1]*modPow(i,mod-2,mod))%mod; } } public static long ncr(int n, int r) { return (((fac[n]*inv[r])%mod)*inv[n-r])%mod; } SolveE() throws IOException { in = new Reader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); out.close(); } public static void main(String args[]) { new Thread(null, new Runnable() { public void run() { try { new SolveE(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); } public static class Reader { public BufferedReader reader; public StringTokenizer st; public Reader(InputStreamReader stream) { reader = new BufferedReader(stream); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() throws IOException{ return reader.readLine(); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
cdfe1239857edb26ac78982efd5dd54e
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
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.Arrays; import java.util.HashMap; import java.util.PriorityQueue; import java.util.StringTokenizer; public class E { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(), m = sc.nextInt(); PC[] pcs = new PC[n]; for(int i = 0; i < n; ++i) pcs[i] = new PC(sc.nextInt(), i); Arrays.sort(pcs); HashMap<Integer, PriorityQueue<Socket>> map = new HashMap<>(); for(int i = 0; i < n; ++i) map.put(pcs[i].power, new PriorityQueue<Socket>()); PriorityQueue<Socket> x; for(int i = 0; i < m; ++i) { int s = sc.nextInt(), cost = 0; while(true) { x = map.get(s); if(x != null) x.add(new Socket(i, cost)); ++cost; if(s <= 1) break; s = s + 1 >> 1; } } int[] a = new int[m], b = new int[n]; boolean[] used = new boolean[m]; PriorityQueue<Socket> cands; Socket soc; int c = 0, u = 0; for(int i = n - 1; i >= 0; --i) { PC pc = pcs[i]; cands = map.get(pc.power); soc = null; while(!cands.isEmpty()) { soc = cands.remove(); if(!used[soc.idx]) break; soc = null; } if(soc == null) continue; ++c; u += soc.cost; used[soc.idx] = true; a[soc.idx] = soc.cost; b[pc.idx] = soc.idx + 1; } out.println(c + " " + u); StringBuilder sb = new StringBuilder(); for(int i = 0; i < m; ++i) sb.append(a[i]).append(i == m - 1 ? "\n" : " "); for(int i = 0; i < n; ++i) sb.append(b[i]).append(i == n - 1 ? "\n" : " "); out.print(sb); out.flush(); out.close(); } static class PC implements Comparable<PC> { int idx, power; PC(int a, int c) { power = a; idx = c; } public int compareTo(PC p) { return power - p.power; } } static class Socket implements Comparable<Socket> { int idx, cost; Socket(int a, int c) { idx = a; cost = c; } public int compareTo(Socket s) { return cost - s.cost; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
f85f2b6b8a2faaec5254751f71faa5ea
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; @SuppressWarnings("unchecked") public class P732E { public void run() throws Exception { int n = nextInt(), m = nextInt(); Map<Integer, Deque<Integer>> comp = new HashMap(n); for (int i = 0; i < n; i++) { int p = nextInt(); Deque<Integer> cl = comp.get(p); if (cl == null) { cl = new ArrayDeque(); comp.put(p, cl); } cl.add(i); } Deque<int []> sock = new ArrayDeque(m << 1); for (int i = 0; i < m; i++) { sock.addLast(new int [] { nextInt(), i }); } int tc = 0, ta = 0, ca [] = new int [n], sa [] = new int [m]; for (int a = 0; (sock.size() > 0) && (comp.size() > 0); a++) { for (int i = sock.size(); i > 0; i--) { int [] s = sock.pollFirst(); if (sa[s[1]] == 0) { Deque<Integer> cl = comp.get(s[0]); if (cl != null) { sa[s[1]] = a + 1; ca[cl.pollFirst()] = s[1] + 1; tc++; ta += a; if (cl.size() == 0) { comp.remove(s[0]); } } if (s[0] != 1) { s[0] = (s[0] + 1) >> 1; sock.addLast(s); } } } } println(tc + " " + ta); for (int a : sa) { print(((a != 0) ? (a - 1) : 0) + " "); } println(); for (int a : ca) { print(a + " "); } } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P732E().run(); br.close(); pw.close(); System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]"); } static long startTime = System.currentTimeMillis(); static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { print("" + o); } } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(Object o) { print(o); println(); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } int gcd(int a, int b) { return ((b > 0) ? gcd(b, a % b) : a); } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
a47c73491b8936f842516ad4306b867a
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.*; import java.util.*; public class TaskE { static InputReader in; static PrintWriter out; public static void main(String[] args) throws FileNotFoundException { InputStream inputStream = System.in; //FileInputStream inputStream = new FileInputStream("input.txt"); OutputStream outputStream = System.out; in = new InputReader(inputStream); out = new PrintWriter(outputStream); new Task().run(); out.close(); } static class Task { void run() { final int oo = (int) 1e9; TreeSet <Vertex> tr = new TreeSet<Vertex>(new CompVertex()); int i, n, m; n = in.nextInt(); m = in.nextInt(); Vertex p[] = new Vertex[n]; for (i = 0; i < n; ++i) p[i] = new Vertex(in.nextInt(), i); Vertex s[] = new Vertex[m]; for (i = 0; i < m; ++i) s[i] = new Vertex(in.nextInt(), i); Arrays.sort(p, new CompVertex()); Arrays.sort(s, new CompVertex()); int ansA[] = new int[m]; int ansB[] = new int[n]; int ansC = 0, ansU = 0; for (i = 0; i < n; ++i) ansB[i] = -1; for (i = 0; i < m; ++i) ansA[i] = -1; Vertex pt[] = new Vertex[n]; Vertex st[] = new Vertex[m]; int nn = n, mm = m; int nt, mt; int add; int j; for (add = 0; add < 32; ++add) { nt = 0; mt = 0; i = 0; j = 0; while (i < n || j < m) { if (j == m) pt[nt++] = p[i++]; else if (i == n) st[mt++] = s[j++]; else if (p[i].pw == s[j].pw) { ++ansC; ansU += add; ansA[s[j].nm] = add; ansB[p[i].nm] = s[j].nm; ++i; ++j; } else if (p[i].pw < s[j].pw) { pt[nt++] = p[i++]; } else { st[mt++] = s[j++]; } } n = nt; m = mt; for (i = 0; i < n; ++i) p[i] = pt[i]; for (i = 0; i < m; ++i) { s[i] = st[i]; s[i].pw = (s[i].pw + 1) >> 1; } } out.print(ansC); out.print(' '); out.println(ansU); for (i = 0; i < mm; ++i) { if (ansA[i] < 0) ansA[i] = 0; out.print(ansA[i]); out.print(' '); } out.println(); for (i = 0; i < nn; ++i) { out.print(ansB[i] + 1); out.print(' '); } out.println(); } class CompVertex implements Comparator<Vertex>{ public int compare(Vertex v1, Vertex v2) { int cmp = Integer.compare(v1.pw, v2.pw); if (cmp == 0) cmp = Integer.compare(v1.nm, v2.nm); return cmp; } } class Vertex{ int pw, nm; Vertex(int pw, int nm) { this.pw = pw; this.nm = nm; } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
c619c8d34c94a9960f09e80c73c2a271
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class TestClass { private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; public static class Queue{ private class node{ int val; node next; node(int a){ val = a; next = null; } } node head,tail; Queue(){ head = null; tail = null; } public void EnQueue(int a){ if(head==null){ node p = new node(a); head = p; tail = p; } else{ node p = new node(a); tail.next = p; tail = p; } } public int DeQueue(){ int a = head.val; head = head.next; return a; } public boolean isEmpty(){ return head==null; } } public static long pow(long x,long y,long m){ if(y==0) return 1; long k = pow(x,y/2,m); if(y%2==0) return (k*k)%m; else return (((k*k)%m)*x)%m; } static long Inversex = 0,Inversey = 0; public static void InverseModulo(long a,long m){ if(m==0){ Inversex = 1; Inversey = 0; } else{ InverseModulo(m,a%m); long temp = Inversex; Inversex = Inversey; Inversey = temp+ - (a/m)*Inversey; } } static long mod1 = 1000000007; static long mod2 = 1000000009; public static long gcd(long a,long b){ if(a%b==0) return b; return gcd(b,a%b); } public static boolean isPrime(long a){ if(a==1) return false; else if(a==2||a==3) return true; for(long i=2;i<=Math.sqrt(a);i++) if(a%i==0) return false; return true; } public static double distance(int a,int b,int x,int y){ return Math.sqrt(((long)(a-x)*(long)(a-x))+((long)(b-y)*(long)(b-y))); } public static class Pair implements Comparable<Pair> { long u; long v; BigInteger bi; public Pair(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } public static int seive(int a[],boolean b[],TreeSet<Integer> c){ int count = 0; for(int i=2;i<a.length;i++){ if(!b[i]){ for(int j=i*i;j<a.length&&j>0;j=j+i) b[j] = true; c.add(i); a[count++] = i; } } return count; } public static void MatrixMultiplication(int a[][],int b[][],int c[][]){ for(int i=0;i<a.length;i++){ for(int j=0;j<b[0].length;j++){ c[i][j] = 0; for(int k=0;k<b.length;k++) c[i][j]=(int)((c[i][j]+((a[i][k]*(long)b[k][j])%mod1))%mod1); } } } public static void Equal(int arr[][],int temp[][]){ for(int i=0;i<arr.length;i++){ for(int j=0;j<arr.length;j++) temp[i][j] = arr[i][j]; } } public static class Trie { Node head; private class Node{ Node a[] = new Node[2]; boolean val; Node(){ a[0] = null; a[1] = null; val = false; } } Trie(){ head = new Node(); } public void insert(Stack<Integer> s){ Node temp = head; while(!s.isEmpty()){ int q = s.pop(); if(temp.a[q]==null) temp.a[q] = new Node(); temp = temp.a[q]; } temp.val = true; } public Node delete(Stack<Integer> s,Node temp){ if(s.isEmpty()) return null; int q = s.pop(); temp.a[q] = delete(s,temp.a[q]); if(temp.a[q]==null&&temp.a[q^1]==null) return null; else return temp; } public void get(Stack<Integer> s,Stack<Integer> p){ Node temp = head; while(!p.isEmpty()){ int q = p.pop(); if(temp.a[q]!=null){ s.push(q); temp = temp.a[q]; } else{ s.push(q^1); temp = temp.a[q^1]; } } } } public static void Merge(long a[][],int p,int r){ if(p<r){ int q = (p+r)/2; Merge(a,p,q); Merge(a,q+1,r); Merge_Array(a,p,q,r); } } public static void get(long a[][],long b[][],int i,int j){ for(int k=0;k<a[i].length;k++) a[i][k] = b[j][k]; } public static void Merge_Array(long a[][],int p,int q,int r){ long b[][] = new long[q-p+1][a[0].length]; long c[][] = new long[r-q][a[0].length]; for(int i=0;i<b.length;i++){ get(b,a,i,p+i); } for(int i=0;i<c.length;i++){ get(c,a,i,q+i+1); } int i = 0,j = 0; for(int k=p;k<=r;k++){ if(i==b.length){ get(a,c,k,j); j++; } else if(j==c.length){ get(a,b,k,i); i++; } else if(b[i][0]<c[j][0]){ get(a,b,k,i); i++; } else{ get(a,c,k,j); j++; } } } private static void soln(){ int n = nI(); int m = nI(); TreeMap<Integer,TreeSet<Integer>> comp = new TreeMap<Integer,TreeSet<Integer>>(); Pair socket[] = new Pair[m]; int fina[] = new int[n]; int soc[] = new int[m]; long c=0,u=0; for(int i=0;i<n;i++){ int x = nI(); if(comp.containsKey(x)){ TreeSet<Integer> nm = comp.get(x); nm.add(i); comp.put(x, nm); } else{ TreeSet<Integer> nm = new TreeSet<Integer>(); nm.add(i); comp.put(x, nm); } } for(int i=0;i<m;i++) socket[i] = new Pair(nI(),i); Arrays.sort(socket); for(int i=0;i<m&&!comp.isEmpty();i++){ int temp = (int)socket[i].u; int temp1 = comp.firstKey(); int count = 0; while(temp>=temp1){ if(comp.containsKey(temp)){ soc[(int)socket[i].v] = count; u+=count; TreeSet<Integer> nm = comp.get(temp); int q = nm.pollFirst(); fina[q] = (int)socket[i].v+1; c++; if(nm.isEmpty()) comp.remove(temp); break; } temp = (int)Math.ceil(temp/2.0); count++; } } pw.println(c+" "+u); for(int i=0;i<m;i++) pw.print(soc[i]+" "); pw.println(); for(int i=0;i<n;i++) pw.print(fina[i]+" "); } public static void main(String[] args) { InputReader(System.in); pw = new PrintWriter(System.out); soln(); pw.close(); } // To Get Input // Some Buffer Methods public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static 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++]; } private static int nI() { 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; } private static long nL() { 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 static String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static String nLi() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } private static int[] nIA(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nI(); return arr; } private static long[] nLA(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nL(); return arr; } private static void pArray(int[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); return; } private static void pArray(long[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); return; } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
a09c09a45012cb3051745075f6365928
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 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.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jialin Ouyang (Jialin.Ouyang@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; QuickScanner in = new QuickScanner(inputStream); QuickWriter out = new QuickWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { static final int MAXNODE = 200000 * 20; int n; Computer[] computers; int m; int uniqueM; int[] s; int[] uniqueS; int[] idxInTrie; Trie trie; IntArrayList2D listS; int c; int u; int[] a; int[] b; public void solve(int testNumber, QuickScanner in, QuickWriter out) { n = in.nextInt(); m = in.nextInt(); computers = new Computer[n]; for (int i = 0; i < n; ++i) computers[i] = new Computer(in.nextInt(), i); Arrays.sort(computers); s = in.nextInt(m); uniqueS = Arrays.copyOf(s, m); Arrays.sort(uniqueS); uniqueM = IntArrayUtils.unique(uniqueS); idxInTrie = new int[m]; trie = new Trie(2, MAXNODE); //graph = new DirectedGraph(m, m); listS = new IntArrayList2D(uniqueM, m); for (int i = 0; i < m; ++i) { int disS = IntArrayUtils.lowerBound(uniqueS, 0, uniqueM, s[i]); idxInTrie[i] = trie.add(s[i], disS); listS.add(disS, i); } a = new int[m]; b = new int[n]; c = u = 0; for (int i = 0; i < n; ++i) { Computer computer = computers[i]; int trieIdx = trie.access(computer.power); if (trieIdx < 0 || trie.nearestIdx[trieIdx] < 0) continue; int disS = trie.nearestIdx[trieIdx]; int sIdx = listS.pollLast(disS); b[computer.idx] = sIdx + 1; ++c; a[sIdx] = trie.nearest[trieIdx]; u += a[sIdx]; trie.dec(idxInTrie[sIdx]); } out.println(c, u); out.println(a); out.println(b); } class Trie extends AbstractTrie { final int MAXN = 40; int[] cnt; int[] nearest; int[] nearestIdx; int[] tmp = new int[MAXN]; public Trie(int letterCapacity, int nodeCapacity) { super(letterCapacity, nodeCapacity); } public void create(int letterCapacity, int nodeCapacity) { cnt = new int[nodeCapacity]; nearest = new int[nodeCapacity]; nearestIdx = new int[nodeCapacity]; } public void initNode(int idx, int parent, int parentLetter) { cnt[idx] = 0; nearest[idx] = MAXN; nearestIdx[idx] = -1; } public int add(int s, int uniqueS) { int len = parse(s); int res = add(tmp, 0, len); ++cnt[res]; for (int i = res, j = 0; i >= 0; i = parent[i], ++j) if (nearest[i] > j) { nearest[i] = j; nearestIdx[i] = uniqueS; } return res; } public int access(int s) { int len = parse(s); return access(tmp, 0, len); } public void dec(int idx) { if (cnt[idx] <= 0) throw new IllegalArgumentException(); --cnt[idx]; for (; idx >= 0 && cnt[idx] == 0; idx = parent[idx]) { merge(idx); } } private int parse(int s) { int res = 0; for (; s > 1; s = (s + 1) >> 1) { tmp[res++] = 1 - (s & 1); } IntArrayUtils.reverse(tmp, 0, res); return res; } private void merge(int idx) { int left = child[0][idx], right = child[1][idx]; if (left < 0 && right < 0) { nearest[idx] = MAXN; nearestIdx[idx] = -1; } else if (left < 0) { update(idx, right); } else if (right < 0) { update(idx, left); } else { update(idx, nearest[left] < nearest[right] ? left : right); } } private void update(int idx, int fromIdx) { nearest[idx] = Math.min(nearest[fromIdx] + 1, MAXN); nearestIdx[idx] = nearestIdx[fromIdx]; } } class Computer implements Comparable<Computer> { int power; int idx; public Computer(int power, int idx) { this.power = power; this.idx = idx; } public int compareTo(Computer o) { return o.power - power; } } } static abstract class AbstractTrie { public int[] parent; public int[] parentLetter; public int[][] child; public int root; public int letterCnt; public int nodePnt; public abstract void create(int letterCapacity, int nodeCapacity); public abstract void initNode(int idx, int parent, int parentLetter); public AbstractTrie(int letterCapacity, int nodeCapacity) { parent = new int[nodeCapacity]; parentLetter = new int[nodeCapacity]; child = new int[letterCapacity][nodeCapacity]; create(letterCapacity, nodeCapacity); init(letterCapacity); } public void init(int letterCnt) { this.root = 0; this.letterCnt = letterCnt; this.nodePnt = 1; initNodeInternal(0, -1, -1); } public int add(int[] letters, int fromIdx, int toIdx) { int resIdx = root; for (int i = fromIdx; i < toIdx; ++i) { int letter = letters[i]; if (child[letter][resIdx] < 0) { child[letter][resIdx] = nodePnt; initNodeInternal(nodePnt++, resIdx, letter); } resIdx = child[letter][resIdx]; } return resIdx; } public int access(int[] letters, int fromIdx, int toIdx) { int resIdx = root; for (int i = fromIdx; i < toIdx; ++i) { resIdx = child[letters[i]][resIdx]; if (resIdx < 0) return resIdx; } return resIdx; } private void initNodeInternal(int idx, int parent, int letter) { this.parent[idx] = parent; this.parentLetter[idx] = letter; for (int i = 0; i < letterCnt; ++i) { child[i][idx] = -1; } initNode(idx, parent, letter); } } static class IntArrayUtils { public static void reverse(int[] values, int fromIdx, int toIdx) { for (int i = fromIdx, j = toIdx - 1; i < j; ++i, --j) { values[i] ^= values[j]; values[j] ^= values[i]; values[i] ^= values[j]; } } public static int unique(int[] values) { return unique(values, 0, values.length); } public static int unique(int[] values, int fromIdx, int toIdx) { if (fromIdx == toIdx) return 0; int res = 1; for (int i = fromIdx + 1; i < toIdx; ++i) { if (values[i - 1] != values[i]) { values[fromIdx + res++] = values[i]; } } return res; } public static int lowerBound(int[] values, int fromIdx, int toIdx, int value) { int res = toIdx; for (int lower = fromIdx, upper = toIdx - 1; lower <= upper; ) { int medium = (lower + upper) >> 1; if (value <= values[medium]) { res = medium; upper = medium - 1; } else { lower = medium + 1; } } return res; } } static class QuickScanner { private static final int BUFFER_SIZE = 1024; private InputStream stream; private byte[] buffer; private int currentPosition; private int numberOfChars; public QuickScanner(InputStream stream) { this.stream = stream; this.buffer = new byte[BUFFER_SIZE]; this.currentPosition = 0; this.numberOfChars = 0; } public int nextInt() { int c = nextNonSpaceChar(); boolean positive = true; if (c == '-') { positive = false; c = nextChar(); } int res = 0; do { if (c < '0' || '9' < c) throw new RuntimeException(); res = res * 10 + c - '0'; c = nextChar(); } while (!isSpaceChar(c)); return positive ? res : -res; } public int[] nextInt(int n) { int[] res = new int[n]; nextInt(n, res); return res; } public void nextInt(int n, int[] res) { for (int i = 0; i < n; ++i) { res[i] = nextInt(); } } public int nextNonSpaceChar() { int res = nextChar(); for (; isSpaceChar(res) || res < 0; res = nextChar()) ; return res; } public int nextChar() { if (numberOfChars == -1) { throw new RuntimeException(); } if (currentPosition >= numberOfChars) { currentPosition = 0; try { numberOfChars = stream.read(buffer); } catch (Exception e) { throw new RuntimeException(e); } if (numberOfChars <= 0) { return -1; } } return buffer[currentPosition++]; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c < 0; } } static class QuickWriter { private final PrintWriter writer; public QuickWriter(OutputStream outputStream) { this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public QuickWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; ++i) { if (i > 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.print('\n'); } public void print(int[] objects) { print(objects, ' '); } public void print(int[] objects, char delimiter) { for (int i = 0; i < objects.length; ++i) { if (i > 0) { writer.print(delimiter); } writer.print(objects[i]); } } public void println(int[] objects) { print(objects); writer.print('\n'); } public void close() { writer.close(); } } static class IntArrayList2D { public int listCnt; public int close; public int[] size; public int[] first; public int[] last; public int[] prev; public int[] next; public int[] values; public IntArrayList2D(int listCapacity, int elementCapacity) { size = new int[listCapacity]; first = new int[listCapacity]; last = new int[listCapacity]; prev = new int[elementCapacity]; next = new int[elementCapacity]; values = new int[elementCapacity]; init(listCapacity); } public void init(int listCnt) { this.listCnt = listCnt; close = 0; Arrays.fill(size, 0, listCnt, 0); Arrays.fill(first, 0, listCnt, -1); Arrays.fill(last, 0, listCnt, -1); } public void add(int listIdx, int value) { ++size[listIdx]; prev[close] = last[listIdx]; next[close] = -1; values[close] = value; if (first[listIdx] < 0) first[listIdx] = close; last[listIdx] = close; ++close; } public int pollLast(int listIdx) { if (size[listIdx] == 0) throw new IllegalArgumentException(); --size[listIdx]; int idx = last[listIdx]; last[listIdx] = prev[idx]; int newIdx = last[listIdx]; if (newIdx >= 0) { next[newIdx] = -1; } else { first[listIdx] = -1; } return values[idx]; } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
85bb1965ffda4b779ba89fed951a9f00
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 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.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jialin Ouyang (Jialin.Ouyang@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; QuickScanner in = new QuickScanner(inputStream); QuickWriter out = new QuickWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { static final int MAXNODE = 200000 * 20; int n; Computer[] computers; int m; int uniqueM; int[] s; int[] uniqueS; int[] disS; int[] idxInTrie; Trie trie; DirectedGraph graph; int c; int u; int[] a; int[] b; public void solve(int testNumber, QuickScanner in, QuickWriter out) { n = in.nextInt(); m = in.nextInt(); computers = new Computer[n]; for (int i = 0; i < n; ++i) computers[i] = new Computer(in.nextInt(), i); Arrays.sort(computers); s = in.nextInt(m); uniqueS = Arrays.copyOf(s, m); Arrays.sort(uniqueS); uniqueM = IntArrayUtils.unique(uniqueS); disS = new int[m]; idxInTrie = new int[m]; trie = new Trie(2, MAXNODE); graph = new DirectedGraph(m, m); for (int i = 0; i < m; ++i) { disS[i] = IntArrayUtils.lowerBound(uniqueS, 0, uniqueM, s[i]); idxInTrie[i] = trie.add(s[i], disS[i]); graph.add(disS[i], i); } a = new int[m]; b = new int[n]; c = u = 0; for (int i = 0; i < n; ++i) { Computer computer = computers[i]; int trieIdx = trie.access(computer.power); if (trieIdx < 0 || trie.nearestIdx[trieIdx] < 0) continue; int uniqueS = trie.nearestIdx[trieIdx]; int edgeIdx = graph.lastOut[uniqueS]; graph.lastOut[uniqueS] = graph.nextOut[edgeIdx]; int sIdx = graph.toIdx[edgeIdx]; b[computer.idx] = sIdx + 1; ++c; a[sIdx] = trie.nearest[trieIdx]; u += a[sIdx]; trie.dec(idxInTrie[sIdx]); } out.println(c, u); out.println(a); out.println(b); } class Trie extends AbstractTrie { final int MAXN = 40; int[] cnt; int[] nearest; int[] nearestIdx; int[] tmp = new int[MAXN]; public Trie(int letterCapacity, int nodeCapacity) { super(letterCapacity, nodeCapacity); } public void create(int letterCapacity, int nodeCapacity) { cnt = new int[nodeCapacity]; nearest = new int[nodeCapacity]; nearestIdx = new int[nodeCapacity]; } public void initNode(int idx, int parent, int parentLetter) { cnt[idx] = 0; nearest[idx] = MAXN; nearestIdx[idx] = -1; } public int add(int s, int uniqueS) { int len = parse(s); int res = add(tmp, 0, len); ++cnt[res]; for (int i = res, j = 0; i >= 0; i = parent[i], ++j) if (nearest[i] > j) { nearest[i] = j; nearestIdx[i] = uniqueS; } return res; } public int access(int s) { int len = parse(s); return access(tmp, 0, len); } public void dec(int idx) { if (cnt[idx] <= 0) throw new IllegalArgumentException(); --cnt[idx]; for (; idx >= 0 && cnt[idx] == 0; idx = parent[idx]) { merge(idx); } } private int parse(int s) { int res = 0; for (; s > 1; s = (s + 1) >> 1) { tmp[res++] = 1 - (s & 1); } IntArrayUtils.reverse(tmp, 0, res); return res; } private void merge(int idx) { int left = child[0][idx], right = child[1][idx]; if (left < 0 && right < 0) { nearest[idx] = MAXN; nearestIdx[idx] = -1; } else if (left < 0) { update(idx, right); } else if (right < 0) { update(idx, left); } else { update(idx, nearest[left] < nearest[right] ? left : right); } } private void update(int idx, int fromIdx) { nearest[idx] = Math.min(nearest[fromIdx] + 1, MAXN); nearestIdx[idx] = nearestIdx[fromIdx]; } } class Computer implements Comparable<Computer> { int power; int idx; public Computer(int power, int idx) { this.power = power; this.idx = idx; } public int compareTo(Computer o) { return o.power - power; } } } static abstract class AbstractTrie { public int[] parent; public int[] parentLetter; public int[][] child; public int root; public int letterCnt; public int nodePnt; public abstract void create(int letterCapacity, int nodeCapacity); public abstract void initNode(int idx, int parent, int parentLetter); public AbstractTrie(int letterCapacity, int nodeCapacity) { parent = new int[nodeCapacity]; parentLetter = new int[nodeCapacity]; child = new int[letterCapacity][nodeCapacity]; create(letterCapacity, nodeCapacity); init(letterCapacity); } public void init(int letterCnt) { this.root = 0; this.letterCnt = letterCnt; this.nodePnt = 1; initNodeInternal(0, -1, -1); } public int add(int[] letters, int fromIdx, int toIdx) { int resIdx = root; for (int i = fromIdx; i < toIdx; ++i) { int letter = letters[i]; if (child[letter][resIdx] < 0) { child[letter][resIdx] = nodePnt; initNodeInternal(nodePnt++, resIdx, letter); } resIdx = child[letter][resIdx]; } return resIdx; } public int access(int[] letters, int fromIdx, int toIdx) { int resIdx = root; for (int i = fromIdx; i < toIdx; ++i) { resIdx = child[letters[i]][resIdx]; if (resIdx < 0) return resIdx; } return resIdx; } private void initNodeInternal(int idx, int parent, int letter) { this.parent[idx] = parent; this.parentLetter[idx] = letter; for (int i = 0; i < letterCnt; ++i) { child[i][idx] = -1; } initNode(idx, parent, letter); } } static class QuickWriter { private final PrintWriter writer; public QuickWriter(OutputStream outputStream) { this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public QuickWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; ++i) { if (i > 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.print('\n'); } public void print(int[] objects) { print(objects, ' '); } public void print(int[] objects, char delimiter) { for (int i = 0; i < objects.length; ++i) { if (i > 0) { writer.print(delimiter); } writer.print(objects[i]); } } public void println(int[] objects) { print(objects); writer.print('\n'); } public void close() { writer.close(); } } static class IntArrayUtils { public static void reverse(int[] values, int fromIdx, int toIdx) { for (int i = fromIdx, j = toIdx - 1; i < j; ++i, --j) { values[i] ^= values[j]; values[j] ^= values[i]; values[i] ^= values[j]; } } public static int unique(int[] values) { return unique(values, 0, values.length); } public static int unique(int[] values, int fromIdx, int toIdx) { if (fromIdx == toIdx) return 0; int res = 1; for (int i = fromIdx + 1; i < toIdx; ++i) { if (values[i - 1] != values[i]) { values[fromIdx + res++] = values[i]; } } return res; } public static int lowerBound(int[] values, int fromIdx, int toIdx, int value) { int res = toIdx; for (int lower = fromIdx, upper = toIdx - 1; lower <= upper; ) { int medium = (lower + upper) >> 1; if (value <= values[medium]) { res = medium; upper = medium - 1; } else { lower = medium + 1; } } return res; } } static class QuickScanner { private static final int BUFFER_SIZE = 1024; private InputStream stream; private byte[] buffer; private int currentPosition; private int numberOfChars; public QuickScanner(InputStream stream) { this.stream = stream; this.buffer = new byte[BUFFER_SIZE]; this.currentPosition = 0; this.numberOfChars = 0; } public int nextInt() { int c = nextNonSpaceChar(); boolean positive = true; if (c == '-') { positive = false; c = nextChar(); } int res = 0; do { if (c < '0' || '9' < c) throw new RuntimeException(); res = res * 10 + c - '0'; c = nextChar(); } while (!isSpaceChar(c)); return positive ? res : -res; } public int[] nextInt(int n) { int[] res = new int[n]; nextInt(n, res); return res; } public void nextInt(int n, int[] res) { for (int i = 0; i < n; ++i) { res[i] = nextInt(); } } public int nextNonSpaceChar() { int res = nextChar(); for (; isSpaceChar(res) || res < 0; res = nextChar()) ; return res; } public int nextChar() { if (numberOfChars == -1) { throw new RuntimeException(); } if (currentPosition >= numberOfChars) { currentPosition = 0; try { numberOfChars = stream.read(buffer); } catch (Exception e) { throw new RuntimeException(e); } if (numberOfChars <= 0) { return -1; } } return buffer[currentPosition++]; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c < 0; } } static class DirectedGraph { public int vertexCnt; public int edgeCnt; public int[] fromIdx; public int[] toIdx; public int[] nextIn; public int[] nextOut; public int[] lastIn; public int[] lastOut; public int[] inDegree; public int[] outDegree; public DirectedGraph(int vertexCapacity, int edgeCapacity) { create(vertexCapacity, edgeCapacity); init(vertexCapacity); } public void create(int vertexCapacity, int edgeCapacity) { fromIdx = new int[edgeCapacity]; toIdx = new int[edgeCapacity]; lastIn = new int[vertexCapacity]; lastOut = new int[vertexCapacity]; nextIn = new int[edgeCapacity]; nextOut = new int[edgeCapacity]; inDegree = new int[vertexCapacity]; outDegree = new int[vertexCapacity]; } public void init(int vertexCnt) { this.vertexCnt = vertexCnt; this.edgeCnt = 0; Arrays.fill(inDegree, 0, vertexCnt, 0); Arrays.fill(outDegree, 0, vertexCnt, 0); Arrays.fill(lastIn, 0, vertexCnt, -1); Arrays.fill(lastOut, 0, vertexCnt, -1); } public void add(int fromIdx, int toIdx) { this.fromIdx[edgeCnt] = fromIdx; this.toIdx[edgeCnt] = toIdx; ++outDegree[fromIdx]; ++inDegree[toIdx]; nextOut[edgeCnt] = lastOut[fromIdx]; lastOut[fromIdx] = edgeCnt; nextIn[edgeCnt] = lastIn[toIdx]; lastIn[toIdx] = edgeCnt; ++edgeCnt; } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
60acf64e620c8138d018161a704c4f6b
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 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.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jialin Ouyang (Jialin.Ouyang@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; QuickScanner in = new QuickScanner(inputStream); QuickWriter out = new QuickWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { int n; int m; Element[] computers; Element[] sockets; DancingLink cDL; DancingLink sDL; int c; int u; int[] a; int[] b; public void solve(int testNumber, QuickScanner in, QuickWriter out) { n = in.nextInt(); m = in.nextInt(); computers = new Element[n]; for (int i = 0; i < n; ++i) computers[i] = new Element(in.nextInt(), i); Arrays.sort(computers); sockets = new Element[m]; for (int i = 0; i < m; ++i) sockets[i] = new Element(in.nextInt(), i); Arrays.sort(sockets); a = new int[m]; b = new int[n]; c = u = 0; cDL = new DancingLink(n); sDL = new DancingLink(m); for (int adapter = 0; sDL.first >= 0; ++adapter) { for (int cIdx = cDL.first, sIdx = sDL.first; cIdx >= 0 && sIdx >= 0; ) { if (computers[cIdx].power < sockets[sIdx].power) { cIdx = cDL.next[cIdx]; } else if (computers[cIdx].power > sockets[sIdx].power) { sIdx = sDL.next[sIdx]; } else { a[sockets[sIdx].idx] = adapter; b[computers[cIdx].idx] = sockets[sIdx].idx + 1; ++c; u += adapter; cDL.cover(cIdx); sDL.cover(sIdx); cIdx = cDL.next[cIdx]; sIdx = sDL.next[sIdx]; } } for (int sIdx = sDL.first; sIdx >= 0; sIdx = sDL.next[sIdx]) { Element socket = sockets[sIdx]; if (socket.power == 1) { sDL.cover(sIdx); } else { socket.power = (socket.power + 1) >> 1; } } } out.println(c, u); out.println(a); out.println(b); } class Element implements Comparable<Element> { int power; int idx; public Element(int power, int idx) { this.power = power; this.idx = idx; } public int compareTo(Element o) { return power - o.power; } } } static class QuickScanner { private static final int BUFFER_SIZE = 1024; private InputStream stream; private byte[] buffer; private int currentPosition; private int numberOfChars; public QuickScanner(InputStream stream) { this.stream = stream; this.buffer = new byte[BUFFER_SIZE]; this.currentPosition = 0; this.numberOfChars = 0; } public int nextInt() { int c = nextNonSpaceChar(); boolean positive = true; if (c == '-') { positive = false; c = nextChar(); } int res = 0; do { if (c < '0' || '9' < c) throw new RuntimeException(); res = res * 10 + c - '0'; c = nextChar(); } while (!isSpaceChar(c)); return positive ? res : -res; } public int nextNonSpaceChar() { int res = nextChar(); for (; isSpaceChar(res) || res < 0; res = nextChar()) ; return res; } public int nextChar() { if (numberOfChars == -1) { throw new RuntimeException(); } if (currentPosition >= numberOfChars) { currentPosition = 0; try { numberOfChars = stream.read(buffer); } catch (Exception e) { throw new RuntimeException(e); } if (numberOfChars <= 0) { return -1; } } return buffer[currentPosition++]; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c < 0; } } static class DancingLink { public int first; public int[] prev; public int[] next; public DancingLink(int capacity) { prev = new int[capacity]; next = new int[capacity]; init(capacity); } public void init(int n) { for (int i = 0; i < n; ++i) { prev[i] = i - 1; next[i] = i + 1; } next[n - 1] = -1; first = 0; } public void cover(int idx) { int prevIdx = prev[idx], nextIdx = next[idx]; if (prevIdx >= 0) { next[prevIdx] = nextIdx; } else { first = nextIdx; } if (nextIdx >= 0) { prev[nextIdx] = prevIdx; } } } static class QuickWriter { private final PrintWriter writer; public QuickWriter(OutputStream outputStream) { this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public QuickWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; ++i) { if (i > 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.print('\n'); } public void print(int[] objects) { print(objects, ' '); } public void print(int[] objects, char delimiter) { for (int i = 0; i < objects.length; ++i) { if (i > 0) { writer.print(delimiter); } writer.print(objects[i]); } } public void println(int[] objects) { print(objects); writer.print('\n'); } public void close() { writer.close(); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
c97956a96ea339fb646b1d94047b525a
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 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.util.Random; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jialin Ouyang (Jialin.Ouyang@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; QuickScanner in = new QuickScanner(inputStream); QuickWriter out = new QuickWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { static final int MAXNODE = 200000 * 20; int n; int[] p; int[] pOrder; int m; int uniqueM; int[] s; int[] uniqueS; int[] disS; int[] idxInTrie; Trie trie; DirectedGraph graph; int c; int u; int[] a; int[] b; public void solve(int testNumber, QuickScanner in, QuickWriter out) { n = in.nextInt(); m = in.nextInt(); p = in.nextInt(n); pOrder = new int[n]; for (int i = 0; i < n; ++i) pOrder[i] = i; IntArrayUtils.sort(pOrder, (x, y) -> p[y] - p[x]); //System.out.printf("pOrder: %s\n", Arrays.toString(pOrder)); s = in.nextInt(m); uniqueS = Arrays.copyOf(s, m); Arrays.sort(uniqueS); uniqueM = IntArrayUtils.unique(uniqueS); disS = new int[m]; idxInTrie = new int[m]; trie = new Trie(2, MAXNODE); graph = new DirectedGraph(m, m); for (int i = 0; i < m; ++i) { disS[i] = IntArrayUtils.lowerBound(uniqueS, 0, uniqueM, s[i]); //System.out.printf("s:%d disS:%d\n", s[i], disS[i]); idxInTrie[i] = trie.add(s[i], disS[i]); graph.add(disS[i], i); } a = new int[m]; b = new int[n]; c = u = 0; for (int i = 0; i < n; ++i) { int pIdx = pOrder[i], pValue = p[pIdx]; //System.out.printf("pValue(%d): %d\n", pIdx, pValue); int trieIdx = trie.access(pValue); if (trieIdx < 0 || trie.nearestIdx[trieIdx] < 0) continue; int uniqueS = trie.nearestIdx[trieIdx]; int edgeIdx = graph.lastOut[uniqueS]; graph.lastOut[uniqueS] = graph.nextOut[edgeIdx]; int sIdx = graph.toIdx[edgeIdx]; b[pIdx] = sIdx + 1; ++c; a[sIdx] = trie.nearest[trieIdx]; u += a[sIdx]; trie.dec(idxInTrie[sIdx]); } out.println(c, u); out.println(a); out.println(b); } class Trie extends AbstractTrie { final int MAXN = 40; int[] cnt; int[] nearest; int[] nearestIdx; int[] tmp = new int[MAXN]; public Trie(int letterCapacity, int nodeCapacity) { super(letterCapacity, nodeCapacity); } public void create(int letterCapacity, int nodeCapacity) { super.create(letterCapacity, nodeCapacity); cnt = new int[nodeCapacity]; nearest = new int[nodeCapacity]; nearestIdx = new int[nodeCapacity]; } public void initNode(int idx, int parent, int parentLetter) { cnt[idx] = 0; nearest[idx] = MAXN; nearestIdx[idx] = -1; } public int add(int s, int uniqueS) { int len = parse(s); int res = add(tmp, 0, len); ++cnt[res]; for (int i = res, j = 0; i >= 0; i = parent[i], ++j) if (nearest[i] > j) { nearest[i] = j; nearestIdx[i] = uniqueS; } return res; } public int access(int s) { int len = parse(s); return access(tmp, 0, len); } public void dec(int idx) { if (cnt[idx] <= 0) throw new IllegalArgumentException(); --cnt[idx]; for (; idx >= 0 && cnt[idx] == 0; idx = parent[idx]) { merge(idx); } } private int parse(int s) { int res = 0; //System.out.printf("%d:", s); for (; s > 1; s = (s + 1) >> 1) { tmp[res++] = 1 - (s & 1); } IntArrayUtils.reverse(tmp, 0, res); //System.out.printf("(%d) %s\n", res, Arrays.toString(tmp)); return res; } private void merge(int idx) { int left = child[0][idx], right = child[1][idx]; if (left < 0 && right < 0) { nearest[idx] = MAXN; nearestIdx[idx] = -1; } else if (left < 0) { update(idx, right); } else if (right < 0) { update(idx, left); } else { update(idx, nearest[left] < nearest[right] ? left : right); } } private void update(int idx, int fromIdx) { nearest[idx] = Math.min(nearest[fromIdx] + 1, MAXN); nearestIdx[idx] = nearestIdx[fromIdx]; } } } static class DirectedGraph { public int vertexCnt; public int edgeCnt; public int[] fromIdx; public int[] toIdx; public int[] nextIn; public int[] nextOut; public int[] lastIn; public int[] lastOut; public int[] inDegree; public int[] outDegree; public DirectedGraph(int vertexCapacity, int edgeCapacity) { create(vertexCapacity, edgeCapacity); init(vertexCapacity); } public void create(int vertexCapacity, int edgeCapacity) { fromIdx = new int[edgeCapacity]; toIdx = new int[edgeCapacity]; lastIn = new int[vertexCapacity]; lastOut = new int[vertexCapacity]; nextIn = new int[edgeCapacity]; nextOut = new int[edgeCapacity]; inDegree = new int[vertexCapacity]; outDegree = new int[vertexCapacity]; } public void init(int vertexCnt) { this.vertexCnt = vertexCnt; this.edgeCnt = 0; Arrays.fill(inDegree, 0, vertexCnt, 0); Arrays.fill(outDegree, 0, vertexCnt, 0); Arrays.fill(lastIn, 0, vertexCnt, -1); Arrays.fill(lastOut, 0, vertexCnt, -1); } public void add(int fromIdx, int toIdx) { this.fromIdx[edgeCnt] = fromIdx; this.toIdx[edgeCnt] = toIdx; ++outDegree[fromIdx]; ++inDegree[toIdx]; nextOut[edgeCnt] = lastOut[fromIdx]; lastOut[fromIdx] = edgeCnt; nextIn[edgeCnt] = lastIn[toIdx]; lastIn[toIdx] = edgeCnt; ++edgeCnt; } } static class QuickScanner { private static final int BUFFER_SIZE = 1024; private InputStream stream; private byte[] buffer; private int currentPosition; private int numberOfChars; public QuickScanner(InputStream stream) { this.stream = stream; this.buffer = new byte[BUFFER_SIZE]; this.currentPosition = 0; this.numberOfChars = 0; } public int nextInt() { int c = nextNonSpaceChar(); boolean positive = true; if (c == '-') { positive = false; c = nextChar(); } int res = 0; do { if (c < '0' || '9' < c) throw new RuntimeException(); res = res * 10 + c - '0'; c = nextChar(); } while (!isSpaceChar(c)); return positive ? res : -res; } public int[] nextInt(int n) { int[] res = new int[n]; nextInt(n, res); return res; } public void nextInt(int n, int[] res) { for (int i = 0; i < n; ++i) { res[i] = nextInt(); } } public int nextNonSpaceChar() { int res = nextChar(); for (; isSpaceChar(res) || res < 0; res = nextChar()) ; return res; } public int nextChar() { if (numberOfChars == -1) { throw new RuntimeException(); } if (currentPosition >= numberOfChars) { currentPosition = 0; try { numberOfChars = stream.read(buffer); } catch (Exception e) { throw new RuntimeException(e); } if (numberOfChars <= 0) { return -1; } } return buffer[currentPosition++]; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c < 0; } } static class QuickWriter { private final PrintWriter writer; public QuickWriter(OutputStream outputStream) { this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public QuickWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; ++i) { if (i > 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.print('\n'); } public void print(int[] objects) { print(objects, ' '); } public void print(int[] objects, char delimiter) { for (int i = 0; i < objects.length; ++i) { if (i > 0) { writer.print(delimiter); } writer.print(objects[i]); } } public void println(int[] objects) { print(objects); writer.print('\n'); } public void close() { writer.close(); } } static abstract class AbstractTrie { public int[] parent; public int[] parentLetter; public int[][] child; public int root; public int letterCnt; public int nodePnt; public abstract void initNode(int idx, int parent, int parentLetter); public AbstractTrie(int letterCapacity, int nodeCapacity) { create(letterCapacity, nodeCapacity); init(letterCapacity); } public void create(int letterCapacity, int nodeCapacity) { parent = new int[nodeCapacity]; parentLetter = new int[nodeCapacity]; child = new int[letterCapacity][nodeCapacity]; } public void init(int letterCnt) { this.root = 0; this.letterCnt = letterCnt; this.nodePnt = 1; initNodeInternal(0, -1, -1); } public int add(int[] letters, int fromIdx, int toIdx) { int resIdx = root; for (int i = fromIdx; i < toIdx; ++i) { int letter = letters[i]; if (child[letter][resIdx] < 0) { child[letter][resIdx] = nodePnt; initNodeInternal(nodePnt++, resIdx, letter); } resIdx = child[letter][resIdx]; } return resIdx; } public int access(int[] letters, int fromIdx, int toIdx) { int resIdx = root; for (int i = fromIdx; i < toIdx; ++i) { resIdx = child[letters[i]][resIdx]; if (resIdx < 0) return resIdx; } return resIdx; } private void initNodeInternal(int idx, int parent, int letter) { this.parent[idx] = parent; this.parentLetter[idx] = letter; for (int i = 0; i < letterCnt; ++i) { child[i][idx] = -1; } initNode(idx, parent, letter); } } static class IntArrayUtils { private static final Random random = new Random(); public static void reverse(int[] values, int fromIdx, int toIdx) { for (int i = fromIdx, j = toIdx - 1; i < j; ++i, --j) { values[i] ^= values[j]; values[j] ^= values[i]; values[i] ^= values[j]; } } public static int unique(int[] values) { return unique(values, 0, values.length); } public static int unique(int[] values, int fromIdx, int toIdx) { if (fromIdx == toIdx) return 0; int res = 1; for (int i = fromIdx + 1; i < toIdx; ++i) { if (values[i - 1] != values[i]) { values[fromIdx + res++] = values[i]; } } return res; } public static int lowerBound(int[] values, int fromIdx, int toIdx, int value) { int res = toIdx; for (int lower = 0, upper = toIdx - 1; lower <= upper; ) { int medium = (lower + upper) >> 1; if (value <= values[medium]) { res = medium; upper = medium - 1; } else { lower = medium + 1; } } return res; } public static void swap(int[] values, int uIdx, int vIdx) { if (uIdx == vIdx) return; values[uIdx] ^= values[vIdx]; values[vIdx] ^= values[uIdx]; values[uIdx] ^= values[vIdx]; } public static void sort(int[] values, IntComparator comparator) { sort(values, 0, values.length, comparator); } public static void sort(int[] values, int lower, int upper, IntComparator comparator) { sortInternal(values, lower, upper - 1, comparator); } private static void sortInternal(int[] values, int lower, int upper, IntComparator comparator) { int size = upper - lower + 1; if (size < 2) return; if (size == 2) { if (comparator.compare(values[lower], values[lower + 1]) > 0) { swap(values, lower, lower + 1); } return; } int pivot = values[lower + random.nextInt(upper - lower)]; int i = lower, j = upper; while (i <= j) { for (; comparator.compare(values[i], pivot) < 0; ++i) { } for (; comparator.compare(values[j], pivot) > 0; --j) { } if (i <= j) swap(values, i++, j--); } sortInternal(values, lower, i - 1, comparator); sortInternal(values, i, upper, comparator); } } static interface IntComparator { int compare(int o1, int o2); } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
b044101c44b6e6eb05ba163bf674c7bf
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 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.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jialin Ouyang (Jialin.Ouyang@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; QuickScanner in = new QuickScanner(inputStream); QuickWriter out = new QuickWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { static final int MAXNODE = 200000 * 20; int n; Computer[] computers; int m; int uniqueM; int[] s; int[] uniqueS; int[] disS; int[] idxInTrie; Trie trie; DirectedGraph graph; int c; int u; int[] a; int[] b; public void solve(int testNumber, QuickScanner in, QuickWriter out) { n = in.nextInt(); m = in.nextInt(); computers = new Computer[n]; for (int i = 0; i < n; ++i) computers[i] = new Computer(in.nextInt(), i); Arrays.sort(computers); // p = in.nextInt(n); // pOrder = new int[n]; // for (int i = 0; i < n; ++i) pOrder[i] = i; // IntArrayUtils.sort(pOrder, (x, y) -> p[y] - p[x]); s = in.nextInt(m); uniqueS = Arrays.copyOf(s, m); Arrays.sort(uniqueS); uniqueM = IntArrayUtils.unique(uniqueS); disS = new int[m]; idxInTrie = new int[m]; trie = new Trie(2, MAXNODE); graph = new DirectedGraph(m, m); for (int i = 0; i < m; ++i) { disS[i] = IntArrayUtils.lowerBound(uniqueS, 0, uniqueM, s[i]); idxInTrie[i] = trie.add(s[i], disS[i]); graph.add(disS[i], i); } a = new int[m]; b = new int[n]; c = u = 0; for (int i = 0; i < n; ++i) { // int pIdx = pOrder[i], pValue = p[pIdx]; Computer computer = computers[i]; int trieIdx = trie.access(computer.power); if (trieIdx < 0 || trie.nearestIdx[trieIdx] < 0) continue; int uniqueS = trie.nearestIdx[trieIdx]; int edgeIdx = graph.lastOut[uniqueS]; graph.lastOut[uniqueS] = graph.nextOut[edgeIdx]; int sIdx = graph.toIdx[edgeIdx]; b[computer.idx] = sIdx + 1; ++c; a[sIdx] = trie.nearest[trieIdx]; u += a[sIdx]; trie.dec(idxInTrie[sIdx]); } out.println(c, u); out.println(a); out.println(b); } class Trie extends AbstractTrie { final int MAXN = 40; int[] cnt; int[] nearest; int[] nearestIdx; int[] tmp = new int[MAXN]; public Trie(int letterCapacity, int nodeCapacity) { super(letterCapacity, nodeCapacity); } public void create(int letterCapacity, int nodeCapacity) { super.create(letterCapacity, nodeCapacity); cnt = new int[nodeCapacity]; nearest = new int[nodeCapacity]; nearestIdx = new int[nodeCapacity]; } public void initNode(int idx, int parent, int parentLetter) { cnt[idx] = 0; nearest[idx] = MAXN; nearestIdx[idx] = -1; } public int add(int s, int uniqueS) { int len = parse(s); int res = add(tmp, 0, len); ++cnt[res]; for (int i = res, j = 0; i >= 0; i = parent[i], ++j) if (nearest[i] > j) { nearest[i] = j; nearestIdx[i] = uniqueS; } return res; } public int access(int s) { int len = parse(s); return access(tmp, 0, len); } public void dec(int idx) { if (cnt[idx] <= 0) throw new IllegalArgumentException(); --cnt[idx]; for (; idx >= 0 && cnt[idx] == 0; idx = parent[idx]) { merge(idx); } } private int parse(int s) { int res = 0; for (; s > 1; s = (s + 1) >> 1) { tmp[res++] = 1 - (s & 1); } IntArrayUtils.reverse(tmp, 0, res); return res; } private void merge(int idx) { int left = child[0][idx], right = child[1][idx]; if (left < 0 && right < 0) { nearest[idx] = MAXN; nearestIdx[idx] = -1; } else if (left < 0) { update(idx, right); } else if (right < 0) { update(idx, left); } else { update(idx, nearest[left] < nearest[right] ? left : right); } } private void update(int idx, int fromIdx) { nearest[idx] = Math.min(nearest[fromIdx] + 1, MAXN); nearestIdx[idx] = nearestIdx[fromIdx]; } } class Computer implements Comparable<Computer> { int power; int idx; public Computer(int power, int idx) { this.power = power; this.idx = idx; } public int compareTo(Computer o) { return o.power - power; } } } static abstract class AbstractTrie { public int[] parent; public int[] parentLetter; public int[][] child; public int root; public int letterCnt; public int nodePnt; public abstract void initNode(int idx, int parent, int parentLetter); public AbstractTrie(int letterCapacity, int nodeCapacity) { create(letterCapacity, nodeCapacity); init(letterCapacity); } public void create(int letterCapacity, int nodeCapacity) { parent = new int[nodeCapacity]; parentLetter = new int[nodeCapacity]; child = new int[letterCapacity][nodeCapacity]; } public void init(int letterCnt) { this.root = 0; this.letterCnt = letterCnt; this.nodePnt = 1; initNodeInternal(0, -1, -1); } public int add(int[] letters, int fromIdx, int toIdx) { int resIdx = root; for (int i = fromIdx; i < toIdx; ++i) { int letter = letters[i]; if (child[letter][resIdx] < 0) { child[letter][resIdx] = nodePnt; initNodeInternal(nodePnt++, resIdx, letter); } resIdx = child[letter][resIdx]; } return resIdx; } public int access(int[] letters, int fromIdx, int toIdx) { int resIdx = root; for (int i = fromIdx; i < toIdx; ++i) { resIdx = child[letters[i]][resIdx]; if (resIdx < 0) return resIdx; } return resIdx; } private void initNodeInternal(int idx, int parent, int letter) { this.parent[idx] = parent; this.parentLetter[idx] = letter; for (int i = 0; i < letterCnt; ++i) { child[i][idx] = -1; } initNode(idx, parent, letter); } } static class QuickWriter { private final PrintWriter writer; public QuickWriter(OutputStream outputStream) { this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public QuickWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; ++i) { if (i > 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.print('\n'); } public void print(int[] objects) { print(objects, ' '); } public void print(int[] objects, char delimiter) { for (int i = 0; i < objects.length; ++i) { if (i > 0) { writer.print(delimiter); } writer.print(objects[i]); } } public void println(int[] objects) { print(objects); writer.print('\n'); } public void close() { writer.close(); } } static class IntArrayUtils { public static void reverse(int[] values, int fromIdx, int toIdx) { for (int i = fromIdx, j = toIdx - 1; i < j; ++i, --j) { values[i] ^= values[j]; values[j] ^= values[i]; values[i] ^= values[j]; } } public static int unique(int[] values) { return unique(values, 0, values.length); } public static int unique(int[] values, int fromIdx, int toIdx) { if (fromIdx == toIdx) return 0; int res = 1; for (int i = fromIdx + 1; i < toIdx; ++i) { if (values[i - 1] != values[i]) { values[fromIdx + res++] = values[i]; } } return res; } public static int lowerBound(int[] values, int fromIdx, int toIdx, int value) { int res = toIdx; for (int lower = 0, upper = toIdx - 1; lower <= upper; ) { int medium = (lower + upper) >> 1; if (value <= values[medium]) { res = medium; upper = medium - 1; } else { lower = medium + 1; } } return res; } } static class QuickScanner { private static final int BUFFER_SIZE = 1024; private InputStream stream; private byte[] buffer; private int currentPosition; private int numberOfChars; public QuickScanner(InputStream stream) { this.stream = stream; this.buffer = new byte[BUFFER_SIZE]; this.currentPosition = 0; this.numberOfChars = 0; } public int nextInt() { int c = nextNonSpaceChar(); boolean positive = true; if (c == '-') { positive = false; c = nextChar(); } int res = 0; do { if (c < '0' || '9' < c) throw new RuntimeException(); res = res * 10 + c - '0'; c = nextChar(); } while (!isSpaceChar(c)); return positive ? res : -res; } public int[] nextInt(int n) { int[] res = new int[n]; nextInt(n, res); return res; } public void nextInt(int n, int[] res) { for (int i = 0; i < n; ++i) { res[i] = nextInt(); } } public int nextNonSpaceChar() { int res = nextChar(); for (; isSpaceChar(res) || res < 0; res = nextChar()) ; return res; } public int nextChar() { if (numberOfChars == -1) { throw new RuntimeException(); } if (currentPosition >= numberOfChars) { currentPosition = 0; try { numberOfChars = stream.read(buffer); } catch (Exception e) { throw new RuntimeException(e); } if (numberOfChars <= 0) { return -1; } } return buffer[currentPosition++]; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c < 0; } } static class DirectedGraph { public int vertexCnt; public int edgeCnt; public int[] fromIdx; public int[] toIdx; public int[] nextIn; public int[] nextOut; public int[] lastIn; public int[] lastOut; public int[] inDegree; public int[] outDegree; public DirectedGraph(int vertexCapacity, int edgeCapacity) { create(vertexCapacity, edgeCapacity); init(vertexCapacity); } public void create(int vertexCapacity, int edgeCapacity) { fromIdx = new int[edgeCapacity]; toIdx = new int[edgeCapacity]; lastIn = new int[vertexCapacity]; lastOut = new int[vertexCapacity]; nextIn = new int[edgeCapacity]; nextOut = new int[edgeCapacity]; inDegree = new int[vertexCapacity]; outDegree = new int[vertexCapacity]; } public void init(int vertexCnt) { this.vertexCnt = vertexCnt; this.edgeCnt = 0; Arrays.fill(inDegree, 0, vertexCnt, 0); Arrays.fill(outDegree, 0, vertexCnt, 0); Arrays.fill(lastIn, 0, vertexCnt, -1); Arrays.fill(lastOut, 0, vertexCnt, -1); } public void add(int fromIdx, int toIdx) { this.fromIdx[edgeCnt] = fromIdx; this.toIdx[edgeCnt] = toIdx; ++outDegree[fromIdx]; ++inDegree[toIdx]; nextOut[edgeCnt] = lastOut[fromIdx]; lastOut[fromIdx] = edgeCnt; nextIn[edgeCnt] = lastIn[toIdx]; lastIn[toIdx] = edgeCnt; ++edgeCnt; } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
d85bd46a9692043c197bfce7ce20e1f3
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; public class Test { public static void main(String[] args) { FastScanner scanner = new FastScanner(); int n = scanner.nextInt(); int m = scanner.nextInt(); Comp[] pa = new Comp[n]; Socket[] sa = new Socket[m]; Map<Long, QuickList> p = new HashMap<>(); List<Socket> socks = new ArrayList<>(); int c = 0; for (int i = 0; i < n; i++) { long pp = scanner.nextLong(); pa[i] = new Comp(pp, i); p.computeIfAbsent(pp, uu -> new QuickList()).add(pa[i]); } for (int i = 0; i < m; i++) { long ss = scanner.nextLong(); sa[i] = new Socket(ss, i); } for (Socket ss : sa) { QuickList cmps = p.get(ss.s); if (cmps != null && !cmps.isEmpty()) { Comp toRemove = cmps.poll(); toRemove.socket = ss.index; c++; ss.count = 0; ss.used = true; } else { socks.add(ss); } } int u = 0; Collections.sort(socks); for (int i = 0; i < socks.size(); i++) { Socket sock = socks.get(i); while (sock.s >= 1) { QuickList cmps = p.get(sock.s); if (cmps != null && !cmps.isEmpty()) { Comp toRemove = cmps.poll(); toRemove.socket = sock.index; c++; u += sock.count; sock.used = true; break; } else { sock.count++; sock.s = sock.s == 1 ? 0 : (sock.s / 2) + (sock.s % 2); } } } System.out.println(c + " " + u); System.out.println(Stream.of(sa).map(uu -> "" + (!uu.used ? 0 : uu.count)).collect(Collectors.joining(" "))); System.out.println(Stream.of(pa).map(uu -> "" + (uu.socket + 1)).collect(Collectors.joining(" "))); } private static class QuickList { int size; List<Comp> cmp = new ArrayList<>(); public void add(Comp comp) { cmp.add(comp); size = cmp.size(); } public Comp poll() { Comp aa = cmp.get(size - 1); size--; return aa; } public boolean isEmpty() { return size == 0; } } private static class Comp { long p; int index; int socket = -1; public Comp(long p, int index) { this.p = p; this.index = index; } } private static class Socket implements Comparable<Socket> { long s; int index; int count; boolean used; public Socket(long p, int index) { this.s = p; this.index = index; } @Override public int compareTo(Socket o) { int res = Long.compare(s, o.s); if (res == 0) { return index - o.index; } return res; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
7c50d21a306dd7612f9b436ca07a72e4
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.BufferedReader; 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.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class E { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); long[] p = new long[n]; long[] s = new long[m]; long max = 0L; for(int i=0;i<n;i++) p[i] = in.nextLong(); for(int i=0;i<m;i++){ s[i] = in.nextLong(); if(max < s[i]) max = s[i]; } int[] b = new int[n]; int[] a = new int[m]; int[] c = new int[m]; Arrays.fill(c, -1); HashMap<Long, Queue<Integer>> coms = new HashMap<>(); for(int i=0;i<n;i++){ if(coms.containsKey(p[i])){ coms.get(p[i]).add(i); }else{ Queue<Integer> aa = new LinkedList<>(); aa.add(i); coms.put(p[i], aa); } } int count = 0; int u = 0; while(max > 0){ for(int i=0;i<m;i++){ if(c[i]!=-1) continue; if(coms.containsKey(s[i])){ count++; Queue<Integer> ll = coms.get(s[i]); c[i] = ll.poll(); b[c[i]] = i+1; u += a[i]; if(ll.size() == 0){ coms.remove(s[i]); } }else{ a[i]++; s[i] = (s[i]+1)/2; } } if(max == 1) break; max = (max + 1)/2; } out.println(count + " " + u); for(int i=0;i<m;i++){ if(c[i]==-1){ out.print(0 + " "); }else{ out.print(a[i] + " "); } } out.println(); for(int i=0;i<n;i++){ out.print((b[i]) + " "); } out.flush(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
5cc253d6e0d9bdef20b7ebdd2224be90
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.NoSuchElementException; public class E { private static class Task { void solve(FastScanner in, PrintWriter out) throws Exception { long start = System.currentTimeMillis(); int N = in.nextInt(); int M = in.nextInt(); int[] P = in.nextIntArray(N); int[] S = in.nextIntArray(M); int[][] powers = new int[N][2]; for (int i = 0; i < N; i++) { powers[i][0] = P[i]; powers[i][1] = i; } Arrays.sort(powers, (o1, o2) -> -(o1[0] - o2[0])); System.err.println(System.currentTimeMillis() - start); long[] sockets = new long[M * 31]; long bit32 = 1L << 32; long bit18 = 1L << 18; int pos = 0; for (int id = 0; id < M; id++) { long s = S[id]; long x = s * bit32 + 30 * bit18 + id; sockets[pos++] = -x; for (int adapter = 1; adapter <= 30; adapter++) { if (s == 1) break; s = (s + 1) / 2; long y = s * bit32 + (30 - adapter) * bit18 + id; sockets[pos++] = -y; } } System.err.println(System.currentTimeMillis() - start); Arrays.sort(sockets); System.err.println(System.currentTimeMillis() - start); int c = 0; int adapters = 0; int[] A = new int[M]; int[] B = new int[N]; boolean[] used = new boolean[M]; int cur = 0; for (int[] power : powers) { int p = power[0]; while (cur < pos) { long socket = -sockets[cur]; long s = socket / bit32; if (s < p) break; long adapter = (socket - s * bit32) / bit18; int id = (int) (socket - s * bit32 - adapter * bit18); adapter = 30 - adapter; if (used[id]) { cur++; } else if (s == p) { c++; adapters += adapter; A[id] = (int) adapter; B[power[1]] = id + 1; used[id] = true; cur++; break; } else { cur++; } } } System.err.println(System.currentTimeMillis() - start); StringBuilder builder = new StringBuilder(); builder.append(c).append(" ").append(adapters).append("\n"); for (int i = 0; i < M; i++) { if (i > 0) builder.append(" "); builder.append(A[i]); } builder.append("\n"); for (int i = 0; i < N; i++) { if (i > 0) builder.append(" "); builder.append(B[i]); } builder.append("\n"); out.println(builder.toString()); System.err.println(System.currentTimeMillis() - start); } } /** * ここから下はテンプレートです。 */ public static void main(String[] args) throws Exception { OutputStream outputStream = System.out; FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } private static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int bufferLength = 0; private boolean hasNextByte() { if (ptr < bufferLength) { return true; } else { ptr = 0; try { bufferLength = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (bufferLength <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][]; for (int i = 0; i < n; i++) { map[i] = nextDoubleArray(m); } return map; } public int nextInt() { return (int) nextLong(); } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = 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 String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) array[i] = next(); return array; } public char[][] nextCharMap(int n) { char[][] array = new char[n][]; for (int i = 0; i < n; i++) array[i] = next().toCharArray(); return array; } public int[][] nextIntMap(int n, int m) { int[][] map = new int[n][]; for (int i = 0; i < n; i++) { map[i] = nextIntArray(m); } return map; } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
3ee0c4e2e4e53356d65f03ca2d0c5adc
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Map; import java.util.Queue; import java.io.BufferedReader; import java.util.Comparator; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Hieu Le */ 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[] comps = new int[n]; Map<Integer, Integer> compCount = new HashMap<>(); for (int i = 0; i < n; ++i) { int power = in.nextInt(); comps[i] = power; if (!compCount.containsKey(power)) compCount.put(power, 0); compCount.put(power, compCount.get(power) + 1); } Machine[] sockets = new Machine[m]; for (int i = 0; i < m; ++i) { int power = in.nextInt(); sockets[i] = new Machine(i, power); } Arrays.sort(sockets, new Comparator<Machine>() { public int compare(Machine o1, Machine o2) { return o1.power - o2.power; } }); int[] adapterCount = new int[sockets.length]; Map<Integer, Queue<Integer>> compToSocket = new HashMap<>(); int u = 0; for (Machine socket : sockets) { int count = 0; int power = socket.power; while (power > 0) { if (compCount.containsKey(power) && compCount.get(power) > 0) { compCount.put(power, compCount.get(power) - 1); adapterCount[socket.index] = count; u += count; if (!compToSocket.containsKey(power)) compToSocket.put(power, new LinkedList<>()); compToSocket.get(power).add(socket.index + 1); break; } if (power == 1) { break; } count++; power = (power + 1) / 2; } } int[] result = new int[comps.length]; int c = 0; for (int i = 0; i < comps.length; ++i) { int power = comps[i]; if (compToSocket.containsKey(power) && !compToSocket.get(power).isEmpty()) { c++; int socket = compToSocket.get(power).poll(); result[i] = socket; } } out.println(c + " " + u); for (int a : adapterCount) out.print(a + " "); out.println(); for (int socket : result) out.print(socket + " "); out.println(); } private class Machine { private int index; private int power; public Machine(int index, int power) { this.index = index; this.power = power; } } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; private static final int BUFFER_SIZE = 32768; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), BUFFER_SIZE); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
84433bed0ad599bb3e82eb9aa2956c46
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.NoSuchElementException; /* _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' | | \ .-\__ `-` ___/-. / ___`. .' /--.--\ `. . __ ."" '< `.___\_<|>_/___.' >'"". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ======`-.____`-.___\_____/___.-`____.-'====== `=---=' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ pass System Test! */ public class E { private static class Task { void solve(FastScanner in, PrintWriter out) throws Exception { long start = System.currentTimeMillis(); int N = in.nextInt(); int M = in.nextInt(); int[] P = in.nextIntArray(N); int[] S = in.nextIntArray(M); int[][] powers = new int[N][2]; for (int i = 0; i < N; i++) { powers[i][0] = P[i]; powers[i][1] = i; } Arrays.sort(powers, (o1, o2) -> -(o1[0] - o2[0])); System.err.println(System.currentTimeMillis() - start); long[] sockets = new long[M * 31]; long bit32 = 1L << 32; long bit18 = 1L << 18; int pos = 0; for (int id = 0; id < M; id++) { long s = S[id]; long x = s * bit32 + 30 * bit18 + id; sockets[pos++] = -x; for (int adapter = 1; adapter <= 30; adapter++) { if (s == 1) break; s = (s + 1) / 2; long y = s * bit32 + (30 - adapter) * bit18 + id; sockets[pos++] = -y; } } System.err.println(System.currentTimeMillis() - start); Arrays.sort(sockets); System.err.println(System.currentTimeMillis() - start); int c = 0; int adapters = 0; int[] A = new int[M]; int[] B = new int[N]; boolean[] used = new boolean[M]; int cur = 0; for (int[] power : powers) { // O(N) int p = power[0]; while (cur < pos) { long socket = -sockets[cur]; long s = socket / bit32; if (s < p) break; long adapter = (socket - s * bit32) / bit18; int id = (int) (socket - s * bit32 - adapter * bit18); adapter = 30 - adapter; if (used[id]) { cur++; } else if (s == p) { c++; adapters += adapter; A[id] = (int) adapter; B[power[1]] = id + 1; used[id] = true; cur++; break; } else { cur++; } } } System.err.println(System.currentTimeMillis() - start); StringBuilder builder = new StringBuilder(); builder.append(c).append(" ").append(adapters).append("\n"); for (int i = 0; i < M; i++) { if (i > 0) builder.append(" "); builder.append(A[i]); } builder.append("\n"); for (int i = 0; i < N; i++) { if (i > 0) builder.append(" "); builder.append(B[i]); } builder.append("\n"); out.println(builder.toString()); System.err.println(System.currentTimeMillis() - start); } } /** * ここから下はテンプレートです。 */ public static void main(String[] args) throws Exception { OutputStream outputStream = System.out; FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } private static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int bufferLength = 0; private boolean hasNextByte() { if (ptr < bufferLength) { return true; } else { ptr = 0; try { bufferLength = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (bufferLength <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][]; for (int i = 0; i < n; i++) { map[i] = nextDoubleArray(m); } return map; } public int nextInt() { return (int) nextLong(); } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = 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 String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) array[i] = next(); return array; } public char[][] nextCharMap(int n) { char[][] array = new char[n][]; for (int i = 0; i < n; i++) array[i] = next().toCharArray(); return array; } public int[][] nextIntMap(int n, int m) { int[][] map = new int[n][]; for (int i = 0; i < n; i++) { map[i] = nextIntArray(m); } return map; } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
c56140cdcae2aa4b5b52612def86c68c
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.IntStream; import static java.lang.Math.*; public class Main { FastScanner in; PrintWriter out; static final String FILE = ""; void solve() { int n = in.nextInt(), m = in.nextInt(); int[] p = new int[n]; for (int i = 0; i < n; i++) p[i] = in.nextInt(); int[] s = new int[m]; for (int i = 0; i < m; i++) s[i] = in.nextInt(); int[] sortedS = IntStream .range(0, m) .mapToObj(i -> i) .sorted((a, b) -> Integer.compare(s[a], s[b])) .mapToInt(Integer::intValue) .toArray(); Map<Integer, TreeSet<Integer>> map = new TreeMap<>(); for (int i = 0; i < n; i++) { TreeSet<Integer> list = map.getOrDefault(p[i], new TreeSet<>()); list.add(i); map.put(p[i], list); } int[] ansP = new int[n]; int[] ansS = new int[m]; int c = 0, u = 0; for (Integer index : sortedS) { int val = s[index]; int del = 0; while (true) { if (map.containsKey(val)) { TreeSet<Integer> set = map.get(val); int cur = set.first(); ansP[cur] = index + 1; ansS[index] = del; u += del; c++; set.remove(cur); if (set.isEmpty()) map.remove(val); else map.put(val, set); break; } del++; if (val == 1) break; val = (val + 1) / 2; } } out.println(c + " " + u); for (Integer it : ansS) out.print(it + " "); out.println(); for (Integer it : ansP) out.print(it + " "); } public void run() { if (FILE.equals("")) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { try { in = new FastScanner(new FileInputStream(FILE + ".in")); out = new PrintWriter(new FileOutputStream(FILE + ".out")); } catch (FileNotFoundException e) { e.printStackTrace(); } } solve(); out.close(); } public static void main(String[] args) { //long time = System.currentTimeMillis(); (new Main()).run(); //System.out.println("TIME = " + (double)(System.currentTimeMillis() - time) / 1000.0); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } } class Pair<A extends Comparable<A>, B extends Comparable<B>> implements Comparable<Pair<A, B>> { public A a; public B b; public Pair(A a, B b) { this.a = a; this.b = b; } @Override public int compareTo(Pair<A, B> o) { if (o == null || o.getClass() != getClass()) return 1; int cmp = a.compareTo(o.a); if (cmp == 0) return b.compareTo(o.b); return cmp; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; if (a != null ? !a.equals(pair.a) : pair.a != null) return false; return !(b != null ? !b.equals(pair.b) : pair.b != null); } } class PairInt extends Pair<Integer, Integer> { public PairInt(Integer u, Integer v) { super(u, v); } } class PairLong extends Pair<Long, Long> { public PairLong(Long u, Long v) { super(u, v); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
f0e289c03aabbf0271cb765020adc038
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Don Li */ public class Sockets { void solve() { int n = in.nextInt(), m = in.nextInt(); int[] p = new int[n]; for (int i = 0; i < n; i++) p[i] = in.nextInt(); int[] s = new int[m + 1]; for (int i = 0; i < m; i++) s[i] = in.nextInt(); Integer[] computers = new Integer[n]; for (int i = 0; i < n; i++) computers[i] = i; Integer[] sockets = new Integer[m]; for (int i = 0; i < m; i++) sockets[i] = i; Arrays.sort(computers, (i, j) -> Integer.compare(p[i], p[j])); Arrays.sort(sockets, (i, j) -> Integer.compare(s[i], s[j])); int c = 0, u = 0; int[] a = new int[m], b = new int[n]; boolean[] done = new boolean[n], used = new boolean[m]; for (int i = 0; i <= 30; i++) { for (int j = 0, k = 0; j < n && k < m; j++) { if (!done[j]) { int x = p[computers[j]]; while (k < m && (s[sockets[k]] < x || used[k])) k++; if (k == m) break; if (s[sockets[k]] == x) { done[j] = true; used[k] = true; a[sockets[k]] = i; b[computers[j]] = sockets[k] + 1; c++; u += i; } } } for (int j = 0; j < m; j++) s[j] = (s[j] + 1) / 2; } out.printf("%d %d%n", c, u); for (int i = 0; i < m; i++) { if (i > 0) out.print(' '); out.print(a[i]); } out.println(); for (int i = 0; i < n; i++) { if (i > 0) out.print(' '); out.print(b[i]); } out.println(); } public static void main(String[] args) { /*int[] s = new int[]{100, 10, 10, 10}; TreeSet<Integer> set = new TreeSet<>((i, j) -> { if (s[i] != s[j]) return Integer.compare(s[i], s[j]); return Integer.compare(i, j); }); for (int i = 0; i < 3; i++) set.add(i); Integer k = set.floor(3); set.remove(k);*/ in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new Sockets().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
72332b7613550b622c86ad810745835e
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author llamaoo7 */ 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); ESockets solver = new ESockets(); solver.solve(1, in, out); out.close(); } static class ESockets { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); comp[] c = new comp[n]; for (int i = 1; i <= n; i++) c[i - 1] = new comp(in.nextInt(), i); sock[] s = new sock[m]; for (int i = 1; i <= m; i++) s[i - 1] = new sock(in.nextInt(), i); int ac = 0; int compc = 0; int adaptc = 0; for (int i = 0; i < 32; i++) { Arrays.sort(c); Arrays.sort(s); int ci = 0; int si = 0; while (ci < n && si < m && c[ci].socket == 0 && !s[si].used) { comp cc = c[ci]; sock cs = s[si]; if (cc.need == cs.curP) { cc.socket = cs.ind; cs.used = true; cs.adapt = ac; adaptc += ac; compc++; ci++; si++; } else if (cc.need < cs.curP) { ci++; } else si++; } for (int j = 0; j < m; j++) s[j].curP = (s[j].curP + 1) / 2; ac++; } out.println(compc + " " + adaptc); Arrays.sort(c, Comparator.comparingInt(cur -> cur.ind)); Arrays.sort(s, Comparator.comparingInt(sock -> sock.ind)); for (int i = 0; i < m; i++) out.print(s[i].adapt + " "); out.println(); for (int i = 0; i < n; i++) out.print(c[i].socket + " "); } class comp implements Comparable<comp> { int need; int ind; int socket; comp(int need, int ind) { this.need = need; this.ind = ind; } public int compareTo(comp o) { if (this.socket != o.socket) return this.socket - o.socket; return this.need - o.need; } } class sock implements Comparable<sock> { int curP; int ind; int adapt; boolean used; sock(int p, int ind) { this.curP = p; this.ind = ind; } public int compareTo(sock o) { if (this.used != o.used) return this.used ? 1 : -1; return this.curP - o.curP; } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
627d86ca5ea9ef4b4736a25d5ea6f0bb
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.io.BufferedReader; import java.util.regex.Pattern; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author amalev */ 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { int ceil(int x, int y) { return (x / y) + (x % y == 0 ? 0 : 1); } public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); HashMap<Integer, List<Integer>> p = new HashMap<>(2 * n); for (int i = 0; i < n; i++) { int p_i = in.nextInt(); if (p.containsKey(p_i)) { p.get(p_i).add(i); } else { ArrayList<Integer> list = new ArrayList<>(); list.add(i); p.put(p_i, list); } } Pair[] s = new Pair[m]; for (int i = 0; i < m; i++) { s[i] = new Pair(in.nextInt(), i); } Arrays.sort(s, (x, y) -> Integer.compare(x.s, y.s)); int c = 0; int u = 0; int[] a = new int[m]; int[] b = new int[n]; for (int i = 0; i < m; i++) { int s_i = s[i].s; if (p.containsKey(s_i)) { List<Integer> entry = p.get(s_i); a[s[i].i] = 1; b[entry.remove(entry.size() - 1)] = s[i].i + 1; c++; if (entry.isEmpty()) { p.remove(s_i); } } } for (int i = 0; i < m; i++) { if (a[s[i].i] > 0) { continue; } int s_i = s[i].s; int j = 0; do { j++; s_i = ceil(s_i, 2); if (p.containsKey(s_i)) { List<Integer> entry = p.get(s_i); a[s[i].i] = j + 1; b[entry.remove(entry.size() - 1)] = s[i].i + 1; c++; u += j; if (entry.isEmpty()) { p.remove(s_i); } break; } } while (s_i > 1); } out.printf("%d %d\n", c, u); for (int i = 0; i < m; i++) { out.print(a[i] > 0 ? a[i] - 1 : a[i]); out.print(" "); } out.println(); for (int i = 0; i < n; i++) { out.print(b[i]); out.print(" "); } out.println(); } class Pair { int s; int i; public Pair(int s, int i) { this.s = s; this.i = i; } } } static class FastScanner { final BufferedReader input; String[] buffer; int pos; final static Pattern SEPARATOR = Pattern.compile("\\s+"); public FastScanner(InputStream inputStream) { input = new BufferedReader(new InputStreamReader(inputStream)); } private String read() { try { if (buffer == null || pos >= buffer.length) { buffer = SEPARATOR.split(input.readLine()); pos = 0; } return buffer[pos++]; } catch (Exception ex) { throw new RuntimeException(ex); } } public int nextInt() { return Integer.parseInt(read()); } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
c2a94f51c7e3c70b5da051d7378e9ff6
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.*; import java.util.*; public class CF732E { static class X { int p, j, a; X(int p, int j, int a) { this.p = p; this.j = j; this.a = a; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); HashMap<Integer, LinkedList<Integer>> map = new HashMap<>(); st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { int p = Integer.parseInt(st.nextToken()); LinkedList<Integer> list = map.get(p); if (list == null) { list = new LinkedList<>(); map.put(p, list); } list.addLast(i); } LinkedList<X> q = new LinkedList<>(); st = new StringTokenizer(br.readLine()); for (int j = 0; j < m; j++) { int p = Integer.parseInt(st.nextToken()); q.addLast(new X(p, j, 0)); } int[] aa = new int[m]; int[] bb = new int[n]; int c = 0, u = 0; while (!q.isEmpty()) { X x = q.removeFirst(); LinkedList<Integer> list = map.get(x.p); if (list == null || list.isEmpty()) { if (x.p > 1) { x.p = (x.p + x.p % 2) / 2; x.a++; q.addLast(x); } continue; } u += aa[x.j] = x.a; int i = list.removeLast(); bb[i] = x.j + 1; c++; } StringBuilder sa = new StringBuilder(); for (int j = 0; j < m; j++) sa.append(aa[j] + " "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) sb.append(bb[i] + " "); System.out.println(c + " " + u); System.out.println(sa); System.out.println(sb); } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
8fa32ca4691fe397ed53f7dfae0b838f
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.io.IOException; import java.util.ArrayDeque; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Queue; public class Sockets { public static void main(String[] args) { FasterScanner sc = new FasterScanner(); int N = sc.nextInt(); int M = sc.nextInt(); int P[] = new int[N + 1]; for (int i = 1; i <= N; i++) { P[i] = sc.nextInt(); } int[] S = new int[M + 1]; for (int i = 1; i <= M; i++) { S[i] = sc.nextInt(); } int[] A = new int[M + 1]; int[] B = new int[N + 1]; CountMap cm = new CountMap(); for (int i = 1; i <= N; i++) { cm.addValue(P[i], i); } Queue<Socket> q = new ArrayDeque<Socket>(); for (int i = 1; i <= M; i++) { Socket sck = new Socket(i, S[i]); q.offer(sck); } int C = 0; long U = 0; while (!q.isEmpty()) { Socket sck = q.poll(); if (cm.hasMore(sck.power)) { int comp = cm.pollKey(sck.power); C++; U += sck.adapters; A[sck.index] = sck.adapters; B[comp] = sck.index; } else if (sck.power > 1) { sck.power = (sck.power + 1) / 2; sck.adapters++; q.offer(sck); } } StringBuilder sb = new StringBuilder(); sb.append(C + " " + U + "\n"); for (int i = 1; i <= M; i++) { sb.append(A[i] + " "); } sb.append("\n"); for (int i = 1; i <= N; i++) { sb.append(B[i] + " "); } sb.append("\n"); System.out.print(sb.toString()); } public static class Socket { public int index; public int power; public int adapters; public Socket(int idx, int p) { this.index = idx; this.power = p; } } public static class CountMap extends HashMap<Integer, Queue<Integer>> { private static final long serialVersionUID = -3016673548224240376L; public boolean hasMore(int k) { return this.containsKey(k) && !this.get(k).isEmpty(); } public int pollKey(int k) { if (this.hasMore(k)) { return this.get(k).poll(); } else { return -1; } } public void addValue(int k, int v) { Queue<Integer> q = this.containsKey(k) ? this.get(k) : new ArrayDeque<Integer>(); q.offer(v); this.put(k, q); } } public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
5c866a7d84365f01f5882ca57755d153
train_002.jsonl
1476714900
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; public class Main { @SuppressWarnings("unchecked") public static void main (String[] args) throws java.lang.Exception { //BufferedReader in=new BufferedReader(new FileReader(".\\mmk\\test\\A-small-attempt0.in")); //PrintWriter out=new PrintWriter(".\\mmk\\test\\output.txt"); BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); int n,m,i,level,maximum_computers_connected,minimum_sockets_used,val,pos; StringTokenizer st=new StringTokenizer(in.readLine().trim()); n=Integer.parseInt(st.nextToken()); m=Integer.parseInt(st.nextToken()); int[] p=new int[n+1]; int[] s=new int[m+1]; int[] no_of_adapters_in_socket=new int[m+1]; int[] socket_no_of_computer=new int[n+1]; Hashtable<Integer,Queue<Integer>> computer_power_table=new Hashtable<Integer,Queue<Integer>>(); Queue<Integer> queue; st=new StringTokenizer(in.readLine().trim()); for(i=0;i<n;i++) { p[i+1]=Integer.parseInt(st.nextToken()); if(!computer_power_table.containsKey(p[i+1])) { queue=new LinkedList<Integer>(); queue.add(i+1); computer_power_table.put(p[i+1],queue); } else { queue=computer_power_table.get(p[i+1]); queue.add(i+1); computer_power_table.put(p[i+1],queue); } } st=new StringTokenizer(in.readLine().trim()); for(i=0;i<m;i++) { s[i+1]=Integer.parseInt(st.nextToken()); } maximum_computers_connected=0; minimum_sockets_used=0; for(level=0;level<=35;level++) { if(level>0) { for(i=1;i<=m;i++) { if(s[i]!=-1) { s[i]=(int)Math.ceil(((double)s[i])/2); } } } for(i=1;i<=m;i++) { if(s[i]!=-1 && computer_power_table.containsKey(s[i])) { val=computer_power_table.get(s[i]).size(); if(val>0) { queue=computer_power_table.get(s[i]); pos=queue.poll(); computer_power_table.put(s[i],queue); maximum_computers_connected++; minimum_sockets_used+=level; s[i]=-1; no_of_adapters_in_socket[i]=level; socket_no_of_computer[pos]=i; } } } } out.println(maximum_computers_connected+" "+minimum_sockets_used); out.print(no_of_adapters_in_socket[1]); for(i=2;i<=m;i++) { out.print(" "+no_of_adapters_in_socket[i]); } out.println(); out.print(socket_no_of_computer[1]); for(i=2;i<=n;i++) { out.print(" "+socket_no_of_computer[i]); } out.println(); out.flush(); out.close(); } }
Java
["2 2\n1 1\n2 2", "2 1\n2 100\n99"]
2 seconds
["2 2\n1 1\n1 2", "1 6\n6\n1 0"]
null
Java 8
standard input
[ "sortings", "greedy" ]
0a687ec4e1411750e33cc3670a614574
The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.
2,100
In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.
standard output
PASSED
a85e60107195797024e19e20167bfc89
train_002.jsonl
1308236400
An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.
256 megabytes
import java.io.*; import java.util.*; public final class african_puzzle { static Scanner sc=new Scanner(System.in); static PrintWriter out=new PrintWriter(System.out); public static void main(String args[]) throws Exception { int n=sc.nextInt(),m=sc.nextInt(); char[][] a=new char[n][m]; int[][] v1=new int[n][123]; int[][] v2=new int[m][123]; for(int i=0;i<n;i++) { String input=sc.next(); for(int j=0;j<m;j++) { char curr_char=input.charAt(j); a[i][j]=curr_char; int val=(int)curr_char; v1[i][val]++; v2[j][val]++; } } StringBuffer sb=new StringBuffer(""); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { char curr_char=a[i][j]; int val=(int)curr_char; if(v1[i][val]==1 && v2[j][val]==1) { sb.append(curr_char); } } } out.println(sb); out.close(); } }
Java
["3 3\ncba\nbcd\ncbc", "5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf"]
2 seconds
["abcd", "codeforces"]
null
Java 7
standard input
[ "implementation", "strings" ]
9c90974a0bb860a5e180760042fd5045
The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.
1,100
Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.
standard output
PASSED
5d0fa34945d9c227000e5b7ab23e4387
train_002.jsonl
1308236400
An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.
256 megabytes
import java.util.Scanner; public class AfricanCrossword { public static void main(String[] args) { int n,m; Scanner sc=new Scanner(System.in); n=sc.nextInt(); m=sc.nextInt(); String a=""; int count; String [] word=new String[n]; char [][] wor=new char[n][m]; for (int i=0;i<n;i++) { word[i]=sc.next(); } for (int i=0;i<n;i++) { String hold=word[i]; for (int j=0;j<m;j++){ wor[i][j]=hold.charAt(j); //System.out.print(wor[i][j]+" "); } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { count=0; char hold=wor[i][j]; for (int k = 0; k < m; k++) { if(wor[i][k]==hold) count++; } for (int k=0;k<n;k++) { if(wor[k][j]==hold) count++; } if (count==2) { a+=hold; } } } System.out.println(a); } }
Java
["3 3\ncba\nbcd\ncbc", "5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf"]
2 seconds
["abcd", "codeforces"]
null
Java 7
standard input
[ "implementation", "strings" ]
9c90974a0bb860a5e180760042fd5045
The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.
1,100
Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.
standard output
PASSED
fcd102d8b5256a56b853b1b05c30d775
train_002.jsonl
1308236400
An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Hasan0504 { // public static Scanner input = new Scanner(System.in); public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); // BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in)); int row = input.nextInt(); int col = input.nextInt(); String s = ""; char[][] c = new char[row][col]; for (int i = 0; i < c.length; i++) { c[i] = input.next().toCharArray(); } for (int i = 0; i < row; i++) { boolean flag = false; boolean flag2 = false; for (int ii = 0; ii < c[i].length; ii++) { char cc=c[i][ii]; for(int iii=0;iii<col;iii++){ if(iii==ii) continue; if(c[i][iii]==cc) { flag=true; break; } }// row for(int iii=0;iii<row;iii++){ if(i==iii) continue; if(c[iii][ii]==cc){ flag2=true; break; } }// colum if(flag2==false && flag==false) s+=cc; flag=false; flag2=false; }// sub Row c[i][ii] }// main row By row System.out.println(s); } }
Java
["3 3\ncba\nbcd\ncbc", "5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf"]
2 seconds
["abcd", "codeforces"]
null
Java 7
standard input
[ "implementation", "strings" ]
9c90974a0bb860a5e180760042fd5045
The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.
1,100
Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.
standard output
PASSED
685455a0b032564200f3684be8705eff
train_002.jsonl
1308236400
An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.
256 megabytes
import java.util.Scanner; public class problem90B { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); sc.nextLine(); char[][] arr = new char[n][m]; for(int i=0;i<n;i++){ String str = sc.nextLine(); for(int j=0;j<m;j++){ arr[i][j] = str.charAt(j); } } String str = ""; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ char tmp = arr[i][j]; boolean flag = false; for(int k=0;k<n;k++){ if(k!=i && arr[k][j]==tmp){ flag = true; break; } } if(!flag){ for(int k=0;k<m;k++){ if(k!=j && arr[i][k] == tmp){ flag = true; break; } } } if(!flag) str += tmp; } } System.out.println(str); } }
Java
["3 3\ncba\nbcd\ncbc", "5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf"]
2 seconds
["abcd", "codeforces"]
null
Java 7
standard input
[ "implementation", "strings" ]
9c90974a0bb860a5e180760042fd5045
The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.
1,100
Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.
standard output
PASSED
604895b45652404ad4134d2f3f27baa4
train_002.jsonl
1308236400
An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Solution { private BufferedReader in; private PrintWriter out; private StringTokenizer st; public String next() throws Exception { if (st == null || !st.hasMoreElements()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public void run() throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(); int m = nextInt(); char[][] a = new char[n][m]; for (int i = 0; i < n; ++i) { a[i] = next().toCharArray(); } boolean[][] u = new boolean[n][m]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { for (int k = j + 1; k < m; ++k) { if (a[i][j] == a[i][k]) { u[i][j] = true; u[i][k] = true; } } } } for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { for (int k = j + 1; k < n; ++k) { if (a[j][i] == a[k][i]) { u[j][i] = true; u[k][i] = true; } } } } String ans = ""; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (!u[i][j]) ans += a[i][j]; } } out.println(ans); out.close(); } public static void main(String[] args) throws Exception { new Solution().run(); } }
Java
["3 3\ncba\nbcd\ncbc", "5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf"]
2 seconds
["abcd", "codeforces"]
null
Java 7
standard input
[ "implementation", "strings" ]
9c90974a0bb860a5e180760042fd5045
The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.
1,100
Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.
standard output
PASSED
2e02fd5e28c06f470ccf2bd6e78e035f
train_002.jsonl
1308236400
An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author nasko */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); String[] ret = new String[n]; boolean[][] used = new boolean[n][m]; for(boolean[] u : used) Arrays.fill(u,false); String ans = ""; for(int i = 0; i < n; ++i) ret[i] = in.nextLine(); for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { char c = ret[i].charAt(j); boolean row = false; boolean col = false; for(int q = i + 1; q < n; ++q) { row |= ( c == ret[q].charAt(j)); } for(int q = j + 1; q < m; ++q) { col |= ( c == ret[i].charAt(q)); } for(int q = i-1; q >=0;--q) { row |= ( c == ret[q].charAt(j)); } for(int q = j - 1; q >=0; --q) { col |= ( c == ret[i].charAt(q)); } if(row || col) used[i][j] = true; } } for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { if(!used[i][j]) ans += ret[i].charAt(j); } } out.println(ans); } } 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() { String s = null; try { s = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3 3\ncba\nbcd\ncbc", "5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf"]
2 seconds
["abcd", "codeforces"]
null
Java 7
standard input
[ "implementation", "strings" ]
9c90974a0bb860a5e180760042fd5045
The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.
1,100
Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.
standard output
PASSED
eb29b41fea57943988d93834e4e28a17
train_002.jsonl
1308236400
An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.
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 bfr= new BufferedReader(new InputStreamReader(System.in)); String[] init= bfr.readLine().split(" "); int x=Integer.parseInt(init[0]); int y=Integer.parseInt(init[1]); char matrix[][]= new char[x][y]; int aux[][]= new int[x][y]; int superaux = 0; if(x>y){ superaux=x; }else{ if(y<x){ superaux=y; }else{ superaux=x; } } for (int i = 0; i < superaux; i++) { matrix[i]=bfr.readLine().toCharArray(); } for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { for (int j2 = 0; j2 < y; j2++) { if(matrix[i][j2]==matrix[i][j] && j2!=j && j!=i){ aux[i][j2]='1'; aux[i][j]='1'; } } } } for (int i = 0; i < y; i++) { for (int j = 0; j < x; j++) { for (int j2 = 0; j2 < x; j2++) { if(matrix[j2][i]==matrix[j][i] && j2!=j && j!=i){ aux[j2][i]='1'; aux[j][i]='1'; } } } } StringBuilder stb= new StringBuilder(); for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { if(aux[i][j]!='1'){ stb.append(matrix[i][j]); } } } System.out.println(stb.toString()); } }
Java
["3 3\ncba\nbcd\ncbc", "5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf"]
2 seconds
["abcd", "codeforces"]
null
Java 7
standard input
[ "implementation", "strings" ]
9c90974a0bb860a5e180760042fd5045
The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.
1,100
Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.
standard output
PASSED
a006a27411d0bc77b60b68d76f421b16
train_002.jsonl
1490625300
T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2.In the picture you can see a complete binary tree with n = 15. Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.You have to write a program that for given n answers q queries to the tree.Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.For example, if ui = 4 and si = «UURL», then the answer is 10.
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 D { public void solve(InputReader in, PrintWriter out) { long n, q; n = in.nextLong(); q = in.nextLong(); while(q-- > 0) { long v = in.nextLong(); String s = in.next(); for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c == 'U') { if(v-1 == n/2) { // root continue; } boolean isRight = false; long v1 = v - (v&(-v)); long v2 = v1 & (-v1); isRight = ((v2 >> 1L) == (v&(-v))); //System.out.println("v2 = " + v2); //System.out.println("(v&(-v)) = " + (v&(-v))); //System.out.println("isR " + isRight); if(isRight) v -= v&(-v); else v += v&(-v); } else if(c=='L') { if((v&(-v)) == 1L) { // leaf continue; } v -= ((v&(-v))>>1L); } else { // c== 'R' if((v&(-v)) == 1L) { // leaf continue; } v += ((v&(-v))>>1L); } } System.out.println(v); } } public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); D solver = new D(); solver.solve(in, out); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["15 2\n4\nUURL\n8\nLRLLLLLLLL"]
3 seconds
["10\n5"]
null
Java 8
standard input
[ "bitmasks", "trees" ]
dc35bdf56bb0ac341895e543b001b801
The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105.
1,900
Print q numbers, i-th number must be the answer to the i-th query.
standard output
PASSED
59c0842e0f1185a7e52bb0770c79e5d9
train_002.jsonl
1490625300
T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2.In the picture you can see a complete binary tree with n = 15. Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.You have to write a program that for given n answers q queries to the tree.Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.For example, if ui = 4 and si = «UURL», then the answer is 10.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { long n = in.nextLong(); int q = in.nextInt(); for (int i = 0; i < q; ++i) { long u = in.nextLong(); String path = in.next(); for (int j = 0; j < path.length(); ++j) { if (path.charAt(j) == 'U') { u = goUp(u, n); } else if (path.charAt(j) == 'L') { u = goLeft(u); } else if (path.charAt(j) == 'R') { u = goRight(u); } } out.println(u); } } private long goUp(long u, long n) { long diff = u & -u; long p1 = u + diff; long p2 = u - diff; long res = u; if (goLeft(p1) == u) { res = p1; } else if (goRight(p2) == u) { res = p2; } return res < n ? res : u; } private long goRight(long u) { if ((u & 1L) != 0) { return u; } long diff = u & -u; return u + (diff >> 1); } private long goLeft(long u) { if ((u & 1L) != 0) { return u; } long diff = u & -u; return u - (diff >> 1); } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["15 2\n4\nUURL\n8\nLRLLLLLLLL"]
3 seconds
["10\n5"]
null
Java 8
standard input
[ "bitmasks", "trees" ]
dc35bdf56bb0ac341895e543b001b801
The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105.
1,900
Print q numbers, i-th number must be the answer to the i-th query.
standard output
PASSED
a1601a644065683e4a6e203acd30d241
train_002.jsonl
1490625300
T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2.In the picture you can see a complete binary tree with n = 15. Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.You have to write a program that for given n answers q queries to the tree.Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.For example, if ui = 4 and si = «UURL», then the answer is 10.
256 megabytes
import java.util.*; import java.io.*; public class Solution { public static int findHeight(long n){ int ans = 0; while(n>0){ n>>=1; ans++; } return ans; } public static long[] find(long v,int height, long val){ long temp = val; while(v != temp){ val>>=1; if(v > temp) temp+=val; else temp-=val; height--; } return new long[]{height,val}; } public static void main (String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); long n = Long.parseLong(st.nextToken()); int queries = Integer.parseInt(st.nextToken()); int maxHeight = findHeight( (n>>1)+1L); for(int q=0; q<queries; q++){ long v = Long.parseLong(br.readLine()); String path = br.readLine(); long[] p = find(v,maxHeight,(n>>1)+1L); int height = (int)p[0]; long val = p[1]; for(int i=0; i<path.length(); i++){ if(path.charAt(i) == 'U'){ if(maxHeight == height) continue; long temp = (v-val)/(val<<1); if((temp&1) == 0) v+=val; else v-=val; val<<=1; height++; } else{ if(height == 1) continue; val>>=1; if(path.charAt(i) == 'L') v-=val; else v+=val; height--; } } out.println(v); } out.close(); } }
Java
["15 2\n4\nUURL\n8\nLRLLLLLLLL"]
3 seconds
["10\n5"]
null
Java 8
standard input
[ "bitmasks", "trees" ]
dc35bdf56bb0ac341895e543b001b801
The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105.
1,900
Print q numbers, i-th number must be the answer to the i-th query.
standard output
PASSED
86355663766f1f400a556810f3f01311
train_002.jsonl
1490625300
T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2.In the picture you can see a complete binary tree with n = 15. Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.You have to write a program that for given n answers q queries to the tree.Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.For example, if ui = 4 and si = «UURL», then the answer is 10.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class D { public D() { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); long n = sc.nextLong(); int depth = (int) (Math.log(n + 1) / Math.log(2)); long[] arr = new long[depth + 2]; arr[0] = 1; for (int i = 1; i < depth + 2; i++) arr[i] = 2 * arr[i - 1]; long q = sc.nextInt(); for (int i = 0; i < q; i++) { long u = sc.nextLong(); String s = sc.next(); int j = 0; for (j = 0; j <= depth; j++) if ((u - arr[j]) % arr[j + 1] == 0) break; j++; int d = j; long pos = (u - arr[j - 1]) / arr[j] + 1; for (int k = 0; k < s.length(); k++) { if (s.charAt(k) == 'U') { if (d == depth) continue; d++; pos = (pos + 1) / 2; } else if (s.charAt(k) == 'L') { if (d == 1) continue; d--; pos = 2 * (pos - 1) + 1; } else if (s.charAt(k) == 'R') { if (d == 1) continue; d--; pos = 2 * (pos - 1) + 2; } } long val = arr[d - 1]; long jump = arr[d]; val += (pos - 1) * jump; out.println(val); } sc.close(); out.close(); } public static void main(String[] args) { new D(); } }
Java
["15 2\n4\nUURL\n8\nLRLLLLLLLL"]
3 seconds
["10\n5"]
null
Java 8
standard input
[ "bitmasks", "trees" ]
dc35bdf56bb0ac341895e543b001b801
The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105.
1,900
Print q numbers, i-th number must be the answer to the i-th query.
standard output
PASSED
0e7452c85f7d8957e5b85bb9bd063ba1
train_002.jsonl
1490625300
T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2.In the picture you can see a complete binary tree with n = 15. Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.You have to write a program that for given n answers q queries to the tree.Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.For example, if ui = 4 and si = «UURL», then the answer is 10.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class D { public static void main(String[] args){ FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(System.out); long n = scan.nextLong(); int m = scan.nextInt(); int d = Long.toBinaryString(n).length(); for(int q = 0; q < m; q++){ long k = scan.nextLong(); char[] in = scan.next().toCharArray(); int s = Long.toBinaryString(Long.lowestOneBit(k)).length()-1; // System.out.println(s); out.println(go2(k, 0, in, s, d)); } out.close(); } static long go2(long at, int i, char[] in, int depth, int d){ if(i == in.length) return at; switch(in[i]){ case 'U': if(depth == d-1) return go2(at, i+1, in, depth, d); if((at&(1L<<(depth+1))) > 0)return go2(at^(1L<<(depth)), i+1, in, depth+1, d); else return go2(at^(1L<<depth)^(1L<<(depth+1)), i+1, in, depth+1, d); case 'L': if(depth == 0) return go2(at, i+1, in, depth, d); return go2(at^(1L<<depth)^(1L<<(depth-1)), i+1, in, depth-1, d); case 'R': if(depth == 0) return go2(at, i+1, in, depth, d); return go2(at^(1L<<depth-1), i+1, in, depth-1, d); } return -1; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n){ long[] a = new long[n]; for(int i = 0; i < n; i++) a[i] = nextLong(); return a; } public double[] nextDoubleArray(int n){ double[] a = new double[n]; for(int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char[][] nextGrid(int n, int m){ char[][] grid = new char[n][m]; for(int i = 0; i < n; i++) grid[i] = next().toCharArray(); return grid; } } }
Java
["15 2\n4\nUURL\n8\nLRLLLLLLLL"]
3 seconds
["10\n5"]
null
Java 8
standard input
[ "bitmasks", "trees" ]
dc35bdf56bb0ac341895e543b001b801
The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105.
1,900
Print q numbers, i-th number must be the answer to the i-th query.
standard output
PASSED
f28351853e35adeadb72d4d10ce2fe33
train_002.jsonl
1490625300
T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2.In the picture you can see a complete binary tree with n = 15. Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.You have to write a program that for given n answers q queries to the tree.Each query consists of an integer number ui (1 ≤ ui ≤ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.For example, if ui = 4 and si = «UURL», then the answer is 10.
256 megabytes
import java.util.*; public class a{ public static void main(String[] args) { Scanner in=new Scanner(System.in); long n=in.nextLong(); long q=in.nextLong(); long root=(n/2)+1; while(q--!=0){ long x=in.nextLong(); String str=in.next(); for(int i=0;i<str.length();i++){ // System.out.println("x "+x); // System.out.println("i "+i); char c=str.charAt(i); if(c=='U'&&x!=root){ // System.out.println("U"); long k=(long)(Math.log(max(x))/Math.log(2)); // System.out.println(k+" "+max(x)); long p=x+(long)Math.pow(2,k); // System.out.println("p "+p); long kp=(long)(Math.log(max(p))/Math.log(2)); // System.out.println("kp "+kp); long lc=p-(long)Math.pow(2,kp-1); // System.out.println("lc "+lc); if(lc==x){ x=p; } else{ x=x-(long)Math.pow(2,k); } } else if(c=='L'){ // System.out.println("L"); long k=(long)(Math.log(max(x))/Math.log(2)); x=x-(long)Math.pow(2,k-1); } else if(str.charAt(i)=='R'){ // System.out.println("R"); long k=(long)(Math.log(max(x))/Math.log(2)); x=x+(long)Math.pow(2,k-1); } } System.out.println(x); } } static long max(long n){ return n&-n; } } //2 //R UUUU L U LULUU //3 2 1
Java
["15 2\n4\nUURL\n8\nLRLLLLLLLL"]
3 seconds
["10\n5"]
null
Java 8
standard input
[ "bitmasks", "trees" ]
dc35bdf56bb0ac341895e543b001b801
The first line contains two integer numbers n and q (1 ≤ n ≤ 1018, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≤ ui ≤ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1 ≤ i ≤ q) doesn't exceed 105.
1,900
Print q numbers, i-th number must be the answer to the i-th query.
standard output
PASSED
8cbf3e1f448daf99e3b7b75be3e60074
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int k=input.nextInt(); ArrayList<Integer>arr=new ArrayList<Integer>(); for(int i=0;i<n;i++) arr.add(input.nextInt()); k--; int t=arr.get(k); for(int i=k+1;i<n;i++){ if(t!=arr.get(i)){ System.out.print(-1); System.exit(0); } } int c=-1; for(int i=0;i<k;i++){ if(arr.get(i)!=t){ c=i; } } System.out.print(c+1); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
cbf89cde570f9f750a9e0707dff6834b
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int k=input.nextInt(); int []arr=new int[n]; for(int i=0;i<n;i++) arr[i]=input.nextInt(); k--; for(int i=k+1;i<n;i++){ if(arr[k]!=arr[i]){ System.out.print(-1); System.exit(0); } } int c=-1; for(int i=0;i<k;i++){ if(arr[i]!=arr[k]){ c=i; } } System.out.print(c+1); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
f75e273900e0b5616604b4047c2938c3
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int k=input.nextInt(); ArrayList<Integer>arr=new ArrayList<Integer>(); for(int i=0;i<n;i++) arr.add(input.nextInt()); k--; int elm=arr.get(k); for(int i=k+1;i<n;i++){ if(elm!=arr.get(i)){ System.out.print(-1); System.exit(0); } } int c=-1; for(int i=0;i<k;i++){ if(arr.get(i)!=elm){ c=i; } } System.out.print(c+1); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
a3c4579d6bd44820d0dc1234081418b3
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; import java.util.*; import java.util.Arrays; import java.lang.*; public class Amr { public static void main(String[] args) { Scanner input= new Scanner(System.in); int k,res,m; k=input.nextInt(); m=input.nextInt(); int c[]=new int[k]; res=k; for(int i=0; i<k ;i++) c[i]=input.nextInt(); //System.out.printf("%d\n",c.length); for(int i=c.length-1; i>0; i--) if(c[i]==c[i-1])res=i; else break; if(m<res)System.out.printf("%d",-1); else if (res==1)System.out.printf("%d",0); else System.out.printf("%d",res-1); } }//blackmailer :D
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
f89670bab56898faedfc01b694af4b2c
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; import java.util.*; import java.util.Arrays; import java.lang.*; public class Amr { public static void main(String[] args) { Scanner input= new Scanner(System.in); int k,res,m; k=input.nextInt(); m=input.nextInt(); int c[]=new int[k]; res=k; for(int i=0; i<k ;i++) c[i]=input.nextInt(); //System.out.printf("%d\n",c.length); for(int i=c.length-1; i>0; i--) if(c[i]==c[i-1])res=i; else break; if(m<res)System.out.printf("%d",-1); else if (res==1)System.out.printf("%d",0); else System.out.printf("%d",res-1); } }//blackmailer
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
29d304b632c6be846eb80a516a3c6583
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class ShooshunsAndSequence { public static void main(String []args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(new OutputStreamWriter(System.out)); StringTokenizer st=new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); int k=Integer.parseInt(st.nextToken())-1; int []secuencia=new int [n]; st=new StringTokenizer(br.readLine()); for(int i=0;i<n;i++)secuencia[i]=Integer.parseInt(st.nextToken()); int v=secuencia[k]; boolean posible=true; for(int i=k;i<n;i++){ if(v!=secuencia[i]){ posible=false; break; } } if(posible) { int i=n-1; for(;i>-1;i--) if(v!=secuencia[i])break; i++; pw.println(i); } else pw.println(-1); pw.flush(); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
354fb0888a186a7119bf1e70479b8cbb
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } } class Task { public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int tmp = a[k-1]; for (int i = k; i < n; i++) { if (a[i] != tmp) { System.out.println(-1); return; } } int res = k - 1; for(int i = k - 1;i>=0;i--) { if(i==0 && a[i] == tmp) { res = 0; break; } if(a[i] != tmp) { res = i + 1; break; } } System.out.println(res); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
864a704bcd9680be46f47b65435f1731
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(),m = input.nextInt(); int a[] = new int[n]; for(int i = 0 ; i < n;i++){ a[i] = input.nextInt(); } int i = 0; for(i = a.length - 1 ; i > 0;i--){ if(a[i-1] != a[i]){ break; } } if(i < m){ System.out.println(i); return; }System.out.println(-1); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
aa27be01a82dbbd1c7e5fe1c91c921cd
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class JavaApplication6 { public static void main(String[] args) { // TODO code application logic here Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt() - 1; int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int x = a[k], i = a.length - 1; while (i>=0&&a[i] == x) { i--; } i++; if (i > k) { System.out.println("-1"); } else { System.out.println(i); } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
d26d7a7fcf664e9c40cbbdc914fadda1
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Sunits789 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n=in.nextInt(); int k=in.nextInt(); int arr[]=new int[n]; in.getArray(arr); int ind=-1; int num=arr[n-1]; for(int i=n-1;i>=0;i--){ if(arr[i]!=num){ ind=i; i=-1; } } if(ind+1<k){ out.println(ind+1); } else{ out.println(-1); } } } class InputReader{ private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream){ reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next(){ while (tokenizer == null||!tokenizer.hasMoreTokens()){ try{ tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e){ throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public void getArray(int arr[]){ for(int i=0;i<arr.length;i++){ arr[i]=nextInt(); } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
4d3f80ed45fd70af49bb098272f5a38a
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.FileReader; import java.io.BufferedWriter; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.File; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author unnamed */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), k = in.nextInt(); int[] a = IOUtils.readIntArray(in, n); int h = a[k - 1]; boolean all = true; int ans = -1; for (int i = 0; i < k - 1; ++i) if (a[i] != h){ all = false; ans = i; } for (int i = k; i < n; ++i) if (a[i] != h) { out.print(-1); return; } if (all) out.print(0); else out.print(ans + 1); } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public InputReader(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void close() { writer.close(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.nextInt(); return array; } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
eafcd4552b42a2e9fdf8fbde486d2a75
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class A_222_Shooshuns_and_Sequence { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); boolean f = true; int a[] = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = sc.nextInt(); } for (int i = k; i <= n; i++) { if (a[i] != a[k]) { f = false; break; } } if (!f) { System.out.println(-1); return; } int count = 0; for (int i = k - 1; i >= 1; i--) { if (a[i] != a[k]) break; count++; } System.out.println(k - 1 - count); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
6dac03d4a1dea0207d100775ac9a2048
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class ShooshunsAndSequence { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n, k, counter = 0, counterz = 0, b = 0, c = 0; boolean flag = false; n = sc.nextInt(); k = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } if (k == 1) { for (int i = 0; i < n; i++) { if (a[k - 1] == a[i]) { b++; } if (i == n - 1) { b -= 1; if (b == n - 1) { System.out.println("0"); } else { System.out.println("-1"); } } } } else if (k == n) { for (int i = 0; i < n; i++) { if (a[k - 1] != a[i]) { counter++; } } System.out.println(counter); } else if (a[k - 1] != a[k] && a[k - 1] != a[k - 2]) { System.out.println("-1"); } else { for (int i = k; i < n; i++) { if (a[k - 1] == a[i]) { counterz++; } if (i == n - 1) { if (counterz == (n - k)) { for (int m = k - 1; m > 0; m--) { if (a[k - 1] != a[m - 1]) { c=m; break; } } System.out.println(c); return; } else { System.out.println("-1"); } } } } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
6991c5c1d73b801291f8fd253eedbe5e
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class test{ public static long[] arr = new long[200010]; public static void main(String[] args){ Scanner read = new Scanner(System.in); int i,j,k,n,h,t,step; long sum; n=read.nextInt(); k=read.nextInt(); h=1; t=n; sum=0; for (i=h;i<=t;i++){ arr[i] = read.nextInt(); sum+=arr[i]; } step=0; if (sum == arr[h]*(t-h+1)) if ((arr[h]==arr[t])&&(arr[h]==arr[(h+t)/2])) k=0; while ((h<=n)&&(k>0)){ step++; sum -= arr[h]; sum += arr[h+k-1]; t++; arr[t]=arr[h+k-1]; h++; if (sum == arr[h]*(t-h+1)) if ((arr[h]==arr[t])&&(arr[h]==arr[(h+t)/2])) k=0; } if (k>0) System.out.println("-1"); else System.out.println(step); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
2f6713ee896223010cffa1ad5a30d441
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.*; public class Main{ public static void main(String... args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); if (n==1){System.out.println(0);System.exit(0);} boolean same = true; int prev=sc.nextInt(); int sameFrom=1; for (int i=2; i<=n; i++){ int curr = sc.nextInt(); if (i>k && curr!=prev){same=false;break;} if (curr==prev){sameFrom++;} else {sameFrom=1;} prev = curr; } System.out.println(same?(n-sameFrom):-1); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
3984ffd8821ac9bbf7829c7e7b91adc2
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.*; public class JavaApplication198 { public static void main(String[] args) { Scanner sin = new Scanner(System.in); int n = sin.nextInt(), k = sin.nextInt(), arr[] = new int[n]; for(int i = 0; i < n; i++) arr[i] = sin.nextInt(); int ans = -1; for(int i = 0; i < n; i++) if(arr[i] != arr[k-1]) ans = i; if(ans > k-1) System.out.println("-1"); else System.out.println(ans+1); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
9e57b80b33f62aee3b24ed0b1abaadbf
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.IOException; import java.io.InputStream; public class A222 { public static void main(String[] args) throws IOException { InputReader reader = new InputReader(System.in); int N = reader.readInt(); int K = reader.readInt()-1; int[] A = new int[N]; for (int n=0; n<N; n++) { A[n] = reader.readInt(); } boolean ok = true; int value = A[K]; for (int n=K+1; n<N; n++) { if (A[n] != value) { ok = false; break; } } if (ok) { while (K > 0 && A[K] == A[K-1]) { K--; } System.out.println(K); } else { System.out.println("-1"); } } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final int readInt() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } boolean negative = false; if (c == '-') { negative = true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return negative ? -res : res; } public final long readLong() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } boolean negative = false; if (c == '-') { negative = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return negative ? -res : res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
83b9c3f0eaade082d5462e5c89479004
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class ShooshunsandSequence { static int arr[]; static int check(int indx, int len) { boolean check = true; int index = 0; for (int i = indx; i < len; i++) { if (arr[indx] != arr[i]) { index = -1; break; } } if (index != -1) { index = 0; for (int i = indx - 1; i >= 0; i--) { if (arr[indx] != arr[i]) { index = i+1; break; } } } return index; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int len = scan.nextInt(); int indx = scan.nextInt() - 1; arr = new int[len]; for (int i = 0; i < len; i++) { arr[i] = scan.nextInt(); } System.out.println(check(indx, len)); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
fb12ba04f66ac0f2903d0562f9dde416
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.*; import java.util.*; public class cf{ public static void main(String argc[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(), k = sc.nextInt(), a[]; a = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); boolean tt = true; for (int i = k - 1; i < n - 1; i++) if (a[i] != a[i + 1]) tt = false; if (tt){ int ans = k - 1; for (int i = k - 1; i > 0; i--) if (a[i] == a[i - 1]) ans--; else break; System.out.print(ans); } else System.out.print(-1); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
8632b2089e9f4e7911c32e35002309b6
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.*; public class ShooshunsAndSequence { public static void main(String[] Args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int[] vals = new int[n]; for(int j =0;j<n;j++) vals[j] = sc.nextInt(); boolean good = true; for(int j = k;j<n;j++) if(vals[j]!=vals[j-1]) good = false; if(!good){ System.out.println(-1); } else{ for(int j =k-2;j>=0&&good;j--){ if(vals[j]!=vals[j+1]){ System.out.println(j+1); good = false; } } if(good){ System.out.println(0); } } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
b9b3c5950b8a615c207cbac82417818b
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
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)); String y[] = in.readLine().split(" "); int n = Integer.parseInt(y[0]); int k = Integer.parseInt(y[1]); y = in.readLine().split(" "); boolean flag = true; for (int i = k - 1; i < n - 1; i++) { if (Integer.parseInt(y[i]) != Integer.parseInt(y[i + 1])) { flag = false; break; } } if (flag) { int counter = 0; for (int i = k-2; i > -1; i--) if (Integer.parseInt(y[i]) == Integer.parseInt(y[k-1])) counter++; else break; System.out.println(k - 1 - counter); } else System.out.println(-1); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
3b16714e023edeb92ee603751850e280
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int k = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } boolean ok = true; for (int i = k-1; i < n-1; i++) { if (a[i] != a[i+1]) { ok = false; break; } } if (ok) { int i; for (i = k-2; i > -1; i--) { if (a[i] != a[k-1])break; } //System.out.println("stop at index " + i); out.println(i+1); } else { out.println(-1); } out.flush(); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
f2ddb3566593054abff3e1024b6a0832
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.lang.Integer.*; import static java.lang.System.*; public class Main { static InputReader in; public static void main(String[] args) throws IOException{ File file = new File("input.txt"); if(file.exists())in = new InputReader(new FileInputStream(file)); else in = new InputReader(System.in); String line, toks[]; int n = in.nextInt(), k = in.nextInt(); int arr[] = new int[n]; for(int i=0; i<n; i++) arr[i] = in.nextInt(); boolean ok = true; for(int i=k; i<n && ok; i++) if(arr[i] != arr[i-1]) ok = false; if(!ok)out.println(-1); else { int acc = k-1; for(int i=k-2; i>=0; i--){ if(arr[i] != arr[k-1])break; acc--; } out.println(acc); } } static void out(Object ...o){ out.println(deepToString(o)); } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } int nextInt(){ return parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
44c9b140cef88950756c07549d28bd36
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author dudkamaster */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n,k; n = in.nextInt(); k = in.nextInt()-1; int a[] = new int[n]; for (int i=0; i<n; i++) a[i] = in.nextInt(); boolean ok = true; for (int i=k; i<n; i++){ ok = ok && (a[i] == a[k]); } if (ok){ int ans = -1; for (int i=0; i<k; i++) if (a[i]!=a[k]) ans = Math.max(ans,i); out.print(ans+1); }else{ out.print(-1); } } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
bb6ad23782e90d2b6761d357ff515c1d
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class ShooshunsAndSequence { public static void main(String[] args) { int m,n; Scanner sc=new Scanner(System.in); m=sc.nextInt(); n=sc.nextInt(); int count=0,counter=0; int [] no= new int [m]; for (int i=0;i<m;i++) no[i]=sc.nextInt(); for (int i=m-1;i>=0;i--) { if (no[i]==no[n-1]) { counter++; } else { count=1; break; } } if (count==1) { if (counter >= m - n) System.out.println(m-counter); else System.out.println("-1"); } else System.out.println(0); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
b510feceb3717afda8deb26c25120fc2
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.*; import java.io.*; public class Main{ static public void main(String args[]) { Scanner in = new Scanner(new BufferedInputStream(System.in)); int n = in.nextInt(), m = in.nextInt(), a[]; a = new int[n + 1]; a[0] = 0; for (int i = 1; i <= n; i++) a[i] = in.nextInt(); for (int i = m; i <= n; i++) if (a[i] != a[m]){ System.out.println(-1); System.exit(0); } for (int i = m - 1; i >= 0; i--) if (a[i] != a[m]){ System.out.println(i); System.exit(0); } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
7d67d0a87ef5bba5db66f25eea83186a
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; /** * * @author Colonelm0 */ public class Main { public static void main(String[] args) { Scanner inp = new Scanner(System.in) ; int n , k ; n = inp.nextInt() ; k = inp.nextInt() ; boolean poss =true ; int [] arr = new int[100002]; int first = 0 ; for(int i = 0 ;i < n ; i++){ arr[i] = inp.nextInt(); if(i == k-1) first = arr[i]; if(i > k-1) if(arr[i] != first) poss = false ; } int ans = 0 ; if(!poss) System.out.println("-1"); else{ for(int i = k-2 ; i >= 0 ; i--) if(arr[i] != first){ ans = i+1 ; break ; } System.out.println(ans) ; } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
baa029a235b7640e34eace1193452cee
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; /** * @author Son-Huy TRAN * */ public class P222A_ShooshunsAndSequence { private static int stepCount(int n, int k, int[] numbers) { for (int i = k + 1; i <= n; i++) { if (numbers[i] != numbers[k]) { return -1; } } int i = k - 1; while (i >= 0 && numbers[i] == numbers[k]) { i--; } return i; } /** * @param args */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int k = scanner.nextInt(); scanner.nextLine(); int[] numbers = new int[n + 1]; for (int i = 1; i <= n; i++) { numbers[i] = scanner.nextInt(); } scanner.close(); int result = stepCount(n, k, numbers); System.out.println(result); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
39a546c75597afb5f0369c0225a42348
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Solution { public static void main(String[] args) throws IOException { new Solution().run(); } StreamTokenizer in; Scanner ins; PrintWriter out; int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } ForGCD gcd(int a,int b) { ForGCD tmp = new ForGCD(); if(a == 0) { tmp.x = 0; tmp.y = 1; tmp.d = b; } else { ForGCD tmp1 = gcd(b%a, a); tmp.d = tmp1.d; tmp.y = tmp1.x; tmp.x = tmp1.y - tmp1.x*(b/a); } return tmp; } void run() throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); ins = new Scanner(System.in); out = new PrintWriter(System.out); try { if(System.getProperty("xDx")!=null) { in = new StreamTokenizer(new BufferedReader(new FileReader("input.txt"))); ins = new Scanner(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); } } catch(Exception e) { } int n = nextInt(); int k = nextInt(); k--; int[] A = new int[n]; for(int i = 0; i < n; i++){ A[i] = nextInt(); if(i>k && A[k]!=A[i]){ out.print(-1); out.close(); return; } } int answ = k; while(answ>=0 && A[answ] == A[k]) answ--; out.print(answ+1); out.close(); } class ForGCD { int x,y,d; } class Team implements Comparable { public int p,t; public int compareTo(Object obj) { Team a = (Team) obj; if(p>a.p || p==a.p && t<a.t) return -1; else if(p==a.p && t==a.t) return 0; else return 1; } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
f698cd2de33ce219b08dc4f3d7958148
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author George Marcus */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int N = in.nextInt(); int K = in.nextInt(); int[] v = new int[N]; for(int i = 0; i < N; i++) v[i] = in.nextInt(); boolean ok = true; for(int i = K; i < N; i++) if(v[i] != v[K - 1]) ok = false; if(!ok) out.print(-1); else { int p; for(p = K - 1; p >= 0; p--) if(v[p] != v[K - 1]) break; out.print(p + 1); } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
00d4151bf2ffee23c3218d47289ff0e5
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Locale; import java.util.StringTokenizer; public class Problem implements Runnable { public static void main(String[] args) { new Problem().run(); } final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader br; PrintWriter out; StringTokenizer in; public String nextToken() throws Throwable { while (in == null || !in.hasMoreTokens()) in = new StringTokenizer(br.readLine()); return in.nextToken(); } public int nextInt() throws Throwable { return Integer.parseInt(nextToken()); } public long nextLong() throws Throwable { return Long.parseLong(nextToken()); } public double nextDouble() throws Throwable { return Double.parseDouble(nextToken()); } int solve() throws Throwable { int n = nextInt(); int k = nextInt() - 1; int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); for (int i = k + 1; i < n; i++) { if (a[i - 1] != a[i]) { out.print("-1"); return 0; } } while(k > 0 && a[k] == a[k - 1]) k--; out.print(k); return 0; } public void run() { try { long startTime = System.currentTimeMillis(); Locale.setDefault(Locale.US); if (ONLINE_JUDGE) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { br = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } int ret = solve(); br.close(); out.close(); long endTime = System.currentTimeMillis(); long freeMemory = Runtime.getRuntime().freeMemory(); long totalMemory = Runtime.getRuntime().totalMemory(); System.err.printf("Time = %.3f s\n", (endTime - startTime) / 1000.0); System.err.printf("Memory = %.3f MB\n", (totalMemory - freeMemory) / (float)(1 << 20)); if (ret != 0) System.exit(ret); } catch (Throwable t) { t.printStackTrace(ONLINE_JUDGE ? System.out : System.err); System.exit(-1); } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
ad1bfb0a242476cc7023729df114454c
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Locale; import java.util.StringTokenizer; public class Problem implements Runnable { public static void main(String[] args) { new Problem().run(); } final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) in = new StringTokenizer(br.readLine()); return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } void solve() throws IOException { int n = nextInt(); int k = nextInt() - 1; int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); for (int i = k + 1; i < n; i++) { if (a[i - 1] != a[i]) { out.print("-1"); return; } } while(k > 0 && a[k] == a[k - 1]) k--; out.print(k); } public void run() { try { long startTime = System.currentTimeMillis(); Locale.setDefault(Locale.US); if (!ONLINE_JUDGE) { br = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); solve(); } else { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); } out.close(); br.close(); long endTime = System.currentTimeMillis(); long freeMemory = Runtime.getRuntime().freeMemory(); long totalMemory = Runtime.getRuntime().totalMemory(); System.err.printf("Time = %.3f s\n", (endTime - startTime) / 1000.0); System.err.printf("Memory = %.3f MB\n", (totalMemory - freeMemory) / (float)(1 << 20)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
57356efeb6486669958ea2357e0fe16d
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class practice { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int [] arr = new int[n]; for(int i = 0; i<n; i++) arr[i] = sc.nextInt(); for(int i = k-1; i<n-1; i++) { if(arr[i] != arr[i+1]) { System.out.println("-1"); return; } } int t = k-1; for(int i = k-1; i>0; i--) { if(arr[i] == arr[i-1]) t = i-1; else { break; } } System.out.println(t); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 7
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
c3db4d9a25db94da954e01dae882a881
train_002.jsonl
1380295800
You are given a rooted tree with n vertices. In each leaf vertex there's a single integer — the number of apples in this vertex. The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf.A tree is balanced if for every vertex v of the tree all its subtrees, corresponding to the children of vertex v, are of equal weight. Count the minimum number of apples that you need to remove from the tree (specifically, from some of its leaves) in order to make the tree balanced. Notice that you can always achieve the goal by just removing all apples.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(in, out); out.close(); } } class TaskD { private int MAXN = (int) 1e5; private long values[] = new long[MAXN+5]; private List<Integer> graph[]; private long lcmTab[] = new long[MAXN+5]; private long valuesAvailable[] = new long[MAXN+5]; public void solve(InputReader in, OutputWriter out) { int n = in.nextInt(); initGraph(n); long sum = 0; for (int i = 0; i < n; i++) { values[i] = in.nextInt(); sum += values[i]; } for (int i = 0; i < n - 1; i++) { int from = in.nextInt() - 1; int to = in.nextInt() - 1; graph[from].add(to); graph[to].add(from); } dfs(0,-1); out.printLine(sum - valuesAvailable[0]); } private long gcd(long a, long b) { return (b==0) ? a : gcd(b,a%b); } private long lcm(long a, long b) { return (a / gcd(a,b)) * b; } private void dfs(int vertex, int parent) { long min = Long.MAX_VALUE; int count = 0; lcmTab[vertex] = 1; for(int neighbour : graph[vertex]) { if(neighbour != parent) { count++; dfs(neighbour, vertex); lcmTab[vertex] = lcm(lcmTab[vertex], lcmTab[neighbour]); min = Math.min(min, valuesAvailable[neighbour]); } } if(count == 0) { valuesAvailable[vertex] = values[vertex]; return; } valuesAvailable[vertex] = min; if(valuesAvailable[vertex] < lcmTab[vertex]) { valuesAvailable[vertex] = 0; lcmTab[vertex] = 1; } valuesAvailable[vertex] = (valuesAvailable[vertex] / lcmTab[vertex]) * lcmTab[vertex] * count; lcmTab[vertex] *= count; } @SuppressWarnings("unchecked") private void initGraph(int n) { graph = new List[n]; for (int i = 0; i < n; i++) { graph[i] = new ArrayList<>(); } } } 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 boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = reader.readLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } catch (IOException e) { throw new RuntimeException(e); } } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["6\n0 0 12 13 5 6\n1 2\n1 3\n1 4\n2 5\n2 6"]
2 seconds
["6"]
null
Java 8
standard input
[ "number theory", "dfs and similar", "trees" ]
db1c28e9ac6251353fbad8730f4705ea
The first line contains integer n (2 ≤ n ≤ 105), showing the number of vertices in the tree. The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 108), ai is the number of apples in the vertex number i. The number of apples in non-leaf vertices is guaranteed to be zero. Then follow n - 1 lines, describing the tree edges. Each line contains a pair of integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi) — the vertices connected by an edge. The vertices are indexed from 1 to n. Vertex 1 is the root.
2,100
Print a single integer — the minimum number of apples to remove in order to make the tree balanced. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the sin, cout streams cin, cout or the %I64d specifier.
standard output
PASSED
e7e3d7bd5c11902215ddb698144ce6f2
train_002.jsonl
1380295800
You are given a rooted tree with n vertices. In each leaf vertex there's a single integer — the number of apples in this vertex. The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf.A tree is balanced if for every vertex v of the tree all its subtrees, corresponding to the children of vertex v, are of equal weight. Count the minimum number of apples that you need to remove from the tree (specifically, from some of its leaves) in order to make the tree balanced. Notice that you can always achieve the goal by just removing all apples.
256 megabytes
import java.io.*; import java.util.*; public class CF349D { static final double MAX = 1e13; // 1e5 * 1e8 static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static class Vertex { int a; List<Vertex> list = new ArrayList<Vertex>(); long sum, unit; Vertex(int a) { this.a = a; } void dfs(Vertex u) { int c = list.size(); if (u != null) c--; if (c == 0) { sum = a; unit = 1; return; } sum = 0; unit = 1; for (Vertex v : list) { if (v == u) continue; v.dfs(this); if (v.sum == 0) return; long d = gcd(unit, v.unit); if ((double) unit * v.unit / d > MAX) return; unit *= v.unit / d; // least common multiple } long min = Long.MAX_VALUE; for (Vertex v : list) { if (v == u) continue; if (min > v.sum / unit) min = v.sum / unit; } sum = min * unit * c; unit *= c; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); Vertex[] aa = new Vertex[n]; StringTokenizer st = new StringTokenizer(br.readLine()); long sum = 0; for (int i = 0; i < n; i++) { int a = Integer.parseInt(st.nextToken()); aa[i] = new Vertex(a); sum += a; } for (int e = 0; e < n - 1; e++) { st = new StringTokenizer(br.readLine()); int i = Integer.parseInt(st.nextToken()) - 1; int j = Integer.parseInt(st.nextToken()) - 1; aa[i].list.add(aa[j]); aa[j].list.add(aa[i]); } aa[0].dfs(null); System.out.println(sum - aa[0].sum); } }
Java
["6\n0 0 12 13 5 6\n1 2\n1 3\n1 4\n2 5\n2 6"]
2 seconds
["6"]
null
Java 8
standard input
[ "number theory", "dfs and similar", "trees" ]
db1c28e9ac6251353fbad8730f4705ea
The first line contains integer n (2 ≤ n ≤ 105), showing the number of vertices in the tree. The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 108), ai is the number of apples in the vertex number i. The number of apples in non-leaf vertices is guaranteed to be zero. Then follow n - 1 lines, describing the tree edges. Each line contains a pair of integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi) — the vertices connected by an edge. The vertices are indexed from 1 to n. Vertex 1 is the root.
2,100
Print a single integer — the minimum number of apples to remove in order to make the tree balanced. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the sin, cout streams cin, cout or the %I64d specifier.
standard output
PASSED
ba789315d65644e02b5af315c7b058a1
train_002.jsonl
1380295800
You are given a rooted tree with n vertices. In each leaf vertex there's a single integer — the number of apples in this vertex. The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf.A tree is balanced if for every vertex v of the tree all its subtrees, corresponding to the children of vertex v, are of equal weight. Count the minimum number of apples that you need to remove from the tree (specifically, from some of its leaves) in order to make the tree balanced. Notice that you can always achieve the goal by just removing all apples.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Stack; public class D349 { public static void main(String[] args)throws Exception{ // TODO Auto-generated method stub new D349().run(); } int[] getArray(String line){ String[] array=line.split(" "); int[] res=new int[array.length]; for(int i=0;i<res.length;i++) res[i]=Integer.parseInt(array[i]); return res; } int n; List<Integer>[] graph; List<Integer>[] childrenGraph; int[] children; int[] color; long[] maxVal; long[] minChange; int[] apples; void run() throws Exception{ BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); n=Integer.parseInt(reader.readLine()); apples=getArray(reader.readLine()); graph=new List[n]; childrenGraph=new List[n]; children=new int[n]; color=new int[n]; maxVal=new long[n]; minChange=new long[n]; for(int i=0;i<n;graph[i++]=new LinkedList<Integer>()); for(int i=0;i<n;childrenGraph[i++]=new LinkedList<Integer>()); for(int i=0;i<n-1;i++){ String[] edge=reader.readLine().split(" "); int from=Integer.parseInt(edge[0])-1; int to=Integer.parseInt(edge[1])-1; graph[from].add(to); graph[to].add(from); } long maxVal=getMaxW(); long all=0; for(int i:apples) all+=i; System.out.println(all-maxVal); System.out.flush(); reader.close(); } long getMaxW(){ Stack<Integer> s=new Stack<Integer>(); s.push(0); color[0]=1; while(!s.isEmpty()){ int akt=s.pop(); //System.out.println(akt+" "+s.size()); if(color[akt]==1){ color[akt]=2; s.push(akt); for(int next:graph[akt]){ if(color[next]==0){ childrenGraph[akt].add(next); color[next]=1; s.push(next); } } children[akt]=childrenGraph[akt].size(); } else if(color[akt]==2){ color[akt]=3; if(children[akt]==0){//leaf Found minChange[akt]=1; maxVal[akt]=apples[akt]; if(maxVal[akt]==0) return 0; } else{ Iterator<Integer> it=childrenGraph[akt].iterator(); int nextChild=it.next(); long aktMinChange=minChange[nextChild]; long aktMax=maxVal[nextChild]; while(it.hasNext()){ //System.out.println("hier"); nextChild=it.next(); long ggt=ggT(aktMinChange, minChange[nextChild]); long newMinChange=aktMinChange/ggt*minChange[nextChild]; long newMaxVal=Math.min(aktMax/newMinChange*newMinChange, maxVal[nextChild]/newMinChange*newMinChange); aktMinChange=newMinChange; aktMax=newMaxVal; if(aktMax==0) return 0; } maxVal[akt]=aktMax*children[akt]; minChange[akt]=aktMinChange*children[akt]; //System.out.println(Arrays.toString(maxVal)); } } } // System.out.println("hier2"); return maxVal[0]; } long findMin(long start, long step, long over){ if(start>over) return 0; return start+(over-start)/step*step; } long ggT(long a, long b){ long big=Math.max(a,b); long small=Math.min(a,b); while(small!=0){ b=big%small; big=small; small=b; } return big; } }
Java
["6\n0 0 12 13 5 6\n1 2\n1 3\n1 4\n2 5\n2 6"]
2 seconds
["6"]
null
Java 6
standard input
[ "number theory", "dfs and similar", "trees" ]
db1c28e9ac6251353fbad8730f4705ea
The first line contains integer n (2 ≤ n ≤ 105), showing the number of vertices in the tree. The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 108), ai is the number of apples in the vertex number i. The number of apples in non-leaf vertices is guaranteed to be zero. Then follow n - 1 lines, describing the tree edges. Each line contains a pair of integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi) — the vertices connected by an edge. The vertices are indexed from 1 to n. Vertex 1 is the root.
2,100
Print a single integer — the minimum number of apples to remove in order to make the tree balanced. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the sin, cout streams cin, cout or the %I64d specifier.
standard output
PASSED
c506f3b2496345c2a27ddaa3eed7e62f
train_002.jsonl
1380295800
You are given a rooted tree with n vertices. In each leaf vertex there's a single integer — the number of apples in this vertex. The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf.A tree is balanced if for every vertex v of the tree all its subtrees, corresponding to the children of vertex v, are of equal weight. Count the minimum number of apples that you need to remove from the tree (specifically, from some of its leaves) in order to make the tree balanced. Notice that you can always achieve the goal by just removing all apples.
256 megabytes
import java.util.*; import java.io.*; public class b { static ArrayList<Integer>[] tree; static long[] data; static long mod = 1000000007; public static void main(String[] args) throws IOException { // Scanner input = new Scanner(new File("input.txt")); // PrintWriter out = new PrintWriter(new File("output.txt")); input.init(System.in); PrintWriter out = new PrintWriter((System.out)); int n = input.nextInt(); data = new long[n]; for(int i = 0; i<n; i++) data[i] = input.nextInt(); ArrayList<Integer>[] adj = new ArrayList[n]; for(int i = 0; i<n; i++) adj[i] = new ArrayList<Integer>(); for(int i = 0; i<n-1; i++) { int a = input.nextInt()-1, b = input.nextInt()-1; adj[a].add(b); adj[b].add(a); } int[] parent = new int[n]; Arrays.fill(parent, -1); tree = new ArrayList[n]; for(int i = 0; i<n; i++) tree[i] = new ArrayList<Integer>(); Queue<Integer> q = new LinkedList<Integer>(); parent[0] = -2; q.add(0); while(!q.isEmpty()) { int at = q.poll(); for(int e: adj[at]) { if(parent[e] == -1) { parent[e] = at; q.add(e); tree[at].add(e); } } } memo = new long[n][3]; for(int i = 0; i<n; i++) memo[i][0] = -1; long[] ans = go(0); System.out.println(ans[0]); out.close(); } static long[][] memo; static long[] go(int at) { if(tree[at].size()==0) return new long[]{0, data[at], 1}; if(memo[at][0] != -1) return memo[at]; long res = 0; ArrayList<Long> ans = new ArrayList<Long>(); long lcm = 1; for(int e: tree[at]) { long[] cur = go(e); res += cur[0]; ans.add(cur[1]); lcm = lcm(lcm, cur[2]); } long min = (long)1e15; for(long x: ans){ min = Math.min(min, x); } long num = lcm <= 0 ? 0 : lcm*(min/lcm); //System.out.println(num); for(long x: ans) res += x - num; //System.out.println(at+" "+res+" "+min*ans.size()+" "+lcm*ans.size()); return memo[at] = new long[]{res, num*ans.size(), lcm*ans.size()}; } static long pow(long x, long p) { if (p == 0) return 1; if ((p & 1) > 0) { return (x * pow(x, p - 1)) % mod; } long sqrt = pow(x, p / 2); return (sqrt * sqrt) % mod; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long lcm(long a, long b) { return a/gcd(a,b)*b; } static class input { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { // TODO add check for eof if necessary tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static String nextLine() throws IOException { return reader.readLine(); } } }
Java
["6\n0 0 12 13 5 6\n1 2\n1 3\n1 4\n2 5\n2 6"]
2 seconds
["6"]
null
Java 6
standard input
[ "number theory", "dfs and similar", "trees" ]
db1c28e9ac6251353fbad8730f4705ea
The first line contains integer n (2 ≤ n ≤ 105), showing the number of vertices in the tree. The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 108), ai is the number of apples in the vertex number i. The number of apples in non-leaf vertices is guaranteed to be zero. Then follow n - 1 lines, describing the tree edges. Each line contains a pair of integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi) — the vertices connected by an edge. The vertices are indexed from 1 to n. Vertex 1 is the root.
2,100
Print a single integer — the minimum number of apples to remove in order to make the tree balanced. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the sin, cout streams cin, cout or the %I64d specifier.
standard output
PASSED
418fa3f727d119b12be0012ae5707165
train_002.jsonl
1380295800
You are given a rooted tree with n vertices. In each leaf vertex there's a single integer — the number of apples in this vertex. The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf.A tree is balanced if for every vertex v of the tree all its subtrees, corresponding to the children of vertex v, are of equal weight. Count the minimum number of apples that you need to remove from the tree (specifically, from some of its leaves) in order to make the tree balanced. Notice that you can always achieve the goal by just removing all apples.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class D { private int n; private int[] w; private long wsum; private List<Integer>[] e; private long[] h; private int[] cnum; public static void main(String[] args) { D solver = new D(); solver.solve(); } private void solve() { Scanner sc = new Scanner(System.in); // sc = new Scanner("6\n" + // "0 0 12 13 5 6\n" + // "1 2\n" + // "1 3\n" + // "1 4\n" + // "2 5\n" + // "2 6\n"); n = sc.nextInt(); w = new int[n]; for (int i = 0; i < n; i++) { w[i] = sc.nextInt(); wsum += w[i]; } e = new ArrayList[n]; for (int i = 0; i < n; i++) { e[i] = new ArrayList<Integer>(); } for (int i = 0; i < n - 1; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; e[u].add(v); e[v].add(u); } cnum = new int[n]; for (int i = 0; i < n; i++) { int k = e[i].size(); cnum[i] = i == 0 ? k : k - 1; } h = new long[n]; for (int i = 0; i < n; i++) { h[i] = w[i] > 0 ? 1 : 0; } long lcm = bfs(0, -1); bfs2(0, -1, lcm); long left = 0; long right = wsum+1; while (left < right) { long mid = (left + right) / 2; boolean r = check(mid); if (!r) { right = mid; } else { left = mid + 1; } } // System.out.println(left); // System.out.println(right); // System.out.println(Arrays.toString(w)); // System.out.println(Arrays.toString(cnum)); // System.out.println(Arrays.toString(h)); long m = right - 1; long sum = 0; for (int i = 0; i < n; i++) { if (cnum[i] > 0) continue; sum += w[i] - h[i]*m; } System.out.println(sum); } private boolean check(long mid) { for (int i = 0; i < n; i++) { if (cnum[i] > 0) continue; if (w[i] < h[i]*mid) return false; } return true; } private void bfs2(int v, int p, long r) { h[v] = r; if (cnum[v] == 0) return; long r2 = r/cnum[v]; for (int u : e[v]) { if (u == p) continue; bfs2(u, v, r2); } } private long bfs(int v, int p) { long lcm = 1; for (int u : e[v]) { if (u == p) continue; long r = bfs(u, v); lcm = lcm(lcm, r); } if (cnum[v] == 0) return 1; return lcm * cnum[v]; } public static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } public static long gcd(long a, long b) { if (b == 0) return a; else return gcd(b, a % b); } }
Java
["6\n0 0 12 13 5 6\n1 2\n1 3\n1 4\n2 5\n2 6"]
2 seconds
["6"]
null
Java 6
standard input
[ "number theory", "dfs and similar", "trees" ]
db1c28e9ac6251353fbad8730f4705ea
The first line contains integer n (2 ≤ n ≤ 105), showing the number of vertices in the tree. The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 108), ai is the number of apples in the vertex number i. The number of apples in non-leaf vertices is guaranteed to be zero. Then follow n - 1 lines, describing the tree edges. Each line contains a pair of integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi) — the vertices connected by an edge. The vertices are indexed from 1 to n. Vertex 1 is the root.
2,100
Print a single integer — the minimum number of apples to remove in order to make the tree balanced. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the sin, cout streams cin, cout or the %I64d specifier.
standard output
PASSED
89813791c88007c5e7f03b310e7c5a03
train_002.jsonl
1585924500
Dreamoon likes strings. Today he created a game about strings:String $$$s_1, s_2, \ldots, s_n$$$ is beautiful if and only if for each $$$1 \le i &lt; n, s_i \ne s_{i+1}$$$.Initially, Dreamoon has a string $$$a$$$. In each step Dreamoon can choose a beautiful substring of $$$a$$$ and remove it. Then he should concatenate the remaining characters (in the same order).Dreamoon wants to use the smallest number of steps to make $$$a$$$ empty. Please help Dreamoon, and print any sequence of the smallest number of steps to make $$$a$$$ empty.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.IOException; import java.util.TreeSet; import java.util.ArrayList; import java.io.UncheckedIOException; import java.util.List; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); DDreamoonLikesStrings solver = new DDreamoonLikesStrings(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } static class DDreamoonLikesStrings { char[] s = new char[200001]; int charset = 'z' - 'a' + 1; Debug debug = new Debug(true); IntegerBIT bit; public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readString(s, 1); TreeSet<Node>[] sets = new TreeSet[charset]; for (int i = 0; i < charset; i++) { sets[i] = new TreeSet<>(); } Node[] nodes = new Node[n]; for (int i = 1; i < n; i++) { if (s[i] != s[i + 1]) { continue; } nodes[i] = new Node(); nodes[i].index = i; sets[s[i] - 'a'].add(nodes[i]); } Node pre = null; for (int i = 1; i < n; i++) { if (nodes[i] == null) { continue; } nodes[i].pre = pre; if (pre != null) { pre.next = nodes[i]; } pre = nodes[i]; } bit = new IntegerBIT(n); List<int[]> seq = new ArrayList<>(n); while (true) { int largestIndex = 0; TreeSet<Node> largest = sets[0]; for (int i = 0; i < charset; i++) { if (sets[i].size() > largest.size()) { largest = sets[i]; largestIndex = i; } } debug.debug("largestIndex", largestIndex); if (largest.size() == 0) { seq.add(new int[]{1, indexOf(n)}); break; } Node head = largest.first(); Node a = null; Node b = null; if (head.pre != null) { a = head.pre; b = head; } else { while (head.find().tail.next != null && s[head.index] == s[head.find().tail.next.index]) { head = head.find().tail.next; Node.merge(head.pre, head); } //only one color if (head.find().tail.next == null) { head = head.find().tail; int[] ans = new int[]{indexOf(head.index + 1), indexOf(n)}; seq.add(ans); head.find().tail = head.pre; if (head.pre != null) { head.pre.next = null; } largest.remove(head); bit.update(head.index + 1, length(ans)); continue; } else { a = head.find().tail; b = a.next; } } int[] ans = new int[]{indexOf(a.index + 1), indexOf(b.index)}; seq.add(ans); bit.update(a.index + 1, length(ans)); a.find().tail = a.pre; if (a.pre != null) { a.pre.next = b.next; } if (b.next != null) { b.next.pre = a.pre; } sets[s[a.index] - 'a'].remove(a); sets[s[b.index] - 'a'].remove(b); } out.println(seq.size()); for (int[] lr : seq) { out.append(lr[0]).append(' ').append(lr[1]).println(); } } public int length(int[] interval) { return interval[1] - interval[0] + 1; } public int indexOf(int i) { return i - bit.query(i); } } static class Debug { private boolean offline; private PrintStream out = System.err; public Debug(boolean enable) { offline = enable && System.getSecurityManager() == null; } public Debug debug(String name, int x) { if (offline) { debug(name, "" + x); } return this; } public Debug debug(String name, String x) { if (offline) { out.printf("%s=%s", name, x); out.println(); } return this; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(int c) { cache.append(c); return this; } public FastOutput println(int c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class IntegerBIT { private int[] data; private int n; public IntegerBIT(int n) { this.n = n; data = new int[n + 1]; } public int query(int i) { int sum = 0; for (; i > 0; i -= i & -i) { sum += data[i]; } return sum; } public void update(int i, int mod) { if (i <= 0) { return; } for (; i <= n; i += i & -i) { data[i] += mod; } } public String toString() { StringBuilder builder = new StringBuilder(); for (int i = 1; i <= n; i++) { builder.append(query(i) - query(i - 1)).append(' '); } return builder.toString(); } } static class Node implements Comparable<Node> { Node pre; Node next; int index; Node p = this; int rank; Node tail = this; Node find() { return p.p == p ? p : (p = p.find()); } static Node larger(Node a, Node b) { return a.index < b.index ? b : a; } static void merge(Node a, Node b) { a = a.find(); b = b.find(); if (a == b) { return; } if (a.rank == b.rank) { a.rank++; } if (a.rank > b.rank) { b.p = a; a.tail = larger(a.tail, b.tail); } else { a.p = b; b.tail = larger(a.tail, b.tail); } } public int compareTo(Node o) { return index - o.index; } public String toString() { return "" + index; } } static class FastInput { private final InputStream is; private StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private byte[] buf = new byte[1 << 20]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public String next() { return readString(); } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } public int readString(char[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } } }
Java
["4\naabbcc\naaabbb\naaa\nabacad"]
2 seconds
["3\n3 3\n2 4\n1 2\n3\n3 4\n2 3\n1 2\n3\n1 1\n1 1\n1 1\n1\n1 6"]
null
Java 8
standard input
[ "data structures", "constructive algorithms" ]
1cb409e072d38270a5d84afd86b599a6
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 200\,000$$$), denoting the number of test cases in the input. For each test case, there's one line with a non-empty string of lowercase Latin letters $$$a$$$. The total sum of lengths of strings in all test cases is at most $$$200\,000$$$.
3,100
For each test case, in the first line, you should print $$$m$$$: the smallest number of steps to make $$$a$$$ empty. Each of the following $$$m$$$ lines should contain two integers $$$l_i, r_i$$$ ($$$1 \leq l_i \leq r_i \leq |a|$$$), denoting, that the $$$i$$$-th step is removing the characters from index $$$l_i$$$ to $$$r_i$$$ in the current string. (indices are numbered starting from $$$1$$$). Note that after the deletion of the substring, indices of remaining characters may change, and $$$r_i$$$ should be at most the current length of $$$a$$$. If there are several possible solutions, you can print any.
standard output
PASSED
bb530b1ac03bb3e2e85951b1ce15c488
train_002.jsonl
1518861900
Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.
256 megabytes
import java.util.*; import java.lang.Math; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); int k = sc.nextInt(); long minmod=n; long d=0; long d1=0; long a[]=new long[k]; int in=0; long mod=0; for(int i=0;i<k;i++){ a[i]=sc.nextLong(); mod=n%a[i]; d=n/a[i]; if(d>=0&&mod<minmod){ minmod=mod; in=i+1; d1=d; } } if(n==0||in==0){ System.out.println((in+1)+" "+0); } else{ System.out.println(in); System.out.println(d1); } } }
Java
["19 3\n5 4 10", "28 3\n5 6 30"]
2 seconds
["2 4", "1 5"]
null
Java 11
standard input
[ "implementation" ]
8e36566b5e0c74730ea118e23b030778
The first line contains two integers N and K (0 ≤ N ≤ 1018, 1 ≤ K ≤ 105) — the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces. The second line contains K integers a1, a2, ..., aK (1 ≤ ai ≤ 1018 for all i) — the capacities of boxes.
1,000
Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input. If there are many correct answers, output any of them.
standard output
PASSED
563899c79cbe6f6a8bfba7e9f72fd08e
train_002.jsonl
1518861900
Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.
256 megabytes
/* package codechef; // 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 Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner scanner = new Scanner(System.in); long n = scanner.nextLong(); long k = scanner.nextLong(); // System.out.println("n -> "+n+" k->"+k); long maxRemainder = n; long boxNumber = 0; long boxName = 1; for(long i=1; i<=k; i++) { // System.out.println(i); long temp = scanner.nextLong(); if(temp<=n && n%temp < maxRemainder) { maxRemainder = n%temp; boxName = i; boxNumber=(long)Math.floor(n/temp); //System.out.println(maxRemainder +" " + boxName +" "+(long)Math.floor(n/temp)); } } scanner.close(); System.out.println(boxName +" " + boxNumber); } }
Java
["19 3\n5 4 10", "28 3\n5 6 30"]
2 seconds
["2 4", "1 5"]
null
Java 11
standard input
[ "implementation" ]
8e36566b5e0c74730ea118e23b030778
The first line contains two integers N and K (0 ≤ N ≤ 1018, 1 ≤ K ≤ 105) — the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces. The second line contains K integers a1, a2, ..., aK (1 ≤ ai ≤ 1018 for all i) — the capacities of boxes.
1,000
Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input. If there are many correct answers, output any of them.
standard output
PASSED
64cf57f7425268918a526e4e91f81728
train_002.jsonl
1518861900
Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.
256 megabytes
import java.util.*; public class CF939B { public static void main(String[] args) { Scanner s=new Scanner(System.in); long N=s.nextLong(); int k=s.nextInt(); long[] arr=new long[k]; for(int i=0;i<arr.length;i++){ arr[i]=s.nextLong(); } int idx=0; long min=Long.MAX_VALUE; long num=Long.MAX_VALUE; for(int i=0;i<arr.length;i++){ if(arr[i]<=N && N%arr[i]<min){ min=N%arr[i]; num=arr[i]; idx=i; } } long ans=N/num; idx=idx+1; System.out.println(idx+" "+ans); } }
Java
["19 3\n5 4 10", "28 3\n5 6 30"]
2 seconds
["2 4", "1 5"]
null
Java 11
standard input
[ "implementation" ]
8e36566b5e0c74730ea118e23b030778
The first line contains two integers N and K (0 ≤ N ≤ 1018, 1 ≤ K ≤ 105) — the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces. The second line contains K integers a1, a2, ..., aK (1 ≤ ai ≤ 1018 for all i) — the capacities of boxes.
1,000
Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input. If there are many correct answers, output any of them.
standard output
PASSED
c57b7cb35e138406f450b4dad9e5cd6d
train_002.jsonl
1518861900
Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.
256 megabytes
import java.io.*; import java.util.*; public class hamster { public static void main(String[] args) throws IOException { //BufferedReader br = new BufferedReader(new FileReader("sn")); //PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("shuffle.out"))); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); long N = Long.parseLong(st.nextToken()); int K = Integer.parseInt(st.nextToken()); StringTokenizer st2 = new StringTokenizer(br.readLine()); long minremainder = (long) Math.pow(10, 18); long remainder = 0; int lowbox = 0; long[] boxes = new long[K]; for (int i=0;i<K;i++) { boxes[i] = Long.parseLong(st2.nextToken()); } for (int i=0;i<K;i++) { remainder = N%(boxes[i]); if (remainder<minremainder) { minremainder = remainder; lowbox = i; } } System.out.print(lowbox+1 + " "); System.out.print((N - N%(boxes[lowbox]))/(boxes[lowbox])); } }
Java
["19 3\n5 4 10", "28 3\n5 6 30"]
2 seconds
["2 4", "1 5"]
null
Java 11
standard input
[ "implementation" ]
8e36566b5e0c74730ea118e23b030778
The first line contains two integers N and K (0 ≤ N ≤ 1018, 1 ≤ K ≤ 105) — the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces. The second line contains K integers a1, a2, ..., aK (1 ≤ ai ≤ 1018 for all i) — the capacities of boxes.
1,000
Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input. If there are many correct answers, output any of them.
standard output
PASSED
28eeee552140086161b866de78efa1f4
train_002.jsonl
1518861900
Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.
256 megabytes
import java.util.*; public class cf464div2B { public static void main(String[] args) { Scanner sc=new Scanner(System.in); long n=sc.nextLong(); long k=sc.nextLong(); long min=(long)Math.pow(10,19);long x=0;long y=0; for(long i=0;i<k;i++) {long a=sc.nextLong(); if(min>n%a) {min=n%a;x=i+1;y=n/a;}} System.out.println(x+" "+y); sc.close();} }
Java
["19 3\n5 4 10", "28 3\n5 6 30"]
2 seconds
["2 4", "1 5"]
null
Java 11
standard input
[ "implementation" ]
8e36566b5e0c74730ea118e23b030778
The first line contains two integers N and K (0 ≤ N ≤ 1018, 1 ≤ K ≤ 105) — the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces. The second line contains K integers a1, a2, ..., aK (1 ≤ ai ≤ 1018 for all i) — the capacities of boxes.
1,000
Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input. If there are many correct answers, output any of them.
standard output
PASSED
173d87bb259765488b8ad279bfaec0e4
train_002.jsonl
1518861900
Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.
256 megabytes
// practice with kaiboy import java.io.*; import java.util.*; public class CF939B extends PrintWriter { CF939B() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF939B o = new CF939B(); o.main(); o.flush(); } void main() { long n = sc.nextLong(); int k = sc.nextInt(); long a_ = n + 1; int i_ = 0; for (int i = 0; i < k; i++) { long a = sc.nextLong(); if (n % a_ > n % a) { a_ = a; i_ = i; } } println(i_ + 1 + " " + n / a_); } }
Java
["19 3\n5 4 10", "28 3\n5 6 30"]
2 seconds
["2 4", "1 5"]
null
Java 11
standard input
[ "implementation" ]
8e36566b5e0c74730ea118e23b030778
The first line contains two integers N and K (0 ≤ N ≤ 1018, 1 ≤ K ≤ 105) — the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces. The second line contains K integers a1, a2, ..., aK (1 ≤ ai ≤ 1018 for all i) — the capacities of boxes.
1,000
Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input. If there are many correct answers, output any of them.
standard output