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
26ba584a2b051158acfa476c0820fd63
train_004.jsonl
1586788500
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.awt.Point; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; public class Codeforces { public static void main(String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t-- > 0){ for(int i = 0; i < 9; i++){ String s = br.readLine(); String newS =s.replace('1', '2'); System.out.println(newS); } } } }
Java
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
2 seconds
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
null
Java 11
standard input
[ "constructive algorithms", "implementation" ]
0e21f1c48c8c0463b2ffa7275eddc633
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
1,300
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
standard output
PASSED
b5a7d0d22a4033df0fa67ac74ed6c632
train_004.jsonl
1586788500
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
256 megabytes
//package com.prituladima.codeforce.contest; import java.io.*; import java.util.*; import static java.lang.Integer.parseInt; import static java.util.Arrays.stream; import static java.util.stream.IntStream.range; /** * Don't confuse variables in inner cycles. Don't call variable like (i j k g). Delegate methods. * -Xmx64m maximum heap size allocation * Never hardcode MAXN. Always make plus one. * 90% errors is copy-paste, wrong indexes and TOO MUCH variables */ public class Main223538cbD { private static final int BITS = 31; private static final int MODULO = (int) 1e9 + 7; private static final int INF = (int) 1e7 + 7; private static final String yes = "YES", no = "NO"; private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private static final boolean MULTI_TEST = true; private int[] memo; private boolean[] used[]; private void solve() { int n = 9; while (n-- > 0) { println(nextToken().replace('9', '1')); } } private int minAns(int lev) { char[] tabs = new char[lev]; Arrays.fill(tabs, '\t'); debug(new StringBuilder().append(tabs).append(" ").append(lev)); return 0; } private void solveAll() { int t = MULTI_TEST ? nextInt() : 1; while (t-- > 0) { solve(); } } public static void main(String[] args) { new Main223538cbD().run(); } private BufferedReader reader; private PrintWriter writer; private StringTokenizer tokenizer; private void run() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))) { this.writer = writer; this.reader = reader; solveAll(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } /** * Base types: Strings, int, long, double */ private String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } private int nextInt() { return parseInt(nextToken()); } private long nextLong() { return Long.parseLong(nextToken()); } private double nextDouble() { return Double.parseDouble(nextToken()); } /** * Primitives 1D arrays: char, int, long, double */ private char[] nextCharArray() { return nextToken().toCharArray(); } private int[] nextIntArray(int size) { return stream(new int[size]).map(c -> nextInt()).toArray(); } private long[] nextLongArray(int size) { return stream(new long[size]).map(c -> nextLong()).toArray(); } private double[] nextDoubleArray(int size) { return stream(new double[size]).map(c -> nextDouble()).toArray(); } private String[] nextStringArray(int size) { return range(0, size).mapToObj(i -> nextToken()).toArray(String[]::new); } /** * Primitives 2D arrays: char, int, long, double */ private char[][] nextCharMatrix(int n) { return range(0, n).mapToObj(i -> nextToken().toCharArray()).toArray(char[][]::new); } private int[][] nextIntMatrix(final int n, final int m) { return range(0, n).mapToObj(i -> nextIntArray(m)).toArray(int[][]::new); } private long[][] nextLongMatrix(final int n, final int m) { return range(0, n).mapToObj(i -> nextLongArray(m)).toArray(long[][]::new); } private double[][] nextDoubleMatrix(final int n, final int m) { return range(0, n).mapToObj(i -> nextDoubleArray(m)).toArray(double[][]::new); } /** * Graphs */ private Map<Integer, Set<Integer>> buildGraph(int amountOfVertex) { Map<Integer, Set<Integer>> graph = new HashMap<>(); for (int from = 1; from <= amountOfVertex; from++) { graph.putIfAbsent(from, new HashSet<>()); } return graph; } /** * Output */ private void printf(String format, Object... args) { writer.printf(format, args); } private void print(Object o) { writer.print(o); } private void println() { writer.println(); } private void println(Object o) { writer.println(o); } private void flush() { writer.flush(); } /** * Utils */ private boolean isValidIndex(int ind, int n) { return 0 <= ind && ind < n; } private void printSeparator() { if (ONLINE_JUDGE) return; println("--------------Answer-----------------"); } private void debug(Object o) { if (ONLINE_JUDGE) return; println(o); } private void debug(int[] array) { if (ONLINE_JUDGE) return; for (int i = 0; i < array.length; i++) { print(array[i]); print(' '); } println(); } private void debug(int[][] matrix) { if (ONLINE_JUDGE) return; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { print(matrix[i][j]); print(' '); } println(); } } private void debug(char[][] matrix) { if (ONLINE_JUDGE) return; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { print(matrix[i][j]); print(' '); } println(); } } public static double maxn(double req, double... opt) { double max = req; for (double value : opt) max = Math.max(max, value); return max; } public static double minn(double req, double... opt) { double min = req; for (double value : opt) min = Math.min(min, value); return min; } public static double sumn(double... a) { return stream(a).sum(); } public static int maxn(int req, int... opt) { int max = req; for (int value : opt) max = Math.max(max, value); return max; } public static int minn(int req, int... opt) { int min = req; for (int value : opt) min = Math.min(min, value); return min; } public static int sumn(int... a) { return stream(a).sum(); } public static long maxn(long req, long... opt) { long max = req; for (long value : opt) max = Math.max(max, value); return max; } public static long minn(long req, long... opt) { long min = req; for (long value : opt) min = Math.min(min, value); return min; } public static long sumn(long... a) { return stream(a).sum(); } public static void safeSort(long[] array) { shuffle(array); Arrays.sort(array); } public static void shuffle(long[] array) { Random random = new Random(); for (int i = 0, j; i < array.length; i++) { j = i + random.nextInt(array.length - i); long buf = array[j]; array[j] = array[i]; array[i] = buf; } } public static void safeSort(int[] array) { shuffle(array); Arrays.sort(array); } public static void shuffle(int[] array) { Random random = new Random(); for (int i = 0, j; i < array.length; i++) { j = i + random.nextInt(array.length - i); int buf = array[j]; array[j] = array[i]; array[i] = buf; } } public static Map<Double, Integer> multiSet(double[] arr) { Map<Double, Integer> multiSet = new HashMap<>(); for (int i = 0; i < arr.length; i++) multiSet.put(arr[i], multiSet.getOrDefault(arr[i], 0) + 1); return multiSet; } public static Map<Integer, Integer> multiSet(int[] arr) { Map<Integer, Integer> multiSet = new HashMap<>(); for (int i = 0; i < arr.length; i++) multiSet.put(arr[i], multiSet.getOrDefault(arr[i], 0) + 1); return multiSet; } public static Map<Long, Integer> multiSet(long[] arr) { Map<Long, Integer> multiSet = new HashMap<>(); for (int i = 0; i < arr.length; i++) multiSet.put(arr[i], multiSet.getOrDefault(arr[i], 0) + 1); return multiSet; } public static int[] calculatePrefixSum(int[] a) { int[] pref = new int[a.length]; pref[0] = a[0]; for (int i = 1; i < a.length; i++) pref[i] = pref[i - 1] + a[i]; return pref; } public static int[] calculateSuffixSum(int[] a) { int[] suff = new int[a.length]; suff[a.length - 1] = a[a.length - 1]; for (int i = a.length - 2; i >= 0; i--) suff[i] = suff[i + 1] + a[i]; return suff; } public static long[] calculatePrefixSum(long[] a) { long[] pref = new long[a.length]; pref[0] = a[0]; for (int i = 1; i < a.length; i++) pref[i] = pref[i - 1] + a[i]; return pref; } public static long[] calculateSuffixSum(long[] a) { long[] suff = new long[a.length]; suff[a.length - 1] = a[a.length - 1]; for (int i = a.length - 2; i >= 0; i--) suff[i] = suff[i + 1] + a[i]; return suff; } }
Java
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
2 seconds
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
null
Java 11
standard input
[ "constructive algorithms", "implementation" ]
0e21f1c48c8c0463b2ffa7275eddc633
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
1,300
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
standard output
PASSED
d95de13ec017e2ff53f01a66b45875a8
train_004.jsonl
1586788500
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
256 megabytes
//package com.prituladima.codeforce.contest; import java.io.*; import java.util.*; import static java.lang.Integer.parseInt; import static java.util.Arrays.stream; import static java.util.stream.IntStream.range; /** * Don't confuse variables in inner cycles. Don't call variable like (i j k g). Delegate methods. * -Xmx64m maximum heap size allocation * Never hardcode MAXN. Always make plus one. * 90% errors is copy-paste, wrong indexes and TOO MUCH variables */ public class Main223538cbD { private static final int BITS = 31; private static final int MODULO = (int) 1e9 + 7; private static final int INF = (int) 1e7 + 7; private static final String yes = "YES", no = "NO"; private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private static final boolean MULTI_TEST = true; private int[] memo; private boolean[] used[]; private void solve() { int n = 9; int[][] a = new int[n][n]; for (int i = 0; i < n; i++) { String token = nextToken(); for (int j = 0; j < n; j++) { a[i][j] = Character.getNumericValue(token.charAt(j)); } } int[] perm = {2, 3, 7, 1, 5, 6, 0, 4, 8}; for (int i = 0; i < 9; i++) { final int j = perm[i]; a[i][j]++; if (a[i][j] == 10) { a[i][j] = 1; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { print(a[i][j]); } println(); } } private int minAns(int lev) { char[] tabs = new char[lev]; Arrays.fill(tabs, '\t'); debug(new StringBuilder().append(tabs).append(" ").append(lev)); return 0; } private void solveAll() { int t = MULTI_TEST ? nextInt() : 1; while (t-- > 0) { solve(); } } public static void main(String[] args) { new Main223538cbD().run(); } private BufferedReader reader; private PrintWriter writer; private StringTokenizer tokenizer; private void run() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))) { this.writer = writer; this.reader = reader; solveAll(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } /** * Base types: Strings, int, long, double */ private String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } private int nextInt() { return parseInt(nextToken()); } private long nextLong() { return Long.parseLong(nextToken()); } private double nextDouble() { return Double.parseDouble(nextToken()); } /** * Primitives 1D arrays: char, int, long, double */ private char[] nextCharArray() { return nextToken().toCharArray(); } private int[] nextIntArray(int size) { return stream(new int[size]).map(c -> nextInt()).toArray(); } private long[] nextLongArray(int size) { return stream(new long[size]).map(c -> nextLong()).toArray(); } private double[] nextDoubleArray(int size) { return stream(new double[size]).map(c -> nextDouble()).toArray(); } private String[] nextStringArray(int size) { return range(0, size).mapToObj(i -> nextToken()).toArray(String[]::new); } /** * Primitives 2D arrays: char, int, long, double */ private char[][] nextCharMatrix(int n) { return range(0, n).mapToObj(i -> nextToken().toCharArray()).toArray(char[][]::new); } private int[][] nextIntMatrix(final int n, final int m) { return range(0, n).mapToObj(i -> nextIntArray(m)).toArray(int[][]::new); } private long[][] nextLongMatrix(final int n, final int m) { return range(0, n).mapToObj(i -> nextLongArray(m)).toArray(long[][]::new); } private double[][] nextDoubleMatrix(final int n, final int m) { return range(0, n).mapToObj(i -> nextDoubleArray(m)).toArray(double[][]::new); } /** * Graphs */ private Map<Integer, Set<Integer>> buildGraph(int amountOfVertex) { Map<Integer, Set<Integer>> graph = new HashMap<>(); for (int from = 1; from <= amountOfVertex; from++) { graph.putIfAbsent(from, new HashSet<>()); } return graph; } /** * Output */ private void printf(String format, Object... args) { writer.printf(format, args); } private void print(Object o) { writer.print(o); } private void println() { writer.println(); } private void println(Object o) { writer.println(o); } private void flush() { writer.flush(); } /** * Utils */ private boolean isValidIndex(int ind, int n) { return 0 <= ind && ind < n; } private void printSeparator() { if (ONLINE_JUDGE) return; println("--------------Answer-----------------"); } private void debug(Object o) { if (ONLINE_JUDGE) return; println(o); } private void debug(int[] array) { if (ONLINE_JUDGE) return; for (int i = 0; i < array.length; i++) { print(array[i]); print(' '); } println(); } private void debug(int[][] matrix) { if (ONLINE_JUDGE) return; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { print(matrix[i][j]); print(' '); } println(); } } private void debug(char[][] matrix) { if (ONLINE_JUDGE) return; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { print(matrix[i][j]); print(' '); } println(); } } public static double maxn(double req, double... opt) { double max = req; for (double value : opt) max = Math.max(max, value); return max; } public static double minn(double req, double... opt) { double min = req; for (double value : opt) min = Math.min(min, value); return min; } public static double sumn(double... a) { return stream(a).sum(); } public static int maxn(int req, int... opt) { int max = req; for (int value : opt) max = Math.max(max, value); return max; } public static int minn(int req, int... opt) { int min = req; for (int value : opt) min = Math.min(min, value); return min; } public static int sumn(int... a) { return stream(a).sum(); } public static long maxn(long req, long... opt) { long max = req; for (long value : opt) max = Math.max(max, value); return max; } public static long minn(long req, long... opt) { long min = req; for (long value : opt) min = Math.min(min, value); return min; } public static long sumn(long... a) { return stream(a).sum(); } public static void safeSort(long[] array) { shuffle(array); Arrays.sort(array); } public static void shuffle(long[] array) { Random random = new Random(); for (int i = 0, j; i < array.length; i++) { j = i + random.nextInt(array.length - i); long buf = array[j]; array[j] = array[i]; array[i] = buf; } } public static void safeSort(int[] array) { shuffle(array); Arrays.sort(array); } public static void shuffle(int[] array) { Random random = new Random(); for (int i = 0, j; i < array.length; i++) { j = i + random.nextInt(array.length - i); int buf = array[j]; array[j] = array[i]; array[i] = buf; } } public static Map<Double, Integer> multiSet(double[] arr) { Map<Double, Integer> multiSet = new HashMap<>(); for (int i = 0; i < arr.length; i++) multiSet.put(arr[i], multiSet.getOrDefault(arr[i], 0) + 1); return multiSet; } public static Map<Integer, Integer> multiSet(int[] arr) { Map<Integer, Integer> multiSet = new HashMap<>(); for (int i = 0; i < arr.length; i++) multiSet.put(arr[i], multiSet.getOrDefault(arr[i], 0) + 1); return multiSet; } public static Map<Long, Integer> multiSet(long[] arr) { Map<Long, Integer> multiSet = new HashMap<>(); for (int i = 0; i < arr.length; i++) multiSet.put(arr[i], multiSet.getOrDefault(arr[i], 0) + 1); return multiSet; } public static int[] calculatePrefixSum(int[] a) { int[] pref = new int[a.length]; pref[0] = a[0]; for (int i = 1; i < a.length; i++) pref[i] = pref[i - 1] + a[i]; return pref; } public static int[] calculateSuffixSum(int[] a) { int[] suff = new int[a.length]; suff[a.length - 1] = a[a.length - 1]; for (int i = a.length - 2; i >= 0; i--) suff[i] = suff[i + 1] + a[i]; return suff; } public static long[] calculatePrefixSum(long[] a) { long[] pref = new long[a.length]; pref[0] = a[0]; for (int i = 1; i < a.length; i++) pref[i] = pref[i - 1] + a[i]; return pref; } public static long[] calculateSuffixSum(long[] a) { long[] suff = new long[a.length]; suff[a.length - 1] = a[a.length - 1]; for (int i = a.length - 2; i >= 0; i--) suff[i] = suff[i + 1] + a[i]; return suff; } }
Java
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
2 seconds
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
null
Java 11
standard input
[ "constructive algorithms", "implementation" ]
0e21f1c48c8c0463b2ffa7275eddc633
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
1,300
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
standard output
PASSED
a556c93135b5c517a2de28f83f837bb3
train_004.jsonl
1586788500
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
256 megabytes
//package com.prituladima.codeforce.contest; import java.io.*; import java.util.*; import static java.lang.Integer.parseInt; import static java.util.Arrays.stream; import static java.util.stream.IntStream.range; /** * Don't confuse variables in inner cycles. Don't call variable like (i j k g). Delegate methods. * -Xmx64m maximum heap size allocation * Never hardcode MAXN. Always make plus one. * 90% errors is copy-paste, wrong indexes and TOO MUCH variables */ public class Main223538cbD { private static final int BITS = 31; private static final int MODULO = (int) 1e9 + 7; private static final int INF = (int) 1e7 + 7; private static final String yes = "YES", no = "NO"; private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private static final boolean MULTI_TEST = true; private int[] memo; private boolean[] used[]; private void solve() { int n = 9; int[][] a = new int[n][n]; for (int i = 0; i < n; i++) { String token = nextToken(); for (int j = 0; j < n; j++) { a[i][j] = Character.getNumericValue(token.charAt(j)); } } // int[] perm = {2, 3, 7, 1, 5, 6, 0, 4, 8}; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { // final int j = perm[i]; // a[i][j]++; if (a[i][j] == 9) { a[i][j] = 1; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { print(a[i][j]); } println(); } } private int minAns(int lev) { char[] tabs = new char[lev]; Arrays.fill(tabs, '\t'); debug(new StringBuilder().append(tabs).append(" ").append(lev)); return 0; } private void solveAll() { int t = MULTI_TEST ? nextInt() : 1; while (t-- > 0) { solve(); } } public static void main(String[] args) { new Main223538cbD().run(); } private BufferedReader reader; private PrintWriter writer; private StringTokenizer tokenizer; private void run() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))) { this.writer = writer; this.reader = reader; solveAll(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } /** * Base types: Strings, int, long, double */ private String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } private int nextInt() { return parseInt(nextToken()); } private long nextLong() { return Long.parseLong(nextToken()); } private double nextDouble() { return Double.parseDouble(nextToken()); } /** * Primitives 1D arrays: char, int, long, double */ private char[] nextCharArray() { return nextToken().toCharArray(); } private int[] nextIntArray(int size) { return stream(new int[size]).map(c -> nextInt()).toArray(); } private long[] nextLongArray(int size) { return stream(new long[size]).map(c -> nextLong()).toArray(); } private double[] nextDoubleArray(int size) { return stream(new double[size]).map(c -> nextDouble()).toArray(); } private String[] nextStringArray(int size) { return range(0, size).mapToObj(i -> nextToken()).toArray(String[]::new); } /** * Primitives 2D arrays: char, int, long, double */ private char[][] nextCharMatrix(int n) { return range(0, n).mapToObj(i -> nextToken().toCharArray()).toArray(char[][]::new); } private int[][] nextIntMatrix(final int n, final int m) { return range(0, n).mapToObj(i -> nextIntArray(m)).toArray(int[][]::new); } private long[][] nextLongMatrix(final int n, final int m) { return range(0, n).mapToObj(i -> nextLongArray(m)).toArray(long[][]::new); } private double[][] nextDoubleMatrix(final int n, final int m) { return range(0, n).mapToObj(i -> nextDoubleArray(m)).toArray(double[][]::new); } /** * Graphs */ private Map<Integer, Set<Integer>> buildGraph(int amountOfVertex) { Map<Integer, Set<Integer>> graph = new HashMap<>(); for (int from = 1; from <= amountOfVertex; from++) { graph.putIfAbsent(from, new HashSet<>()); } return graph; } /** * Output */ private void printf(String format, Object... args) { writer.printf(format, args); } private void print(Object o) { writer.print(o); } private void println() { writer.println(); } private void println(Object o) { writer.println(o); } private void flush() { writer.flush(); } /** * Utils */ private boolean isValidIndex(int ind, int n) { return 0 <= ind && ind < n; } private void printSeparator() { if (ONLINE_JUDGE) return; println("--------------Answer-----------------"); } private void debug(Object o) { if (ONLINE_JUDGE) return; println(o); } private void debug(int[] array) { if (ONLINE_JUDGE) return; for (int i = 0; i < array.length; i++) { print(array[i]); print(' '); } println(); } private void debug(int[][] matrix) { if (ONLINE_JUDGE) return; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { print(matrix[i][j]); print(' '); } println(); } } private void debug(char[][] matrix) { if (ONLINE_JUDGE) return; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { print(matrix[i][j]); print(' '); } println(); } } public static double maxn(double req, double... opt) { double max = req; for (double value : opt) max = Math.max(max, value); return max; } public static double minn(double req, double... opt) { double min = req; for (double value : opt) min = Math.min(min, value); return min; } public static double sumn(double... a) { return stream(a).sum(); } public static int maxn(int req, int... opt) { int max = req; for (int value : opt) max = Math.max(max, value); return max; } public static int minn(int req, int... opt) { int min = req; for (int value : opt) min = Math.min(min, value); return min; } public static int sumn(int... a) { return stream(a).sum(); } public static long maxn(long req, long... opt) { long max = req; for (long value : opt) max = Math.max(max, value); return max; } public static long minn(long req, long... opt) { long min = req; for (long value : opt) min = Math.min(min, value); return min; } public static long sumn(long... a) { return stream(a).sum(); } public static void safeSort(long[] array) { shuffle(array); Arrays.sort(array); } public static void shuffle(long[] array) { Random random = new Random(); for (int i = 0, j; i < array.length; i++) { j = i + random.nextInt(array.length - i); long buf = array[j]; array[j] = array[i]; array[i] = buf; } } public static void safeSort(int[] array) { shuffle(array); Arrays.sort(array); } public static void shuffle(int[] array) { Random random = new Random(); for (int i = 0, j; i < array.length; i++) { j = i + random.nextInt(array.length - i); int buf = array[j]; array[j] = array[i]; array[i] = buf; } } public static Map<Double, Integer> multiSet(double[] arr) { Map<Double, Integer> multiSet = new HashMap<>(); for (int i = 0; i < arr.length; i++) multiSet.put(arr[i], multiSet.getOrDefault(arr[i], 0) + 1); return multiSet; } public static Map<Integer, Integer> multiSet(int[] arr) { Map<Integer, Integer> multiSet = new HashMap<>(); for (int i = 0; i < arr.length; i++) multiSet.put(arr[i], multiSet.getOrDefault(arr[i], 0) + 1); return multiSet; } public static Map<Long, Integer> multiSet(long[] arr) { Map<Long, Integer> multiSet = new HashMap<>(); for (int i = 0; i < arr.length; i++) multiSet.put(arr[i], multiSet.getOrDefault(arr[i], 0) + 1); return multiSet; } public static int[] calculatePrefixSum(int[] a) { int[] pref = new int[a.length]; pref[0] = a[0]; for (int i = 1; i < a.length; i++) pref[i] = pref[i - 1] + a[i]; return pref; } public static int[] calculateSuffixSum(int[] a) { int[] suff = new int[a.length]; suff[a.length - 1] = a[a.length - 1]; for (int i = a.length - 2; i >= 0; i--) suff[i] = suff[i + 1] + a[i]; return suff; } public static long[] calculatePrefixSum(long[] a) { long[] pref = new long[a.length]; pref[0] = a[0]; for (int i = 1; i < a.length; i++) pref[i] = pref[i - 1] + a[i]; return pref; } public static long[] calculateSuffixSum(long[] a) { long[] suff = new long[a.length]; suff[a.length - 1] = a[a.length - 1]; for (int i = a.length - 2; i >= 0; i--) suff[i] = suff[i + 1] + a[i]; return suff; } }
Java
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
2 seconds
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
null
Java 11
standard input
[ "constructive algorithms", "implementation" ]
0e21f1c48c8c0463b2ffa7275eddc633
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
1,300
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
standard output
PASSED
becef14829f32d4c238eb99dc3be9fc7
train_004.jsonl
1586788500
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static void change(int i,int j,char[][]in) { if(in[i][j]=='1') { in[i][j]='2'; } else { in[i][j]='1'; } } public static void main(String[] args) throws Exception{ PrintWriter pw=new PrintWriter(System.out); MScanner sc = new MScanner(System.in); int tc=sc.nextInt(); while(tc-->0) { char[][]in=new char[9][9]; for(int i=0;i<9;i++)in[i]=sc.nextLine().toCharArray(); change(0, 0, in); change(1, 3, in); change(2, 6, in); change(3, 1, in); change(4, 4, in); change(5, 7, in); change(6, 2, in); change(7, 5, in); change(8, 8, in); for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { pw.print(in[i][j]); } pw.println(); } } pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void addX(int[]in,int x) { for(int i=0;i<in.length;i++)in[i]+=x; } static void addX(long[]in,int x) { for(int i=0;i<in.length;i++)in[i]+=x; } }
Java
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
2 seconds
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
null
Java 11
standard input
[ "constructive algorithms", "implementation" ]
0e21f1c48c8c0463b2ffa7275eddc633
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
1,300
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
standard output
PASSED
d56eef01e4dbd0361bae8f6fa0332a57
train_004.jsonl
1586788500
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) throws IOException { FastReader scn = new FastReader(); int t = scn.nextInt(); StringBuilder res = new StringBuilder(); while (t > 0) { char[][] arr = new char[9][9]; for (int i = 0; i < 9; i++) { String s = scn.next(); for (int j = 0; j < 9; j++) { arr[i][j] = s.charAt(j); } } for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { char ch = arr[i][j]; if(ch == '9'){ ch = '1'; } res.append(ch); } res.append('\n'); } t--; } System.out.print(res); } }
Java
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
2 seconds
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
null
Java 11
standard input
[ "constructive algorithms", "implementation" ]
0e21f1c48c8c0463b2ffa7275eddc633
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
1,300
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
standard output
PASSED
b090eededff25f2a357fe7031fdffeb2
train_004.jsonl
1586788500
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.math.*; public final class AntiSudoku { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- != 0) { char[][] ch = new char[9][9]; for(int i = 0; i < 9; i++) { String str = sc.next(); ch[i] = str.toCharArray(); } //System.out.println(); antiSudoku(ch); } } static void antiSudoku(char[][] a) { a[0][0] = a[0][1]; a[1][3] = a[1][4]; a[2][6] = a[2][7]; a[3][1] = a[3][2]; a[4][4] = a[4][5]; a[5][7] = a[5][8]; a[6][2] = a[6][1]; a[7][5] = a[7][4]; a[8][8] = a[8][7]; for (int i = 0; i < 9; i++) { System.out.println(a[i]); } } }
Java
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
2 seconds
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
null
Java 11
standard input
[ "constructive algorithms", "implementation" ]
0e21f1c48c8c0463b2ffa7275eddc633
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
1,300
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
standard output
PASSED
a892baf2ade72bc52354e6fe864d85dd
train_004.jsonl
1586788500
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; /** * Codeforces Problem 1335D */ public class Solution { public static void main(String args[]) { try (Scanner scanner = new Scanner(System.in);) { int t = scanner.nextInt(); for (int i = 0; i < t; i++) { String solution = solveNext(scanner); System.out.println(solution); } } System.exit(0); } public static String solveNext(Scanner scanner) { int[][] grid = new int[N][N]; for (int i = 0; i < 9; i++) { String row = scanner.next(); for (int j = 0; j < N; j++) { grid[i][j] = Character.getNumericValue(row.charAt(j)); } } return new Solution(grid).solve(); } static final int N = 9; final int[][] grid; public Solution(int[][] grid) { this.grid = grid; } public String solve() { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (this.grid[i][j] == 1) { this.grid[i][j] = 2; } } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < 9; i++) { if (i > 0) { sb.append("\n"); } for (int j = 0; j < 9; j++) { sb.append(this.grid[i][j]); } } return sb.toString(); } }
Java
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
2 seconds
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
null
Java 11
standard input
[ "constructive algorithms", "implementation" ]
0e21f1c48c8c0463b2ffa7275eddc633
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
1,300
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
standard output
PASSED
536e0f986dabbdcdb90ccbabd65c724e
train_004.jsonl
1586788500
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.InputMismatchException; import java.util.*; import java.io.*; public class Main{ public static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader sc = new InputReader(inputStream); PrintWriter w = new PrintWriter(outputStream); int t = sc.nextInt(); while(t-->0) { char[][] a=new char[9][9]; for (int i = 0; i < 9; i++) { a[i]=sc.next().toCharArray(); } a[0][1] = a[0][0]; a[1][4] = a[1][3]; a[2][7] = a[2][6]; a[3][0] = a[3][1]; a[4][3] = a[4][4]; a[5][6] = a[5][7]; a[6][2] = a[6][1]; a[7][5] = a[7][4]; a[8][8] = a[8][7]; for (int i = 0; i < 9; i++) w.println(a[i]); } w.close(); } }
Java
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
2 seconds
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
null
Java 11
standard input
[ "constructive algorithms", "implementation" ]
0e21f1c48c8c0463b2ffa7275eddc633
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
1,300
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
standard output
PASSED
549d4b929b043abd82b25e15d52dccda
train_004.jsonl
1586788500
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which: Any number in this field is in range $$$[1; 9]$$$; each row contains at least two equal elements; each column contains at least two equal elements; each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; /** * @author Tran Anh Tai * @template for CP codes */ public class ProbA { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ int[] steps = new int[]{0, 3, 6, 1, 4, 7, 2, 5, 8}; public void solve(InputReader in, PrintWriter out) { int t = in.nextInt(); for (int test = 0; test < t; test++) { for (int i = 0; i < 9; i++) { String s = in.nextToken(); for (int j = 0; j < 9; j++) { if (j != steps[i]) { out.print(s.charAt(j)); } else { out.print((s.charAt(j) == '1') ? '2' : '1'); } } out.println(); } } } } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } } }
Java
["1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563"]
2 seconds
["154873396\n336592714\n729645835\n863725145\n979314628\n412958357\n631457992\n998236471\n247789563"]
null
Java 11
standard input
[ "constructive algorithms", "implementation" ]
0e21f1c48c8c0463b2ffa7275eddc633
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.
1,300
For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
standard output
PASSED
cd9cb15b275a2f8d96703cc586dbdf30
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
import static java.lang.Math.*; import static java.util.Arrays.*; import java.util.*; public class B { public Object solve () { int N = sc.nextInt(); long [] A = sc.nextLongs(); int M = sc.nextInt(); int [][] Q = new int [M][4]; for (int i : rep(M)) Q[i] = new int [] { i, sc.nextInt(), sc.nextInt(), -1 }; sort(Q, by(1, 2)); A = stream(A).map(x -> (-x)).toArray(); RMQ X = new RMQ(A); Fenwick Y = new Fenwick(N); PriorityQueue<int[]> Z = new PriorityQueue<>(by(1, 2)); int x = X.get(0, N); Z.add(new int [] { x, (int)A[x], 0, N }); int L = 0, m = 0; while (!Z.isEmpty()) { int [] z = Z.poll(); x = z[0]; ++L; Y.add(1, x); while (m < M && Q[m][1] == L) { int j = Q[m][2]; int p = Y.bs(j) + 1; Q[m][3] = -(int)A[p]; ++m; } int from = z[2], to = z[3]; if (from < x) { int y = X.get(from, x); Z.add(new int [] { y, (int)A[y], from, x }); } if (x+1 < to) { int y = X.get(x+1, to); Z.add(new int [] { y, (int)A[y], x+1, to }); } } sort(Q, by(0)); for (int [] q : Q) print(q[3]); return null; } private static final int CONTEST_TYPE = 1; private static void init () { } private static final long LINF = (long) 1e18 + 10; private static Comparator<int[]> by (int j, int ... J) { Comparator<int[]> res = (x, y) -> x[j] - y[j]; for (int i : J) res = res.thenComparing((x, y) -> x[i] - y[i]); return res; } private static int [] rep (int N) { return rep(0, N); } private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } private static <T> T [] sort(T [] A, Comparator<T> C) { Arrays.sort(A, C); return A; } private static class Fenwick { private final long [] X; private final long mod; public Fenwick (int N) { this(N, 0); } public Fenwick (int N, int mod) { X = new long [N]; this.mod = mod; } public void add (long x, int i) { ++i; assert i <= X.length; while (i <= X.length) { X[i-1] += x; if (mod > 0) X[i-1] = ((X[i-1] % mod) + mod) % mod; i += (i & (-i)); } } public int bs (long S) { int res = -1; for (int b = Integer.highestOneBit(X.length); b > 0; b >>= 1) if (res + b < X.length && X[res + b] < S) S -= X[res += b]; return res; } } private static class RMQ { private final RMQ L, R; private final int from, to, m; private int F; private long X = LINF; public RMQ (long [] A) { this(A, 0, A.length); } public int get (int from, int to) { return getNode (from, to).F; } private RMQ getNode (int from, int to) { assert(from >= this.from && to <= this.to && from < to); if (from == this.from && to == this.to) return this; RMQ r = null, s = null; if (from < m) r = L.getNode(from, min(to, m)); if (m < to) s = R.getNode(max(from, m), to); if (r == null) return s; else if (s == null) return r; else if (r.X <= s.X) return r; else return s; } private RMQ (long [] A, int from, int to) { assert(from < to); this.from = from; this.to = to; m = (from + to) / 2; for (int i = from; i < to; ++i) if (A[i] < X) X = A[F = i]; if (m > from) { L = new RMQ(A, from, m); R = new RMQ(A, m, to); } else L = R = null; } } //////////////////////////////////////////////////////////////////////////////////// OFF private static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static Object print (Object o, Object ... A) { IOUtils.print(o, A); return null; } private static class IOUtils { public static class MyScanner { public String next () { newLine(); return line[index++]; } public int nextInt () { return Integer.parseInt(next()); } public String nextLine () { line = null; return readLine(); } public String [] nextStrings () { return split(nextLine()); } public long[] nextLongs () { return nextStream().mapToLong(Long::parseLong).toArray(); } ////////////////////////////////////////////// private boolean eol () { return index == line.length; } private String readLine () { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final java.io.BufferedReader r; private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); } private MyScanner (java.io.BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine () { if (line == null || eol()) { line = split(readLine()); index = 0; } } private java.util.stream.Stream<String> nextStream () { return java.util.Arrays.stream(nextStrings()); } private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim (String delim, Object o, Object ... A) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : A) append(b, p, delim); return b.substring(delim.length()); } ////////////////////////////////////////////////////////////////////////////////// private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########"); private static void start () { if (t == 0) t = millis(); } private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) f.accept(java.lang.reflect.Array.get(o, i)); } else if (o instanceof Iterable<?>) ((Iterable<?>)o).forEach(f::accept); else g.accept(o instanceof Double ? formatter.format(o) : o); } private static void append (final StringBuilder b, Object o, final String delim) { append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o); } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void print (Object o, Object ... A) { String res = build(o, A); if (DEBUG == 2) err(res, '(', time(), ')'); pw.println(res); if (DEBUG == 1) { pw.flush(); System.out.flush(); } } private static void err (Object o, Object ... A) { System.err.println(build(o, A)); } private static int DEBUG; private static void exit () { String end = "------------------" + System.lineSeparator() + time(); switch(DEBUG) { case 1: print(end); break; case 2: err(end); break; } IOUtils.pw.close(); System.out.flush(); System.exit(0); } private static long t; private static long millis () { return System.currentTimeMillis(); } private static String time () { return "Time: " + (millis() - t) / 1000.0; } private static void run (int N) { try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); } catch (Throwable t) {} for (int n = 1; n <= N; ++n) { Object res = new B().solve(); if (res != null) { @SuppressWarnings("all") Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res; print(o); } } exit(); } } //////////////////////////////////////////////////////////////////////////////////// public static void main (String[] args) { init(); @SuppressWarnings("all") int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt(); IOUtils.run(N); } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
2c87f101cd149ec8395604c626c8b76b
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
import static java.lang.Math.*; import java.util.*; public class B { public Object solve () { int N = sc.nextInt(); A = sc.nextInts(); int M = sc.nextInt(); int [][] Q = new int [M][4]; for (int i : rep(M)) Q[i] = new int [] { i, sc.nextInt(), sc.nextInt(), -1 }; sort(Q, by(1, 2)); MaxNode X = new MaxNode(0, N); for (int i : rep(N)) X.set(i, A[i]); PickNode Y = new PickNode(0, N); PriorityQueue<int[]> Z = new PriorityQueue<>(by(1, 2)); int x = X.get(0, N); Z.add(new int [] { x, -A[x], 0, N }); int L = 0, m = 0; while (!Z.isEmpty()) { int [] z = Z.poll(); x = z[0]; ++L; Y.set(x); while (m < M && Q[m][1] == L) { int j = Q[m][2]; int p = Y.get(j); Q[m][3] = A[p]; ++m; } int from = z[2], to = z[3]; if (from < x) { int y = X.get(from, x); Z.add(new int [] { y, -A[y], from, x }); } if (x+1 < to) { int y = X.get(x+1, to); Z.add(new int [] { y, -A[y], x+1, to }); } } sort(Q, by(0)); for (int [] q : Q) print(q[3]); return null; } int [] A; private static final int CONTEST_TYPE = 1; private static void init () { } private static Comparator<int[]> by (int j, int ... J) { Comparator<int[]> res = (x, y) -> x[j] - y[j]; for (int i : J) res = res.thenComparing((x, y) -> x[i] - y[i]); return res; } private static int [] rep (int N) { return rep(0, N); } private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } private static <T> T [] sort(T [] A, Comparator<T> C) { Arrays.sort(A, C); return A; } private class MaxNode { private final MaxNode L, R; private final int from, to, m; private long X = 0; public int get () { return get(from, to); } public int get (int from, int to) { assert(from >= this.from && to <= this.to && from < to); if (from == this.from && to == this.to) { if (from + 1 == to) return from; else if (L.X == X) return L.get(); else return R.get(); } else { int i = -1, j = -1; if (from < m) i = L.get(from, min(to, m)); if (to > m) j = R.get(max(from, m), to); if (i == -1) return j; else if (j == -1) return i; else if (A[i] >= A[j]) return i; else return j; } } private void set (int i, long X) { assert(from <= i && i < to); this.X = max(this.X, X); if (i < m) L.set(i, X); if (i >= m && m > from) R.set(i, X); } private MaxNode (int from, int to) { assert(from < to); this.from = from; this.to = to; m = (from + to) / 2; if (m > from) { L = new MaxNode(from, m); R = new MaxNode(m, to); } else L = R = null; } } private class PickNode { private final PickNode L, R; private final int from, to, m; private int X = 0; public int get (int X) { assert(0 < X && X <= this.X); if (from + 1 == to) { assert X == this.X; return from; } else if (X <= L.X) return L.get(X); else return R.get(X - L.X); } private void set (int i) { assert(from <= i && i < to); ++X; if (i < m) L.set(i); if (i >= m && m > from) R.set(i); } private PickNode (int from, int to) { assert(from < to); this.from = from; this.to = to; m = (from + to) / 2; if (m > from) { L = new PickNode(from, m); R = new PickNode(m, to); } else L = R = null; } } //////////////////////////////////////////////////////////////////////////////////// OFF private static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static Object print (Object o, Object ... A) { IOUtils.print(o, A); return null; } private static class IOUtils { public static class MyScanner { public String next () { newLine(); return line[index++]; } public int nextInt () { return Integer.parseInt(next()); } public String nextLine () { line = null; return readLine(); } public String [] nextStrings () { return split(nextLine()); } public int[] nextInts () { return nextStream().mapToInt(Integer::parseInt).toArray(); } ////////////////////////////////////////////// private boolean eol () { return index == line.length; } private String readLine () { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final java.io.BufferedReader r; private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); } private MyScanner (java.io.BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine () { if (line == null || eol()) { line = split(readLine()); index = 0; } } private java.util.stream.Stream<String> nextStream () { return java.util.Arrays.stream(nextStrings()); } private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim (String delim, Object o, Object ... A) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : A) append(b, p, delim); return b.substring(delim.length()); } ////////////////////////////////////////////////////////////////////////////////// private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########"); private static void start () { if (t == 0) t = millis(); } private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) f.accept(java.lang.reflect.Array.get(o, i)); } else if (o instanceof Iterable<?>) ((Iterable<?>)o).forEach(f::accept); else g.accept(o instanceof Double ? formatter.format(o) : o); } private static void append (final StringBuilder b, Object o, final String delim) { append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o); } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void print (Object o, Object ... A) { String res = build(o, A); if (DEBUG == 2) err(res, '(', time(), ')'); pw.println(res); if (DEBUG == 1) { pw.flush(); System.out.flush(); } } private static void err (Object o, Object ... A) { System.err.println(build(o, A)); } private static int DEBUG; private static void exit () { String end = "------------------" + System.lineSeparator() + time(); switch(DEBUG) { case 1: print(end); break; case 2: err(end); break; } IOUtils.pw.close(); System.out.flush(); System.exit(0); } private static long t; private static long millis () { return System.currentTimeMillis(); } private static String time () { return "Time: " + (millis() - t) / 1000.0; } private static void run (int N) { try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); } catch (Throwable t) {} for (int n = 1; n <= N; ++n) { Object res = new B().solve(); if (res != null) { @SuppressWarnings("all") Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res; print(o); } } exit(); } } //////////////////////////////////////////////////////////////////////////////////// public static void main (String[] args) { init(); @SuppressWarnings("all") int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt(); IOUtils.run(N); } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
0e51b5738508f8ff860f693684b79122
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
import static java.util.Collections.*; import java.util.*; public class B { public Object solve () { int N = sc.nextInt(); int [] A = sc.nextInts(); int [][] B = new int [N][2]; for (int i : rep(N)) B[i] = new int [] { i, A[i] }; int M = sc.nextInt(); int [][] Q = new int [M][4]; for (int i : rep(M)) Q[i] = new int [] { i, sc.nextInt(), sc.nextInt(), 0 }; sort(B, reverseOrder(by(1)).thenComparing(by(0))); sort(Q, by(1, 2)); OST S = new OST(N); int m = 0; for (int i : rep(N)) { S.add(B[i][0]); while (m < M && Q[m][1] == i+1) { int j = Q[m][2], y = S.select(j); Q[m++][3] = A[y]; } } sort(Q, by(0)); for (int [] q : Q) print(q[3]); return null; } private static final int CONTEST_TYPE = 1; private static void init () { } private static Comparator<int[]> by (int j, int ... J) { Comparator<int[]> res = (x, y) -> x[j] - y[j]; for (int i : J) res = res.thenComparing((x, y) -> x[i] - y[i]); return res; } private static int [] rep (int N) { return rep(0, N); } private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } private static <T> T [] sort(T [] A, Comparator<T> C) { Arrays.sort(A, C); return A; } private static class Fenwick { private final long [] X; private final long mod; public Fenwick (int N) { this(N, 0); } public Fenwick (int N, int mod) { X = new long [N]; this.mod = mod; } public void add (long x, int i) { ++i; assert i <= X.length; while (i <= X.length) { X[i-1] += x; if (mod > 0) X[i-1] = ((X[i-1] % mod) + mod) % mod; i += (i & (-i)); } } public int bs (long S) { int res = -1; for (int b = Integer.highestOneBit(X.length); b > 0; b >>= 1) if (res + b < X.length && X[res + b] < S) S -= X[res += b]; return res; } public long get (int to) { assert to <= X.length; long res = 0; for (; to > 0; to -= (to & (-to))) { res += X[to-1]; if (mod > 0) res = ((res % mod) + mod) % mod; } return res; } public long get (int from, int to) { assert from <= to; long res = get(to) - get(from); if (mod > 0) res = ((res % mod) + mod) % mod; return res; } } private static class OST { private final Fenwick F; public OST (int N) { F = new Fenwick(N); } public boolean add (int i) { return addOrRemove(i, 1, false); } public boolean contains (int i) { return F.get(i, i+1) == 1; } public int select (int j) { return F.bs(j) + 1; } private boolean addOrRemove (int i, int d, boolean x) { if (contains(i) != x) return false; F.add(d, i); return true; } } //////////////////////////////////////////////////////////////////////////////////// OFF private static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static Object print (Object o, Object ... A) { IOUtils.print(o, A); return null; } private static class IOUtils { public static class MyScanner { public String next () { newLine(); return line[index++]; } public int nextInt () { return Integer.parseInt(next()); } public String nextLine () { line = null; return readLine(); } public String [] nextStrings () { return split(nextLine()); } public int[] nextInts () { return nextStream().mapToInt(Integer::parseInt).toArray(); } ////////////////////////////////////////////// private boolean eol () { return index == line.length; } private String readLine () { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final java.io.BufferedReader r; private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); } private MyScanner (java.io.BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine () { if (line == null || eol()) { line = split(readLine()); index = 0; } } private java.util.stream.Stream<String> nextStream () { return java.util.Arrays.stream(nextStrings()); } private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim (String delim, Object o, Object ... A) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : A) append(b, p, delim); return b.substring(delim.length()); } ////////////////////////////////////////////////////////////////////////////////// private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########"); private static void start () { if (t == 0) t = millis(); } private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) f.accept(java.lang.reflect.Array.get(o, i)); } else if (o instanceof Iterable<?>) ((Iterable<?>)o).forEach(f::accept); else g.accept(o instanceof Double ? formatter.format(o) : o); } private static void append (final StringBuilder b, Object o, final String delim) { append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o); } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void print (Object o, Object ... A) { String res = build(o, A); if (DEBUG == 2) err(res, '(', time(), ')'); pw.println(res); if (DEBUG == 1) { pw.flush(); System.out.flush(); } } private static void err (Object o, Object ... A) { System.err.println(build(o, A)); } private static int DEBUG; private static void exit () { String end = "------------------" + System.lineSeparator() + time(); switch(DEBUG) { case 1: print(end); break; case 2: err(end); break; } IOUtils.pw.close(); System.out.flush(); System.exit(0); } private static long t; private static long millis () { return System.currentTimeMillis(); } private static String time () { return "Time: " + (millis() - t) / 1000.0; } private static void run (int N) { try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); } catch (Throwable t) {} for (int n = 1; n <= N; ++n) { Object res = new B().solve(); if (res != null) { @SuppressWarnings("all") Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res; print(o); } } exit(); } } //////////////////////////////////////////////////////////////////////////////////// public static void main (String[] args) { init(); @SuppressWarnings("all") int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt(); IOUtils.run(N); } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
dd861c7f579e08829f055ae9b08417b1
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Collection; import java.io.IOException; import java.util.Deque; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.ArrayDeque; 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); TaskB2 solver = new TaskB2(); solver.solve(1, in, out); out.close(); } } static class TaskB2 { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int[] a = new int[1 + n]; for (int i = 1; i <= n; i++) { a[i] = in.readInt(); } int m = in.readInt(); Query[] qs = new Query[m]; for (int i = 0; i < m; i++) { qs[i] = new Query(); qs[i].k = in.readInt(); qs[i].pos = in.readInt(); } Query[] sortedQs = qs.clone(); Arrays.sort(sortedQs, (x, y) -> x.k - y.k); Deque<Query> deque = new ArrayDeque<>(Arrays.asList(sortedQs)); Integer[] addIndex = new Integer[n]; for (int i = 0; i < n; i++) { addIndex[i] = i + 1; } Arrays.sort(addIndex, (x, y) -> a[x] == a[y] ? x - y : -(a[x] - a[y])); Segment seg = new Segment(1, n, a); for (int i = 1; i <= n; i++) { seg.update(addIndex[i - 1], addIndex[i - 1], 1, n); while (!deque.isEmpty() && deque.peekFirst().k == i) { Query q = deque.removeFirst(); q.ans = seg.query(q.pos, 1, n); } } for (Query q : qs) { out.println(q.ans); } } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; 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 int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class Query { int k; int pos; int ans; } static class Segment implements Cloneable { private Segment left; private Segment right; private int val; private int size; public void pushUp() { size = left.size + right.size; } public void pushDown() { } public Segment(int l, int r, int[] val) { if (l < r) { int m = (l + r) >> 1; left = new Segment(l, m, val); right = new Segment(m + 1, r, val); pushUp(); } else { this.val = val[l]; size = 0; } } private boolean covered(int ll, int rr, int l, int r) { return ll <= l && rr >= r; } private boolean noIntersection(int ll, int rr, int l, int r) { return ll > r || rr < l; } public void update(int ll, int rr, int l, int r) { if (noIntersection(ll, rr, l, r)) { return; } if (covered(ll, rr, l, r)) { size = 1; return; } pushDown(); int m = (l + r) >> 1; left.update(ll, rr, l, m); right.update(ll, rr, m + 1, r); pushUp(); } public int query(int k, int l, int r) { Segment trace = this; while (l < r) { int m = (l + r) >> 1; trace.pushDown(); if (trace.left.size >= k) { r = m; trace = trace.left; } else { l = m + 1; k -= trace.left.size; trace = trace.right; } } return trace.val; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c).append('\n'); 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(); } } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
577469902371c4d2193ad42e7838031b
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.ArrayDeque; import java.util.Comparator; import java.util.Collections; 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); TaskB1 solver = new TaskB1(); solver.solve(1, in, out); out.close(); } static class TaskB1 { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); ArrayList<Integer> arr = new ArrayList<>(); HashMap<Integer, ArrayDeque<Integer>> indexes = new HashMap<>(); FenwickTree prefSums = new FenwickTree(N); int[] saveArr = new int[N]; for (int i = 0; i < N; i++) { arr.add(in.nextInt()); saveArr[i] = arr.get(arr.size() - 1); indexes.putIfAbsent(arr.get(arr.size() - 1), new ArrayDeque<>()); indexes.get(arr.get(arr.size() - 1)).add(i); } Collections.sort(arr, Collections.reverseOrder()); ArrayList<Query> query = new ArrayList<>(); int M = in.nextInt(); for (int i = 0; i < M; i++) { query.add(new Query(i, in.nextInt(), in.nextInt())); } Collections.sort(query, new Comparator<Query>() { public int compare(Query query, Query t1) { return Integer.compare(query.k, t1.k); } }); int curK = 0; int pointer = 0; int[] res = new int[M]; for (int i = 0; i < M; i++) { Query next = query.get(i); for (int j = curK; j < next.k; j++) { while (indexes.get(arr.get(pointer)).isEmpty()) { pointer++; } prefSums.add(indexes.get(arr.get(pointer)).remove()); } curK = next.k; int low = 0; int high = N - 1; while (low < high) { int mid = (low + high) / 2; if (prefSums.sum(mid) >= next.pos) { high = mid; } else { low = mid + 1; } } res[next.i] = saveArr[low]; } for (int i : res) { out.println(i); } } class FenwickTree { int[] BIT; int N; FenwickTree(int N) { this.N = N; BIT = new int[N]; } void add(int id) { for (int i = id; i < N; i |= i + 1) { BIT[i]++; } } int sum(int r) { int res = 0; for (int i = r; i >= 0; i = (i & (i + 1)) - 1) { res += BIT[i]; } return res; } } class Query { int i; int k; int pos; Query(int i, int k, int pos) { this.i = i; this.k = k; this.pos = pos; } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
54f2f72a2822b7c1c48b84fa9592bfb5
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
/** * @author derrick20 * Key greedy idea: we want to optimally pick things, so let's try * to sort it. In fact, I can guarantee what the subsequence is, * finding it in O(N) time. I will pick the largest number, * then, go to the smaller numbers in order of index. * This is our comparator definition: sort by biggest val, * THEN smallest index * * However, the issue with this is the transition from one subsequence * to another. The only way to do this effectively would be to insert * into the sequence. However, what this amounts to is incrementing * a delta to ALL values that come after me! So, this naturally * suggests a range sum update, which is easy through a BIT. * It's nicely arranged such that the BIT is 10^5 in size, so it all * works out! * However, one subtlety is that we don't actually know the exact * position of the current ACTIVE elements. However, we can binary * search for that position, the first position where we can hit * a number with a certain "effective" index, as specified in the current * kth sized subsequence * * Key bugs: having the */ import java.io.*; import java.util.*; public class OptimalSubsequences { public static void main(String args[]) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); N = sc.nextInt(); // Make everything one-indexed, since BIT Pair[] seq = new Pair[N + 1]; // Put an impossibly early pair that'll stay at the beginning seq[0] = new Pair(-1, (int) 2e9); // This sequence is gonna be sorted, but we need to retrieve the original value // for a given index HashMap<Integer, Integer> original = new HashMap<>(); for (int i = 1; i <= N; i++) { int val = sc.nextInt(); seq[i] = new Pair(i, val); original.put(i, val); } int M = sc.nextInt(); Query[] queries = new Query[M]; int[] answers = new int[M]; for (int i = 0; i < M; i++) { int k = sc.nextInt(); int pos = sc.nextInt(); queries[i] = new Query(k, i, pos); } // The queries need to be sorted by the size of the subsequence // Arrays.sort(queries); Arrays.sort(seq); // System.out.println(Arrays.toString(queries)); // System.out.println(Arrays.toString(seq)); BIT bit = new BIT(new int[N + 1]); int k = 1; int ptr = 0; while (k <= N) { // the 0th arr pair won't be used! bit.add(seq[k].idx, 1); // System.out.println(bit + "\n"); // Scan through all the queries of a certain k value while (ptr < M && queries[ptr].k == k) { // Find the idxOfCurr inside the current subsequence int index = bit.findFirstOccurrence(queries[ptr].pos);// binarySearch(bit, queries[ptr].pos); // System.out.println((seq[index] + " " + original.get(index))); answers[queries[ptr].idx] = original.get(index); ptr++; } k++; } for (int ans : answers) { out.println(ans); } out.close(); } static int N; // Find the first INDEX within the BIT at which the "effective index" // stored by the bit at that position is value we inserted // 001112222333 // Say we want to find 1, then we keep querying the BIT at different // positions, so if it is >= 1 or not. // Reduced to: 0011 static int binarySearch(BIT bit, int val) { int lo = 1; int hi = N; while (lo < hi) { int mid = (hi - lo) / 2 + lo; // round DOWN if (bit.prefixSum(mid) >= val) { hi = mid; // We can guarantee this is fine } else { lo = mid + 1; // otherwise, we scrape up and eliminate it } } // Now they are equal return lo; } static class Query implements Comparable<Query> { int k, idx, pos; public Query(int myK, int index, int position) { k = myK; idx = index; pos = position; } public int compareTo(Query q2) { // All same size will be grouped together return k - q2.k; } public String toString() { return "(" + k + ", " + idx + ", " + pos + ")"; } } static class Pair implements Comparable<Pair> { int idx, val; public Pair(int index, int value) { idx = index; val = value; } public int compareTo(Pair p2) { return (p2.val - val) != 0 ? (p2.val - val) : idx - p2.idx; } public String toString() { return "(" + idx + ", " + val + ")"; } } static class BIT { int[] arr; int[] tree; // todo ***This ASSUMES THAT ARR IS 1-INDEXED ALREADY*** public BIT(int[] arr) { this.arr = arr; this.tree = new int[arr.length]; // copy arr values into tree for (int i = 1; i < arr.length; i++) { tree[i] = arr[i]; } constructBIT(arr, tree); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Index: "); for (int i = 1; i < tree.length; i++) { sb.append(i + " "); } sb.append("\nPrefix Sum: "); for (int i = 1; i < tree.length; i++) { sb.append(this.prefixSum(i) + " "); } return sb.toString(); } public int leastSignificantBit(int x) { // by negating it, all return x & (-x); } public void constructBIT(int[] arr, int[] tree) { // propagate information up to the pieces above it that would be responsible for it for (int i = 1; i < tree.length; i++) { int j = i + leastSignificantBit(i); // all of it's "parents" will need to possess its values, // but, we can be clever and only propagate to its immediate parent. // Since we are processing in order, that parent will propagate to its parent // eventually, so we are fine. Add methods are log(N) because we can't rely on our // parents eventually doing work for us. if (j < arr.length) { tree[j] += tree[i]; } } } public int findFirstOccurrence(int val) { int lastmask = Integer.highestOneBit(N); int bitmask = Integer.highestOneBit(N) >> 1; int index = lastmask; int sum = tree[index]; int ans = sum == val ? index : -1; while (bitmask != 0) { int next = (index | bitmask); if (next <= N && sum < val) { index = next; sum += tree[next]; } else if (sum >= val) { // try to go downwards sum -= tree[index]; index ^= lastmask; index |= bitmask; sum += tree[index]; /* 15 17 18 16 17 17 18 19 19 20 19 12 17 13 13 16 40 11 4 4 3 4 1 12 1 7 6 7 2 13 13 13 5 2 1 8 6 2 2 3 2 9 3 12 11 2 1 12 10 9 3 9 8 8 1 12 7 10 4 3 3 2 1 9 1 8 1 14 8 2 2 5 4 14 11 13 10 1 1 7 1 5 1 13 11 5 1 9 5 11 1 1 1 14 10 10 8 14 5 7 1 2 2 9 5 1 1 12 3 14 9 12 2 4 1 3 2 7 1 6 6 13 4 11 8 4 1 9 7 9 6 13 1 4 2 14 2 11 8 8 5 5 5 3 3 15 2 15 4 7 5 4 2 4 1 11 9 8 1 3 3 6 3 5 1 12 1 11 7 13 5 6 3 7 4 4 4 14 4 11 7 9 8 */ } if (sum == val) { ans = index; } lastmask = bitmask; bitmask >>= 1; } return ans; } public int valueAt(int i) { int value = tree[i]; // This overcounts by some amount of overlap due // to the responsibility (size given by LSB(i)) if (i > 0) { // If i == 0, bad! int end = i - leastSignificantBit(i); int j = i - 1; // Slide down j's chain of authority until we meet, // subtracting everything in the path. This // is slightly more efficient than calling sum twice! while (j != end) { value -= tree[j]; j -= leastSignificantBit(j); } } return value; } // return the sum public int sum(int i, int j) { return prefixSum(j) - prefixSum(i - 1); // exclude the values under i } // returns sum from 1 to i of the array // propagate downward! (decomposing the sum) public int prefixSum(int i) { int sum = 0; while (i > 0) { sum += tree[i]; i -= leastSignificantBit(i); } return sum; } // add a value of val at the ith value // propagate upward! public void add(int i, int val) { while (i < tree.length) { tree[i] += val; i += leastSignificantBit(i); } } // Change a value at an index (basically add the new value and subtract // the original value public void set(int i, int k) { int val = sum(i, i); add(i, k - val); } } static class FastScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double cnt = 1; BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt=1; boolean neg = false; if(c==NC)c=getChar(); for(;(c<'0' || c>'9'); c = getChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=getChar()) { res = (res<<3)+(res<<1)+c-'0'; cnt*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/cnt; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c>32) { res.append(c); c=getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c!='\n') { res.append(c); c=getChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=getChar(); if(c==NC)return false; else if(c>32)return true; } } } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
10cb138b35f021a836870871bbae0986
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
/** * @author derrick20 * Key greedy idea: we want to optimally pick things, so let's try * to sort it. In fact, I can guarantee what the subsequence is, * finding it in O(N) time. I will pick the largest number, * then, go to the smaller numbers in order of index. * This is our comparator definition: sort by biggest val, * THEN smallest index * * However, the issue with this is the transition from one subsequence * to another. The only way to do this effectively would be to insert * into the sequence. However, what this amounts to is incrementing * a delta to ALL values that come after me! So, this naturally * suggests a range sum update, which is easy through a BIT. * It's nicely arranged such that the BIT is 10^5 in size, so it all * works out! * However, one subtlety is that we don't actually know the exact * position of the current ACTIVE elements. However, we can binary * search for that position, the first position where we can hit * a number with a certain "effective" index, as specified in the current * kth sized subsequence * * Key bugs: having the */ import java.io.*; import java.util.*; public class OptimalSubsequences { public static void main(String args[]) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); N = sc.nextInt(); // Make everything one-indexed, since BIT Pair[] seq = new Pair[N + 1]; // Put an impossibly early pair that'll stay at the beginning seq[0] = new Pair(-1, (int) 2e9); // This sequence is gonna be sorted, but we need to retrieve the original value // for a given index HashMap<Integer, Integer> original = new HashMap<>(); for (int i = 1; i <= N; i++) { int val = sc.nextInt(); seq[i] = new Pair(i, val); original.put(i, val); } int M = sc.nextInt(); Query[] queries = new Query[M]; int[] answers = new int[M]; for (int i = 0; i < M; i++) { int k = sc.nextInt(); int pos = sc.nextInt(); queries[i] = new Query(k, i, pos); } // The queries need to be sorted by the size of the subsequence // Arrays.sort(queries); Arrays.sort(seq); // System.out.println(Arrays.toString(queries)); // System.out.println(Arrays.toString(seq)); BIT bit = new BIT(new int[N + 1]); int k = 1; int ptr = 0; while (k <= N) { // the 0th arr pair won't be used! bit.add(seq[k].idx, 1); // System.out.println(bit + "\n"); // Scan through all the queries of a certain k value while (ptr < M && queries[ptr].k == k) { // Find the idxOfCurr inside the current subsequence int index = binarySearch(bit, queries[ptr].pos); // System.out.println((seq[index] + " " + original.get(index))); answers[queries[ptr].idx] = original.get(index); ptr++; } k++; } for (int ans : answers) { out.println(ans); } out.close(); } static int N; // Find the first INDEX within the BIT at which the "effective index" // stored by the bit at that position is value we inserted // 001112222333 // Say we want to find 1, then we keep querying the BIT at different // positions, so if it is >= 1 or not. // Reduced to: 0011 static int binarySearch(BIT bit, int val) { int lo = 1; int hi = N; while (lo < hi) { int mid = (hi - lo) / 2 + lo; // round DOWN if (bit.prefixSum(mid) >= val) { hi = mid; // We can guarantee this is fine } else { lo = mid + 1; // otherwise, we scrape up and eliminate it } } // Now they are equal return lo; } static class Query implements Comparable<Query> { int k, idx, pos; public Query(int myK, int index, int position) { k = myK; idx = index; pos = position; } public int compareTo(Query q2) { // All same size will be grouped together return k - q2.k; } public String toString() { return "(" + k + ", " + idx + ", " + pos + ")"; } } static class Pair implements Comparable<Pair> { int idx, val; public Pair(int index, int value) { idx = index; val = value; } public int compareTo(Pair p2) { return (p2.val - val) != 0 ? (p2.val - val) : idx - p2.idx; } public String toString() { return "(" + idx + ", " + val + ")"; } } static class BIT { int[] arr; int[] tree; // todo ***This ASSUMES THAT ARR IS 1-INDEXED ALREADY*** public BIT(int[] arr) { this.arr = arr; this.tree = new int[arr.length]; // copy arr values into tree for (int i = 1; i < arr.length; i++) { tree[i] = arr[i]; } constructBIT(arr, tree); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Index: "); for (int i = 1; i < tree.length; i++) { sb.append(i + " "); } sb.append("\nPrefix Sum: "); for (int i = 1; i < tree.length; i++) { sb.append(this.prefixSum(i) + " "); } return sb.toString(); } public int leastSignificantBit(int x) { // by negating it, all return x & (-x); } public void constructBIT(int[] arr, int[] tree) { // propagate information up to the pieces above it that would be responsible for it for (int i = 1; i < tree.length; i++) { int j = i + leastSignificantBit(i); // all of it's "parents" will need to possess its values, // but, we can be clever and only propagate to its immediate parent. // Since we are processing in order, that parent will propagate to its parent // eventually, so we are fine. Add methods are log(N) because we can't rely on our // parents eventually doing work for us. if (j < arr.length) { tree[j] += tree[i]; } } } public int findFirstOccurrence(int val) { int lastmask = Integer.highestOneBit(N); int bitmask = Integer.highestOneBit(N) >> 1; int index = lastmask; int sum = tree[index]; int ans = sum == val ? index : -1; while (bitmask != 0) { int next = (index | bitmask); if (next <= N && sum < val) { index = next; sum += tree[next]; } else if (sum >= val) { // try to go downwards // todo KEY ERROR HERE!!! // todo NEEDED TO SUBTRACT THE CORRECT RESPONSIBILITY sum -= tree[index]; index ^= lastmask; index |= bitmask; sum += tree[index]; } if (sum == val) { ans = index; } lastmask = bitmask; bitmask >>= 1; } return ans; } public int valueAt(int i) { int value = tree[i]; // This overcounts by some amount of overlap due // to the responsibility (size given by LSB(i)) if (i > 0) { // If i == 0, bad! int end = i - leastSignificantBit(i); int j = i - 1; // Slide down j's chain of authority until we meet, // subtracting everything in the path. This // is slightly more efficient than calling sum twice! while (j != end) { value -= tree[j]; j -= leastSignificantBit(j); } } return value; } // return the sum public int sum(int i, int j) { return prefixSum(j) - prefixSum(i - 1); // exclude the values under i } // returns sum from 1 to i of the array // propagate downward! (decomposing the sum) public int prefixSum(int i) { int sum = 0; while (i > 0) { sum += tree[i]; i -= leastSignificantBit(i); } return sum; } // add a value of val at the ith value // propagate upward! public void add(int i, int val) { while (i < tree.length) { tree[i] += val; i += leastSignificantBit(i); } } // Change a value at an index (basically add the new value and subtract // the original value public void set(int i, int k) { int val = sum(i, i); add(i, k - val); } } static class FastScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double cnt = 1; BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt=1; boolean neg = false; if(c==NC)c=getChar(); for(;(c<'0' || c>'9'); c = getChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=getChar()) { res = (res<<3)+(res<<1)+c-'0'; cnt*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/cnt; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c>32) { res.append(c); c=getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c!='\n') { res.append(c); c=getChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=getChar(); if(c==NC)return false; else if(c>32)return true; } } } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
ad541371804c30b535464d839833ae85
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class B { static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { FS in = new FS(); int N = in.nextInt(); int ar[] = new int[N]; for(int i = 0; i < N; i++) ar[i] = in.nextInt(); Integer[] order = new Integer[N]; for(int i = 0; i < N; i++) order[i] = i; Arrays.sort(order, (a,b) -> (ar[a] == ar[b] ? b-a : ar[a]-ar[b])); long ids[] = new long[N]; for(int i = 0; i < N; i++) ids[i] = order[i]; // System.out.println(Arrays.toString(ids)); Wave wt = new Wave(ids); int M = in.nextInt(); for(int i = 0; i < M; i++) { int sz = in.nextInt(); int pos = in.nextInt(); // System.out.println(" p="+pos+" l="+(N-sz)+" r="+N); int index = wt.kthSmallest(pos, N-sz, N); out.println(ar[(int) ids[(int)index]]); } out.close(); } static class Wave{ // s for smallest, b for biggest long s = Long.MAX_VALUE, b = Long.MIN_VALUE; int N; long[] arr; int[] dex, sPtr; Wave sWav = null, bWav = null; /// CONSTRUCTOR Wave(long[] arr){ this(arr.clone(), null);} private Wave(long[] arr, int[] dex){ /// initialization stuff ////////// this.arr = arr; if(dex == null){ dex = new int[arr.length]; for(int n = 0; n < dex.length; n++) dex[n] = n;} this.dex = dex; N = dex.length; /// find the max and min ////////// for(int n = 0; n < N; n++){ s = Math.min(s, arr[dex[n]]); b = Math.max(b, arr[dex[n]]);} sPtr = new int[N+1]; for(int n = 0; n < N; n++){ sPtr[n+1] = sPtr[n]; if(arr[dex[n]] <= s + (b-s) / 2) sPtr[n+1]++;} if(s == b) return; /// recursive calls /////////////// int[] sDex = new int[sPtr[N]]; int[] bDex = new int[N - sPtr[N]]; for(int n = 0; n < N; n++){ if(sPtr[n] != sPtr[n+1]) sDex[sPtr[n]] = dex[n]; else bDex[n - sPtr[n]] = dex[n];} sWav = new Wave(arr, sDex); bWav = new Wave(arr, bDex);} /// returns index of kth (1-based) smallest element between [l,r) // (ties broken by left-to-right position) int kthSmallest(int k, int l, int r){ if(s == b) return dex[l+k-1]; // arr[dex[l+k-1]] is the value itself if(sPtr[r] - sPtr[l] >= k) return sWav.kthSmallest(k, sPtr[l], sPtr[r]); return bWav.kthSmallest(k-sPtr[r]+sPtr[l], l-sPtr[l], r-sPtr[r]);} /// returns amount of ints i (ss <= i <= bb) between [l, r) int numValsBtwn(long ss, long bb, int l, int r){ if(ss <= s && b <= bb) return r - l; if(bb < s || b < ss || s == b) return 0; return sWav.numValsBtwn(ss, bb, sPtr[l], sPtr[r]) + bWav.numValsBtwn(ss, bb, l-sPtr[l], r-sPtr[r]);} /// swaps element at (zero-based) index n-1 and index n. /// it will runtime error if !(1 <= n < arr.length) void swap(int n){ if(dex.length == arr.length){ arr[n-1] ^= arr[n]; arr[n] ^= arr[n-1]; arr[n-1] ^= arr[n];} dex[n-1] ^= dex[n]; dex[n] ^= dex[n-1]; dex[n-1] ^= dex[n]; if(s == b) return; switch(sPtr[n+1] - sPtr[n-1]){ case 2: sWav.swap(sPtr[n]); break; case 0: bWav.swap(n - sPtr[n]); break; default: setIndex(n-1, dex[n-1]); setIndex(n, dex[n]); sPtr[n] = (sPtr[n] == sPtr[n+1])? sPtr[n-1]: sPtr[n+1];}} private void setIndex(int n, int newDex){ dex[n] = newDex; if(s == b) return; if(sPtr[n+1] != sPtr[n]) sWav.setIndex(sPtr[n], newDex); else bWav.setIndex(n-sPtr[n], newDex);} } static class FS{ BufferedReader br; StringTokenizer st; public FS() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch(Exception e) { throw null;} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());} double nextDouble() { return Double.parseDouble(next());} long nextLong() { return Long.parseLong(next());} int[] NIA(int n) { int r[] = new int[n]; for(int i = 0; i < n; i++) r[i] = nextInt(); return r; } long[] NLA(int n) { long r[] = new long[n]; for(int i = 0; i < n; i++) r[i] = nextLong(); return r; } char[][] grid(int r, int c){ char res[][] = new char[r][c]; for(int i = 0; i < r; i++) { char l[] = next().toCharArray(); for(int j = 0; j < c; j++) { res[i][j] = l[j]; } } return res; } } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
2676f76f6663f706e54add92f97d03d1
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class b implements Runnable { int n, m; int[] a, ans; int[][] arr; Query[] qs; public void solve(FS in, PrintWriter out) { n = in.nextInt(); a = new int[n]; for(int i = 0; i < n; ++i) a[i] = in.nextInt(); m = in.nextInt(); qs = new Query[m]; ans = new int[m]; for(int i = 0; i < m; ++i) { int len = in.nextInt(); int idx = in.nextInt() - 1; qs[i] = new Query(i, len, idx); } Arrays.sort(qs); arr = new int[n][]; for(int i = 0; i < n; ++i) { arr[i] = new int[] {a[i], i}; } Arrays.sort(arr, (x, y) -> { if(x[0] == y[0]) { return x[1] - y[1]; } return y[0] - x[0]; }); int ptr = 0; BIT bit = new BIT(n + 10); for(Query cur : qs) { while(ptr < cur.len) { int idx = arr[ptr][1]; bit.update(idx + 1, 1); ++ptr; } int idx = cur.idx; int cans = bit.getKth(idx); ans[cur.id] = cans; } for(int i : ans) out.println(a[i]); } class Query implements Comparable<Query> { int id; int len, idx; Query(int i, int a, int b) { id = i; len = a; idx = b; } public int compareTo(Query o) { return len - o.len; } } static class BIT { int n; int[] tree; public BIT(int n) { this.n = n; tree = new int[n + 2]; } int read(int i) { int sum = 0; while (i > 0) { sum += tree[i]; i -= i & -i; } return sum; } void update(int i, int val) { while (i <= n) { tree[i] += val; i += i & -i; } } // if the BIT is a freq array, returns the // index of the kth item, or n if there are fewer // than k items. int getKth(int k) { int e=Integer.highestOneBit(n), o=0; for (; e!=0; e>>=1) { if (e+o<=n && tree[e+o]<=k) { k-=tree[e+o]; o+=e; } } return o; } } public void run() { System.err.println("go!"); FS in = new FS(); PrintWriter out = new PrintWriter(System.out); solve(in, out); out.close(); } public static void main(String[] args) { new Thread(null, new b(), "lmao", 1L<<28).start(); } static class FS { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while(!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch(Exception e) {} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
018afaf5330da6d23cd3f3496b6cde17
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
import java.io.BufferedReader; // import java.io.FileInputStream; // import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Comparator; import java.util.Random; import java.util.StringTokenizer; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.round; import static java.util.Arrays.copyOf; import static java.util.Arrays.fill; import static java.util.Arrays.sort; import static java.util.Collections.reverseOrder; import static java.util.Collections.sort; import static java.util.Comparator.comparingInt; public class Solution { FastScanner in; PrintWriter out; class Pair { int a, id; Pair(int a, int id) { this.a = a; this.id = id; } } class Triplet { int k, pos, id; Triplet(int k, int pos, int id) { this.k = k; this.pos = pos; this.id = id; } } private void solve() throws IOException { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); Pair[] p = new Pair[n]; for (int i = 0; i < n; i++) p[i] = new Pair(a[i], i); sort(p, (o1, o2) -> o1.a != o2.a ? o2.a - o1.a : o1.id - o2.id); int m = in.nextInt(); Triplet[] t = new Triplet[m]; for (int i = 0; i < m; i++) t[i] = new Triplet(in.nextInt() - 1, in.nextInt() - 1, i); sort(t, comparingInt(o -> o.k)); int[] ans = new int[m]; AVLTreePBDS tree = new AVLTreePBDS(false); for (int i = 0, j = 0; i < n; i++) { tree.add(p[i].id); while (j < m && t[j].k == i) { ans[t[j].id] = a[tree.findByOrder(t[j].pos)]; j++; } } for (int i = 0; i < m; i++) out.println(ans[i]); } class AVLTreePBDS { private Node root; private boolean multi; AVLTreePBDS(boolean multi) { this.root = null; this.multi = multi; } int size() { return size(root); } boolean isEmpty() { return size(root) == 0; } boolean contains(int key) { return contains(root, key); } void add(int key) { root = add(root, key); } void remove(int key) { root = remove(root, key); } Integer first() { Node min = findMin(root); return min != null ? min.key : null; } Integer last() { Node max = findMax(root); return max != null ? max.key : null; } Integer poolFirst() { Node min = findMin(root); if (min != null) { remove(min.key); return min.key; } return null; } Integer poolLast() { Node max = findMax(root); if (max != null) { remove(max.key); return max.key; } return null; } // min >= key Integer ceiling(int key) { return contains(key) ? key : higher(key); } // max <= key Integer floor(int key) { return contains(key) ? key : lower(key); } // min > key Integer higher(int key) { Node min = higher(root, key); return min == null ? null : min.key; } private Node higher(Node cur, int key) { if (cur == null) return null; if (cur.key <= key) return higher(cur.right, key); // cur.key > key Node left = higher(cur.left, key); return left == null ? cur : left; } // max < key Integer lower(int key) { Node max = lower(root, key); return max == null ? null : max.key; } private Node lower(Node cur, int key) { if (cur == null) return null; if (cur.key >= key) return lower(cur.left, key); // cur.key < key Node right = lower(cur.right, key); return right == null ? cur : right; } private class Node { int key, height, size; Node left, right; Node(int key) { this.key = key; height = size = 1; left = right = null; } } private int height(Node cur) { return cur == null ? 0 : cur.height; } private int balanceFactor(Node cur) { return height(cur.right) - height(cur.left); } private int size(Node cur) { return cur == null ? 0 : cur.size; } // fixVertex private void fixHeightAndSize(Node cur) { cur.height = max(height(cur.left), height(cur.right)) + 1; cur.size = size(cur.left) + size(cur.right) + 1; } private Node rotateRight(Node cur) { Node prevLeft = cur.left; cur.left = prevLeft.right; prevLeft.right = cur; fixHeightAndSize(cur); fixHeightAndSize(prevLeft); return prevLeft; } private Node rotateLeft(Node cur) { Node prevRight = cur.right; cur.right = prevRight.left; prevRight.left = cur; fixHeightAndSize(cur); fixHeightAndSize(prevRight); return prevRight; } private Node balance(Node cur) { fixHeightAndSize(cur); if (balanceFactor(cur) == 2) { if (balanceFactor(cur.right) < 0) cur.right = rotateRight(cur.right); return rotateLeft(cur); } if (balanceFactor(cur) == -2) { if (balanceFactor(cur.left) > 0) cur.left = rotateLeft(cur.left); return rotateRight(cur); } return cur; } private boolean contains(Node cur, int key) { if (cur == null) return false; else if (key < cur.key) return contains(cur.left, key); else if (key > cur.key) return contains(cur.right, key); else return true; } private Node add(Node cur, int key) { if (cur == null) return new Node(key); if (key < cur.key) cur.left = add(cur.left, key); else if (key > cur.key || multi) cur.right = add(cur.right, key); return balance(cur); } private Node findMin(Node cur) { return cur.left != null ? findMin(cur.left) : cur; } private Node findMax(Node cur) { return cur.right != null ? findMax(cur.right) : cur; } private Node removeMin(Node cur) { if (cur.left == null) return cur.right; cur.left = removeMin(cur.left); return balance(cur); } private Node removeMax(Node cur) { if (cur.right == null) return cur.left; cur.right = removeMax(cur.right); return balance(cur); } private Node remove(Node cur, int key) { if (cur == null) return null; if (key < cur.key) cur.left = remove(cur.left, key); else if (key > cur.key) cur.right = remove(cur.right, key); else { // k == cur.key Node prevLeft = cur.left; Node prevRight = cur.right; if (prevRight == null) return prevLeft; Node min = findMin(prevRight); min.right = removeMin(prevRight); min.left = prevLeft; return balance(min); } return balance(cur); } int orderOfKey(int key) { return orderOfKey(root, key); } // count < key private int orderOfKey(Node cur, int key) { if (cur == null) return 0; if (cur.key < key) return size(cur.left) + 1 + orderOfKey(cur.right, key); if (cur.key == key) return size(cur.left); // cur.key > key return orderOfKey(cur.left, key); } Integer findByOrder(int pos) { return size(root) > pos ? findByOrder(root, pos) : null; } // get i-th private int findByOrder(Node cur, int pos) { if (size(cur.left) > pos) return findByOrder(cur.left, pos); if (size(cur.left) == pos) return cur.key; // size(cur.left) < pos return findByOrder(cur.right, pos - 1 - size(cur.left)); } } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Solution().run(); } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
e109ae5ca6e5dd932dc91ca75f21e969
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
//package com.company; import java.io.*; import java.util.*; public class Main { public static class Task { public class TreapSimple { Random random = new Random(); class Treap { int key; long prio; Treap left; Treap right; int size; Treap(int key) { this.key = key; prio = random.nextLong(); size = 1; } void update() { size = 1 + getSize(left) + getSize(right); } } int getSize(Treap root) { return root == null ? 0 : root.size; } class TreapPair { Treap left; Treap right; TreapPair(Treap left, Treap right) { this.left = left; this.right = right; } } TreapPair split(Treap root, int minRight) { if (root == null) return new TreapPair(null, null); if (root.key >= minRight) { TreapPair leftSplit = split(root.left, minRight); root.left = leftSplit.right; root.update(); leftSplit.right = root; return leftSplit; } else { TreapPair rightSplit = split(root.right, minRight); root.right = rightSplit.left; root.update(); rightSplit.left = root; return rightSplit; } } Treap merge(Treap left, Treap right) { if (left == null) return right; if (right == null) return left; // if (random.nextInt(left.size + right.size) < left.size) { if (left.prio > right.prio) { left.right = merge(left.right, right); left.update(); return left; } else { right.left = merge(left, right.left); right.update(); return right; } } Treap insert(Treap root, int x) { TreapPair t = split(root, x); return merge(merge(t.left, new Treap(x)), t.right); } Treap remove(Treap root, int x) { if (root == null) { return null; } if (x < root.key) { root.left = remove(root.left, x); root.update(); return root; } else if (x > root.key) { root.right = remove(root.right, x); root.update(); return root; } else { return merge(root.left, root.right); } } int kth(Treap root, int k) { if (k < getSize(root.left)) return kth(root.left, k); else if (k > getSize(root.left)) return kth(root.right, k - getSize(root.left) - 1); return root.key; } void print(Treap root) { if (root == null) return; print(root.left); System.out.println(root.key); print(root.right); } Treap union(Treap left, Treap right) { if (left == null) return right; if (right == null) return left; if (left.prio <= right.prio) return union(right, left); TreapPair sp = split(right, left.key); left.left = union(left.left, sp.left); left.right = union(left.right, sp.right); return left; } // random test public void main(String[] args) { Treap treap = null; Set<Integer> set = new TreeSet<>(); for (int i = 0; i < 100000; i++) { int x = random.nextInt(100000); if (random.nextBoolean()) { treap = remove(treap, x); set.remove(x); } else if (!set.contains(x)) { treap = insert(treap, x); set.add(x); } if (set.size() != getSize(treap)) throw new RuntimeException(); } // print(treap); } } public class Entry implements Comparable<Entry>{ int originalIndex, value; public Entry(int originalIndex, int value) { this.originalIndex = originalIndex; this.value = value; } @Override public int compareTo(Entry o) { if (this.value == o.value) return Integer.compare(this.originalIndex, o.originalIndex); return Integer.compare(o.value, this.value); } } public class Query { int index, k, x; int tIdx; public Query(int index, int k, int x) { this.index = index; this.k = k; this.x = x; } } public void solve(Scanner sc, PrintWriter pw) throws IOException { int n = sc.nextInt(); Entry[] entries = new Entry[n]; for (int i = 0; i < n; i++) { int v = sc.nextInt(); entries[i] = new Entry(i, v); } Arrays.sort(entries); TreapSimple trs = new TreapSimple(); TreapSimple.Treap tr = null; int q = sc.nextInt(); Query[] queries = new Query[q]; for (int i = 0; i < q; i++) { int k = sc.nextInt(); int x = sc.nextInt() - 1; queries[i] = new Query(i, k, x); } Arrays.sort(queries, new Comparator<Query>() { @Override public int compare(Query o1, Query o2) { return o1.k - o2.k; } }); int eIdx = 0; for (int i = 0; i < q; i++) { while (trs.getSize(tr) < queries[i].k) { // System.err.println(trs.getSize(tr)); tr = trs.insert(tr, entries[eIdx++].originalIndex); } queries[i].tIdx = trs.kth(tr, queries[i].x); } Arrays.sort(entries, new Comparator<Entry>() { @Override public int compare(Entry o1, Entry o2) { return o1.originalIndex - o2.originalIndex; } }); Arrays.sort(queries, new Comparator<Query>() { @Override public int compare(Query o1, Query o2) { return o1.index - o2.index; } }); for (int i = 0; i < q; i++) { pw.println(entries[queries[i].tIdx].value); } } } static long TIME_START, TIME_END; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileInputStream("input")); PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out)); // PrintWriter pw = new PrintWriter(new FileOutputStream("input")); Runtime runtime = Runtime.getRuntime(); long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory(); TIME_START = System.currentTimeMillis(); Task t = new Task(); t.solve(sc, pw); TIME_END = System.currentTimeMillis(); long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory(); pw.close(); System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000); System.err.println("Time used: " + (TIME_END - TIME_START) + "."); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(s); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
568136fdb381b374cfdedde5e1c4dda2
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB2 solver = new TaskB2(); solver.solve(1, in, out); out.close(); } static class TaskB2 { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Integer[] order = new Integer[n]; for (int i = 0; i < n; i++) { order[i] = i; } Arrays.sort(order, (u, v) -> (u.equals(v) ? u - v : -Integer.compare(a[u], a[v]))); int numQueries = in.nextInt(); Query[] qs = new Query[numQueries]; for (int i = 0; i < numQueries; i++) { qs[i] = new Query(); qs[i].id = i; qs[i].k = in.nextInt() - 1; qs[i].pos = in.nextInt(); } Arrays.sort(qs, (u, v) -> (u.k - v.k)); FenwickTree tree = new FenwickTree(n); int[] ans = new int[numQueries]; int lastK = 0; for (Query q : qs) { while (lastK <= q.k) { tree.add(order[lastK], 1); ++lastK; } int l = -1; int r = n - 1; while (r - l > 1) { int m = (l + r) / 2; if (tree.sum(m) < q.pos) { l = m; } else { r = m; } } ans[q.id] = a[r]; } for (int i = 0; i < numQueries; i++) { out.println(ans[i]); } } class Query { int id; int k; int pos; } class FenwickTree { int[] a; FenwickTree(int n) { a = new int[n]; } public void add(int pos, int val) { while (pos < a.length) { a[pos] += val; pos |= pos + 1; } } public int sum(int r) { int res = 0; while (r >= 0) { res += a[r]; r = (r & (r + 1)) - 1; } return res; } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
7620ab2d33809c9fa0d91b81964d9554
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class Main{ //SOLUTION BEGIN //Into the Hardware Mode void pre() throws Exception{} void solve(int TC)throws Exception{ int n = ni(); long[] a = new long[n]; PriorityQueue<long[]> q = new PriorityQueue<>((long[] l1, long[] l2) -> (l1[1] == l2[1]?Long.compare(l2[0], l1[0]):Long.compare(l1[1], l2[1]))); for(int i = 0; i< n; i++){ a[i] = nl(); q.add(new long[]{i, a[i]}); } int m = 1; while(m<n)m<<=1; int[] t = new int[m<<1]; for(int i = 0; i< n; i++)t[i+m] = 1; for(int i = m-1; i> 0; i--)t[i] = t[i<<1]+t[i<<1|1]; int qq = ni(); long[] ans = new long[qq]; int[][] qu = new int[qq][]; for(int i = 0; i< qq; i++)qu[i] = new int[]{i, ni(), ni()}; Arrays.sort(qu, (int[] i1, int[] i2) -> Integer.compare(i2[1], i1[1])); int cur = n; for(int i = 0; i< qq; i++){ while(cur > qu[i][1]){ long[] tt = q.poll(); off(t, (int)tt[0]+m); cur--; } ans[qu[i][0]] = a[get(t, 0, m-1, 1, qu[i][2]-1)]; } for(long l:ans)pn(l); } void off(int[] t, int p){ t[p] = 0; for(p>>=1; p>0; p>>=1)t[p] = t[p<<1]+t[p<<1|1]; } int get(int[] t, int l, int r, int i, int k){ if(l == r)return l; int mid = (l+r)/2; if(t[i<<1] <= k)return get(t, mid+1, r, i<<1|1, k-t[i<<1]); return get(t, l, mid, i<<1, k); } class SegTree{ int m = 1; public SegTree(int n){ } } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} void exit(boolean b){if(!b)System.exit(0);} long IINF = (long)1e18; final int INF = (int)1e9+2, MX = (int)2e6+5; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-7; static boolean multipleTC = false, memory = false, fileIO = false; FastReader in;PrintWriter out; void run() throws Exception{ if(fileIO){ in = new FastReader("C:/users/user/desktop/inp.in"); out = new PrintWriter("C:/users/user/desktop/out.out"); }else { in = new FastReader(); out = new PrintWriter(System.out); } //Solution Credits: Taranpreet Singh int T = (multipleTC)?ni():1; pre(); for(int t = 1; t<= T; t++)solve(t); out.flush(); out.close(); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));} int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;} long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str = ""; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
9ffc9fd3312eb6cdeb21939f6b5a6bfb
train_004.jsonl
1574582700
This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$: $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list); $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if: it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$; and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t&lt;c_t$$$. For example: $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$, $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$, $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.
256 megabytes
//package round602; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; public class B2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); int[][] ai = new int[n][]; for(int i = 0;i < n;i++){ ai[i] = new int[]{a[i], i}; } Arrays.sort(ai, new Comparator<int[]>() { public int compare(int[] a, int[] b) { if(a[0] != b[0])return a[0] - b[0]; return -(a[1] - b[1]); } }); int Q = ni(); int[][] qs = new int[Q][]; for(int i = 0;i < Q;i++){ qs[i] = new int[]{ni(), ni()-1, i}; } Arrays.sort(qs, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[0] - b[0]; } }); int[] ft = new int[n+5]; int p = 0; int[] anss = new int[Q]; for(int k = 1;k <= n;k++){ addFenwick(ft, ai[n-k][1], 1); while(p < Q && qs[p][0] <= k){ anss[qs[p][2]] = a[firstGEFenwick(ft, qs[p][1]+1)]; p++; } } for(int v : anss){ out.println(v); } } public static int sumFenwick(int[] ft, int i) { int sum = 0; for(i++;i > 0;i -= i&-i)sum += ft[i]; return sum; } public static void addFenwick(int[] ft, int l, int r, int v) { addFenwick(ft, l, v); addFenwick(ft, r, -v); } public static void addFenwick(int[] ft, int i, int v) { if(v == 0 || i < 0)return; int n = ft.length; for(i++;i < n;i += i&-i)ft[i] += v; } public static int firstGEFenwick(int[] ft, int v) { int i = 0, n = ft.length; for(int b = Integer.highestOneBit(n);b != 0;b >>= 1){ if((i|b) < n && ft[i|b] < v){ i |= b; v -= ft[i]; } } return i; } public static int[] radixSort(int[] f){ return radixSort(f, f.length); } public static int[] radixSort(int[] f, int n) { int[] to = new int[n]; { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[f[i]&0xffff]++] = f[i]; int[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i]; int[] d = f; f = to;to = d; } return f; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new B2().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3", "7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4"]
3 seconds
["20\n10\n20\n10\n20\n10", "2\n3\n2\n3\n2\n3\n1\n1\n3"]
NoteIn the first example, for $$$a=[10,20,10]$$$ the optimal subsequences are: for $$$k=1$$$: $$$[20]$$$, for $$$k=2$$$: $$$[10,20]$$$, for $$$k=3$$$: $$$[10,20,10]$$$.
Java 8
standard input
[ "greedy", "constructive algorithms", "sortings", "data structures", "binary search" ]
082eec813f870357dbe3c5abec6a2b52
The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.
1,800
Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.
standard output
PASSED
a24befef6b766d3f1aa46362b89d4f29
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class SolutionA { public static void main(String[] args){ new SolutionA().run(); } int n, m; int a[], b[]; void solve(){ n = in.nextInt(); m = in.nextInt(); a = new int[n]; b = new int[m]; for(int i = 0; i<n; ++i) a[i] = in.nextInt(); for(int i = 0; i < m; ++i) b[i] = in.nextInt(); int ans = 0; int l = n-1; int r = m-1; while(l >= 0 && r >= 0){ if(a[l] > b[r]){ ans++; l--; } else { l--; r--; } } out.println(ans + l + 1); } class Pair implements Comparable<Pair>{ int x, y; Pair(int x, int y){ this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if(o.x == x) return ((Integer) y).compareTo(o.y); return ((Integer) x).compareTo(o.x); } } FastScanner in; PrintWriter out; void run(){ in = new FastScanner(System.in); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.close(); } void runIO(){ try{ in = new FastScanner(new File("expr.in")); out = new PrintWriter(new FileWriter(new File("expr.out"))); solve(); out.close(); }catch(Exception ex){ ex.printStackTrace(); } } class FastScanner{ BufferedReader bf; StringTokenizer st; public FastScanner(File f){ try{ bf = new BufferedReader(new FileReader(f)); } catch(IOException ex){ ex.printStackTrace(); } } public FastScanner(InputStream is){ bf = new BufferedReader(new InputStreamReader(is)); } String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(bf.readLine()); } catch(IOException ex){ ex.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } double nextDouble(){ return Double.parseDouble(next()); } float nextFloat(){ return Float.parseFloat(next()); } String nextLine(){ try{ return bf.readLine(); } catch(Exception ex){ ex.printStackTrace(); } return ""; } long nextLong(){ return Long.parseLong(next()); } } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
aefdc4e119bf6dd591a482a81fc3418a
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
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.text.SimpleDateFormat; import java.util.Arrays; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Algorithm { public static void main(String args[]) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solution s = new Solution(); s.solve(in, out); out.close(); } } class Solution { public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[] na = new int[n]; for (int i = 0; i < n; i++) { na[i] = in.nextInt(); } Arrays.sort(na); int[] ma = new int[m]; for (int i = 0; i < m; i++) { ma[i] = in.nextInt(); } Arrays.sort(ma); int k=0; int sum =0; boolean good; for (int i = 0; i < n; i++) { good = false; for (int j = k; j<m; j++){ if (na[i]<=ma[j]){ k=++j; //System.out.println(""+k+j); good = true; break; } } if (!good){ sum++; } } out.print(sum); } public void sortPair(Pair[] p) { int count = p.length; Pair t; for (int i = 0; i < count - 1; i++) { for (int j = i + 1; j < count; j++) { if (p[i].a > p[j].a) { t = p[i]; p[i] = p[j]; p[j] = t; } } } } class Pair { int i; int a; int p; public Pair(int i, int a) { this.i = i; this.a = a; } } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
72b421be94967e914839a8b080d24e74
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.*; public class Player { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int[] need = new int[n]; int[] prepared = new int[m]; for (int i = 0; i < n; i++) need[i] = scanner.nextInt(); for (int i = 0; i < m; i++) prepared[i] = scanner.nextInt(); int result = 0; int counter = 0; for (int i = 0; i < m && counter < n; i++) { if (need[counter] <= prepared[i]) { result++; counter++; } } System.out.println(n - result); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
c759c7c6d3492c4d6bb9246718e46292
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.*; public final class GeorgeAndRound {static int[] a,b,c; public static void main(String[] args) { Scanner br=new Scanner(System.in); int n=br.nextInt(); int m=br.nextInt(); a=new int[n]; c=new int[m]; b=new int[m]; int f=0; for(int i=0;i<n;i++ ) a[i]=br.nextInt(); for(int i=0;i<m;i++) b[i]=br.nextInt(); for(int i=0;i<n;i++) { if(search(a[i])==-1) f++; } System.out.println(f); } public static int search(int x) {int i=0; while(i<b.length) { if(b[i]>=x && c[i]==0) {c[i]=1; return i;} i++; } return -1; } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
439b9e28aa6473ecd2729888564d48e4
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.io.IOException; import java.text.ParseException; import java.util.*; public class Tests { private static int pow(int num, int pow) { int res = 1; for (int i = 1; i <= pow; i++) { res *= num; } return res; } private static int nod(int a, int b) { while (b != 0) { int tmp = a % b; a = b; b = tmp; } return a; } public static void main(String[] args) throws IOException, ParseException { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); Integer[] a = new Integer[n]; int[] b = new int[m]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } for (int i = 0; i < m; i++) { b[i] = scanner.nextInt(); } /* Map<Integer, Integer> allCount = new HashMap<Integer, Integer>(); for (int i = 0; i < m; i++) { Integer gotNumber = allCount.get(b[i]); if (gotNumber != null) { allCount.put(b[i], gotNumber + 1); } else { allCount.put(b[i], 1); } } for (int i = 0; i < n; i++) { Integer gotNumber = allCount.get(a[i]); if (gotNumber != null) { allCount.put(a[i], gotNumber - 1); } else { allCount.put(a[i], -1); } } int count = 0; for (Map.Entry<Integer, Integer> entry : allCount.entrySet()) { if (entry.getValue() < 0) { count -= entry.getValue(); } } System.out.println(count); */ List<Integer> needed = new ArrayList<Integer>(Arrays.asList(a)); Collections.sort(needed); Arrays.sort(b); for (int i = 0; i < b.length; i++) { Integer listNum = needed.get(0); if (listNum <= b[i]) { needed.remove(listNum); } if (needed.size() == 0) { break; } } System.out.println(needed.size()); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
4e9cb4b40b39439654381817718a1eb1
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.io.PrintStream; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nipuna Samarasekara */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { ///////////////////////////////////////////////////////////// public void solve(int testNumber, FastScanner in, FastPrinter out) { int n=in.nextInt(),m=in.nextInt(); int[] A=in.readIntArray(n); int[] B=in.readIntArray(m); Arrays.sort(A);Arrays.sort(B); int p1=n-1,p2=m-1; int ct=0; while(p1>=0){ if(p2>=0){ if(B[p2]>=A[p1]){ p1--;p2--; } else{ ct++;p1--; } } else {ct++; p1--; } } out.println(ct); } } class FastScanner extends BufferedReader { public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); // if (isEOF && ret < 0) { // throw new InputMismatchException(); // } // isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } public String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } public int[] readIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
d25f1bb8e6fcda0e68b95e777b83837f
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import javax.swing.event.InternalFrameEvent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /** * Created with IntelliJ IDEA. * User: AUtemuratov * Date: 07.04.14 * Time: 15:43 * To change this template use File | Settings | File Templates. */ public class Main { static ArrayList<Integer> a = new ArrayList<Integer>(); static ArrayList<Integer> b = new ArrayList<Integer>(); public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer tk = new StringTokenizer(bf.readLine()); int n = Integer.parseInt(tk.nextToken()); int m = Integer.parseInt(tk.nextToken()); tk = new StringTokenizer(bf.readLine()); for (int i=1; i<=n; i++) { a.add(Integer.parseInt(tk.nextToken())); } tk = new StringTokenizer(bf.readLine()); for (int i=1; i<=m; i++) { b.add(Integer.parseInt(tk.nextToken())); } pw.println(check()); pw.close(); } public static int check() { for (int i=0; i<a.size(); i++) { for (int j=0; j<b.size(); j++) { if (a.get(i)<=b.get(j)) { a.remove(i); b.remove(j); check(); break; } } } return a.size(); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
a94f3db9663faa225ab5c6a3f8f2aad0
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class CF387B { static int n; static int m; static int[] a; static int[] b; public static void main(String[] args) { Scanner in = new Scanner(System.in); n = in.nextInt(); m = in.nextInt(); a = new int[n]; b = new int[m]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); for (int i = 0; i < m; i++) b[i] = in.nextInt(); int ap = 0; for (int bp = 0; bp < m; bp++) { if (b[bp] >= a[ap]) { ap++; if (ap == n) break; } } System.out.println(n-ap); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
ff19047b1a0d9046acf638758da43bc4
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.io.*; import java.util.*; import java.*; import java.math.BigInteger; import java.util.ArrayList; import java.util.Random; import java.lang.*; import javax.naming.BinaryRefAddr; public class zad { private static BufferedReader in; private static StringTokenizer tok; private static PrintWriter out; final static boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") !=null; public static void init() throws FileNotFoundException{ if(ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("out.txt"); } } private static String readString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } private static int readInt() throws IOException { return Integer.parseInt(readString()); } private static double readDouble() throws IOException { return Double.parseDouble(readString()); } private static long readLong() throws IOException { return Long.parseLong(readString()); } private static float readFloat() throws IOException{ return Float.parseFloat(readString()); } public static class Point implements Comparable{ private int x; private int y; Point(int x, int mum){ this.x = x; y = mum; } public int getX(){ return x; } public void setX(int x){ this.x = x; } public int getY(){ return y; } public boolean equals(Point b){ if(this.x == b.getX() && this.y == b.getY()) return true; return false; } public int compareTo(Object obj) { Point tmp = (Point)obj; if(this.x < tmp.getX()) { /* текущее меньше полученного */ return -1; } else if(this.x > tmp.getX()) { /* текущее больше полученного */ return 1; } /* текущее равно полученному */ return 0; } } public static void Solve() throws IOException{ int n =readInt(); int m =readInt(); int[] need = new int[n]; for(int i=0;i<n;i++){ need[i] = readInt(); } int[] mas = new int[m]; for(int i=0;i<m;i++){ mas[i] =readInt(); } int ans=0; int j = m-1; for(int i=n-1;i>-1;i--){ if(need[i]>mas[j]){ ans++; } else{ if(j-1==-1){ out.print(ans+i); return; } else j--; } } out.print(ans); } public static void main(String[] args) throws IOException { init(); Solve(); in.close(); out.close(); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
591cd9ae32781a7621e8ed280a677cc0
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class B { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(bf.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[] a = new int[n]; st = new StringTokenizer(bf.readLine()); for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); int[] b = new int[m]; st = new StringTokenizer(bf.readLine()); for(int i=0; i<m; i++) b[i] = Integer.parseInt(st.nextToken()); Arrays.sort(a); Arrays.sort(b); int counter = m-1; int ans = 0; for(int i=n-1; i>=0; i--) { if(counter >= 0 && b[counter] >= a[i]) counter--; else ans++; } System.out.println(ans); // Scanner scan = new Scanner(System.in); // PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); // int n = Integer.parseInt(bf.readLine()); // StringTokenizer st = new StringTokenizer(bf.readLine()); // int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); // int n = Integer.parseInt(st.nextToken()); // int n = scan.nextInt(); // out.close(); System.exit(0); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
65547a9e2da96ce9e620608725b06438
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Solution implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new Solution(), "", 256 * (1L << 20)).start(); } public void run() { try { long t1 = System.currentTimeMillis(); if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); //out = new PrintWriter("output.txt"); out = new PrintWriter(System.out); } Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } // solution void solve() throws IOException { int n = readInt(), m = readInt(); int[] a = new int[n], b = new int[m]; for(int i = 0; i<n; i++) a[i] = readInt(); for(int i = 0; i<m; i++) b[i] = readInt(); int answer = n; for(int i = 0; i<=n; i++) { if(i>m) break; boolean good = true; for(int j = 0; j<i && good; j++) if(a[i - j - 1] > b[m-1-j]) good = false; if(good) answer = Math.min(answer, n - i); } out.println(answer); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
f85777e493786b3bd6d2e2de02cd9c1e
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.*; import java.io.*; public class id2 { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[] arrN = new int[n]; int[] arrM = new int[m]; for(int i=0; i < n; i++){ arrN[i] = sc.nextInt(); } for (int i=0; i < m; i++){ arrM[i] = sc.nextInt(); } int count = n; Arrays.sort(arrN); Arrays.sort(arrM); for (int i=0; i < n; i++){ for (int j = 0; j < m; j++){ if (arrN[i] <= arrM[j]){ count--; arrM[j] = 0; break; } } } System.out.println(count); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
a6ddedec108f7fff7b6a3ec7e1f53409
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.io.*; import java.lang.*; public class Contest { public static void main(String args[]) throws IOException { BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); String x[]= br.readLine().split(" "); int n = Integer.parseInt(x[0]); int m = Integer.parseInt(x[1]); String as[] = br.readLine().split(" "); String bs[] = br.readLine().split(" "); int a[]=new int[n]; int b[]=new int[m]; for(int i=0; i<n; i++) a[i]=Integer.parseInt(as[i]); for(int i=0; i<m; i++) b[i]=Integer.parseInt(bs[i]); for(int i=0; i<n; i++) for(int j=0; j<m; j++) if(b[j]==a[i]) a[i]=b[j]=0; BubbleSort(a); BubbleSort(b); outer: for(int i=0; i<n; i++) { if(a[i]!=0) { for(int j=0; j<m; j++) if(b[j]>a[i]) { a[i]=b[j]=0; continue outer; } } } int count =0; for(int i=0; i<n; i++) if(a[i]!=0) count++; System.out.println(count); } public static void BubbleSort( int [ ] num ) { int j; boolean flag = true; // set flag to true to begin first pass int temp; //holding variable while ( flag ) { flag= false; //set flag to false awaiting a possible swap for( j=0; j < num.length -1; j++ ) { if ( num[ j ] < num[j+1] ) // change to > for ascending sort { temp = num[ j ]; //swap elements num[ j ] = num[ j+1 ]; num[ j+1 ] = temp; flag = true; //shows a swap occurred } } } } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
70241c6603fd30113f252fc0f1ab6d55
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.Arrays; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ 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(); Integer[] a = new Integer[n]; Integer[] b = new Integer[m]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } for (int i = 0; i < m; i++) { b[i] = in.nextInt(); } Arrays.sort(a); Arrays.sort(b); boolean[] ok = new boolean[n]; for (int i = m - 1; i >= 0; i--) { for (int j = n - 1; j >= 0; j--) { if (!ok[j] && a[j] <= b[i]) { ok[j] = true; break; } } } int res = 0; for (int i = 0; i < n; i++) { if (!ok[i]) ++res; } out.println(res); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
45bcb2a794d2e848d6a37124be6f0dfb
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.*; import java.io.*; public class BGood { FastScanner in; PrintWriter out; public void solve() throws IOException { int n = in.nextInt(); int m = in.nextInt(); int nMas[] = new int[n]; for(int i = 0; i < n; i++) { nMas[i] = in.nextInt(); } int bMas[] = new int[m]; for(int i = 0; i < m; i++) { bMas[i] = in.nextInt(); } Arrays.sort(nMas); Arrays.sort(bMas); int i = 0; int jStart = 0; for(; i < n; i++) { boolean bFound = false; for(int j = jStart; j < m; j++) { if(bMas[j] >= nMas[i]) { jStart = j + 1; bFound = true; break; } } if(bFound == false) break; } out.print(n - i); } public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); //in = new FastScanner(new File("sum.in")); //out = new PrintWriter(new File("sum.out")); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] arg) { new BGood().run(); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
fb7cdc73e1c605c93f7dc0ea31a83992
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.Scanner; 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 */ 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(); int []a = new int[n]; int []b = new int[m]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } for (int i = 0; i < m; i++) { b[i] = in.nextInt(); } Arrays.sort(a); Arrays.sort(b); int bPointer = 0; int aPointer = 0; int res = 0; for (int i = 0; i < n; i++) { while (bPointer < m && a[i] > b[bPointer])bPointer++; if (bPointer < m){ bPointer++; continue; } else res++; } out.println(res); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
0d066194efe2f665622638d002ac1c27
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.*; import java.io.*; public class B implements Runnable { public void solve() throws IOException { int N = nextInt(); int M = nextInt(); int[] a = new int[N]; for(int i = 0; i < N; i++)a[i] = nextInt(); int[] b = new int[M]; for(int i = 0; i < M; i++) b[i] = nextInt(); int ind = 0; for(int i = 0; i < N; i++){ boolean found = false; for(int j = ind; j < M; j++){ if(b[j] >= a[i]){ ind++; found = true; break; } else{ ind++; } } if(!found){ System.out.println(N - i); return; } } System.out.println(0); } //----------------------------------------------------------- public static void main(String[] args) { new B().run(); } public void print1Int(int[] a){ for(int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } public void print2Int(int[][] a){ for(int i = 0; i < a.length; i++){ for(int j = 0; j < a[0].length; j++){ System.out.print(a[i][j] + " "); } System.out.println(); } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); tok = null; solve(); in.close(); } catch (IOException e) { System.exit(0); } } public String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.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()); } BufferedReader in; StringTokenizer tok; }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
b7c949b0d6dcdcdb84726aad1b3079e6
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import static java.lang.Math.abs; /** * Created by Dmytry on 3/10/14. */ public class Main { static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(""); public static void main(String[] args) throws Exception { int n = NI(); int m = NI(); int[] tasks = new int[n]; int[] difficulties = new int[m]; for (int i = 0; i < n; i ++) { tasks[i] = NI(); } for (int i = 0; i < m; i ++) { difficulties[i] = NI(); } for (int i = 0; i < n; i ++) { for (int j = 0; j < m; j ++) { if ((tasks[i] <= difficulties[j]) && (tasks[i] != 0)) { tasks[i] = 0; difficulties[j] = 0; } } } int result = 0; for (int t : tasks) { if (t != 0) result ++; } System.out.println(result); } static String NS() throws Exception { while (!st.hasMoreTokens()) st = new StringTokenizer(stdin.readLine()); return st.nextToken(); } static int NI() throws Exception {return Integer.parseInt(NS());} }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
c481c02c42164ae08519dea41091ca4a
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.Scanner; public class Codeforce{ public static void main(String[] arg){ Scanner sc = new Scanner(System.in); int problemsNeeded = sc.nextInt(); int georgeProblems = sc.nextInt(); int[] totalProblemNeeded = new int[problemsNeeded]; int[] totalGeorgeProblem = new int[georgeProblems]; for (int i = 0; i < problemsNeeded; i ++){ totalProblemNeeded[i] = sc.nextInt(); } for (int i = 0; i < georgeProblems; i ++){ totalGeorgeProblem[i] = sc.nextInt(); } sc.close(); for (int i = 0; i < totalProblemNeeded.length; i++){ for (int j = 0; j <totalGeorgeProblem.length; j++){ if (totalProblemNeeded[i] == totalGeorgeProblem[j]){ totalGeorgeProblem[j] = totalProblemNeeded[i]= 0; problemsNeeded--; break; } } } if (problemsNeeded > 0){ for (int i = 0; i < totalProblemNeeded.length; i++){ if (totalProblemNeeded[i] != 0){ for (int j = 0; j < totalGeorgeProblem.length; j++){ if (totalGeorgeProblem[j] > totalProblemNeeded[i]){ totalGeorgeProblem[j] = totalProblemNeeded[i]= 0; problemsNeeded--; break; } } } } } System.out.println(problemsNeeded); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
ef2b61f5ffe1c39615a9ebff00cdfe91
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
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.StringTokenizer; public class B { /** * @param args */ public static void main(String[] args) throws IOException { BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer to = new StringTokenizer(sc.readLine(), " "); int n = Integer.parseInt(to.nextToken()); int m = Integer.parseInt(to.nextToken()); ArrayList<Integer> ns = new ArrayList<Integer>(n); ArrayList<Integer> ms = new ArrayList<Integer>(n); to = new StringTokenizer(sc.readLine(), " "); for (int i = 0; i < n; i++) { ns.add(Integer.parseInt(to.nextToken())); } Collections.sort(ns); to = new StringTokenizer(sc.readLine(), " "); for (int i = 0; i < m; i++) { ms.add(Integer.parseInt(to.nextToken())); } Collections.sort(ms); int i = 0, j = 0; while (i < n && j < m) { if (ns.get(i) <= ms.get(j)) { i++; j++; } else { j++; } } System.out.println(n - i); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
456ae4dcc4571e24c6cda7442110cbe1
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Robin Kumar (krobin_93) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReaderClass in = new InputReaderClass(inputStream); OutputWriterClass out = new OutputWriterClass(outputStream); GeorgeAndRound solver = new GeorgeAndRound(); solver.solve(1, in, out); out.close(); } } class GeorgeAndRound { public void solve(int testNumber, InputReaderClass in, OutputWriterClass out) { int n = in.readInt(); int m = in.readInt(); int[] prep = new int[m]; int[] req = new int[n]; for (int i = 0; i < n; i++) req[i] = in.readInt(); Arrays.sort(req); for (int i = 0; i < m; i++) prep[i] = in.readInt(); Arrays.sort(prep); int count=0; int j = 0; for (int i = 0; i < n && j < m;j++ ) { if (req[i]<= prep[j]) { count++; i++; } // System.out.println("count of " + req[i] + " " + prepLookup[req[i]]); } out.printLine(n-count); } } class InputReaderClass { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReaderClass(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriterClass { private final PrintWriter writer; public OutputWriterClass(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter( outputStream))); } public OutputWriterClass(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
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
a7cb23737fc583fc2967da3648471bc8
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.lang.*; import java.io.*; import java.util.*; public class Round { public static void main(String[] args) throws java.lang.Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(in, out); out.close(); } } class TaskA { public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); int[] a = new int[n]; int[] b = new int[m]; int i, j, k; int tot = 0; int ans = 0; for (i=0; i<n; ++i) a[i] = in.nextInt(); for (i=0; i<m; ++i) b[i] = in.nextInt(); i = n - 1; j = m - 1; while (i>=0 && j>=0) { k = j; while (j>=0 && b[j]>=a[i]) --j; tot += k - j; if (tot == 0) { ++ans; } else { --tot; } --i; } if (i >= 0) { ans += Math.max(i+1-tot, 0); } out.println(ans); } } 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
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
bd7f267db8bdb033724f9fde53f89937
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String ar[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int a[] = new int[n]; int b[] = new int[m]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } for (int i = 0; i < m; i++) b[i] = in.nextInt(); int i = 0, j = 0; while (i < n && j < m) { if (a[i] <= b[j]) i++; j++; } System.out.println(n - i); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
41946716a3f5bb65a693b48a345117b2
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.io.*; import java.util.*; public class CF227B { private static BufferedReader br; private static StringTokenizer st; private static PrintWriter pw; // private static Timer t = new Timer(); public CF227B() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); } String next() throws IOException { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() { if (st != null && st.hasMoreElements()) return true; try { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); } catch (Exception e) { return false; } return true; } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } void solve() throws IOException { int n = nextInt(), m = nextInt(); int[] need = new int[n]; for(int i = 0; i < n; i++) { need[i] = nextInt(); } int[] mas = new int[m]; for(int i = 0; i < m; i++) { mas[i] = nextInt(); } int ans = 0; int j = m - 1; for(int i = n-1; i >= 0; i--) { if(need[i] > mas[j]) { ans++; }else { if(j-1 == -1) { pw.println(ans+i); pw.flush(); return; } else j--; } } pw.println(ans); /* int n = nextInt(), m = nextInt(), count = 0; long[] a = new long[n]; ArrayList<Long> list = new ArrayList<>(); for(int i = 0; i < n; i++) a[i] = nextLong(); for(int i = 0; i < m; i++) { list.add(nextLong()); } for(int i = 0; i < n; i++) { if(list.contains(a[i])) { list.remove(list.indexOf(a[i])); }else count++; } pw.println(count); */ pw.flush(); } public static void main(String[] args) throws IOException{ new CF227B().solve(); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
0f22de5c3a4c8818bc5ab270a021a6ef
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Round { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); int[] tasks1 = new int[N]; int[] tasks2 = new int[M]; for(int i = 0; i < tasks1.length; i++){ tasks1[i] = sc.nextInt(); } for(int i = 0; i < tasks2.length; i++){ tasks2[i] = sc.nextInt(); } Arrays.sort(tasks1); Arrays.sort(tasks2); int index1 = 0; int index2 = 0; while(index1 < tasks1.length && index2 < tasks2.length){ while(index2 < tasks2.length && tasks1[index1] > tasks2[index2]){ index2++; } if(index2 < tasks2.length){ index1++; index2++; } } int count = tasks1.length - index1; System.out.println(count); sc.close(); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
9b86b5ddf946933a180f55bb3ab04660
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.*; public class GeorgeRound { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int m = s.nextInt(); int[] r = new int[n]; // requirements int[] c = new int[m]; // complexities for(int i=0; i<n; i++) r[i] = s.nextInt(); for(int i=0; i<m; i++) c[i] = s.nextInt(); s.close(); Arrays.sort(r); Arrays.sort(c); int t = 0, i = 0, j = 0; while(j < m && i < n) { if(c[j] >= r[i]) { i++; j++; t++; } else j++; } System.out.println(n-t); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
605df1427a4a5b4ed40db7ca3329ced9
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.Arrays; import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author KHALED */ public class GeorgeandRound { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); int m=scan.nextInt(); int[]needed=new int[n]; int[]prepared=new int[m]; for (int i = 0; i < n; i++) { needed[i]=scan.nextInt(); } for (int i = 0; i < m; i++) { prepared[i]=scan.nextInt(); } Arrays.sort(needed); Arrays.sort(prepared); int index=0; int count=0; if(m==0) { System.out.println(n); return; } for (int i = 0; i < n; i++) { for (int j = index; j < m; j++) { if(prepared[j]>=needed[i]) { index=j+1; count++; break; } } if(index==m) break; } System.out.println(n-count); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
53d1b755369fa473ac79ce01a1782eb1
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.*; public class p387B { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(), m = in.nextInt(); int[] a = new int[n], b = new int[m]; for(int i=0; i<n; ++i) a[i] = in.nextInt(); for(int i=0; i<m; ++i) b[i] = in.nextInt(); int count = 0; int a_ptr = a.length-1, b_ptr = b.length-1; while(a_ptr >= 0 && b_ptr >= 0) { if(a[a_ptr] <= b[b_ptr]) { --a_ptr; --b_ptr; } else { ++count; --a_ptr; } } if(a_ptr >= 0) count += a_ptr+1; System.out.println(count); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
60550366ef81d8fcae94e4a3a5e9872a
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nguyen Trung Hieu - vuondenthanhcong11@yahoo.com */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int needCount = in.readInt(); int preparedCount = in.readInt(); int[] need = IOUtils.readIntArray(in, needCount); int[] prepared = IOUtils.readIntArray(in, preparedCount); Arrays.sort(need); Arrays.sort(prepared); int up = 0; int down = 0; while (up < needCount && down < preparedCount) { if (need[up] > prepared[down]) down++; else { up++; down++; } } out.printLine(needCount - up); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public 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(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
8ce6068600fc1a38ab6d0cbd5e4079da
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Scanner; public class TaskB { Scanner in; PrintWriter out; int n, m, ans; int[] a, b; public static void main(String[] args) { TaskB mainTest = new TaskB(); mainTest.readData(); mainTest.solve(); mainTest.outputData(); } public TaskB() { in = new Scanner(System.in); out = new PrintWriter(new OutputStreamWriter(System.out)); } public void readData() { n = in.nextInt(); m = in.nextInt(); a = new int[n]; b = new int[m]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } for (int i = 0; i < m; i++) { b[i] = in.nextInt(); } } public void solve() { Arrays.sort(a); Arrays.sort(b); int j = 0; for (int i = 0; i < m && j < n; i++) { if (b[i] >= a[j]) { j++; } } ans = n - j; } public void outputData() { System.out.println(ans); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
34f76b28b26cac62b9f2bbc2197a5d94
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Scanner; import java.util.Set; /** * * @author izharishaksa */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int m = sc.nextInt(); int n = sc.nextInt(); int[] req = new int[m]; for (int i = 0; i < m; i++) { req[i] = sc.nextInt(); } HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) { int x = sc.nextInt(); if (map.containsKey(x)) { map.put(x, map.get(x) + 1); } else { map.put(x, 1); } } boolean[] sudah = new boolean[m]; for (int i = 0; i < m; i++) { if (map.containsKey(req[i])) { int x = map.get(req[i]); if (x > 0) { sudah[i] = true; x--; map.put(req[i], x); } } } int total = 0; Set<Integer> set = map.keySet(); List<Integer> list = new ArrayList<Integer>(); for (int i : set) { list.add(i); } Collections.sort(list); for (int i = 0; i < m; i++) { if (!sudah[i]) { for (int j : list) { if (j > req[i]) { int x = map.get(j); if (x > 0) { x--; sudah[i] = true; map.put(j, x); break; } } } } } for (int i = 0; i < m; i++) { if (!sudah[i]) { total++; } } System.out.println(total); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
3e6d78bb4dcfde7f144d3814d3e4f00b
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.Scanner; public class Enter { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int[] a = new int[n]; int[] b = new int[m]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } for (int i = 0; i < m; i++) { b[i] = scanner.nextInt(); } int result = 0; int last = m - 1; for (int i = n - 1; i >= 0; i--) { if (i < m) { if (a[i] > b[last]) { result++; } else { last--; } } else { result++; } } System.out.print(result); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
6c3cc7f1bb7d0d9fb343ae289732c0a4
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; public class CopyOfSolution { public static void main(String[] args) throws NumberFormatException, IOException { OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); InputReader in = new InputReader(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextInt(); } int[] b = new int[m]; for (int i = 0; i < b.length; i++) { b[i] = in.nextInt(); } // Arrays.sort(a); // Arrays.sort(b); int j = 0; int i = 0; for (; i < n; i++, j++) { while (j < m && b[j] < a[i]) { j++; } if (j >= m) { break; } } out.println(n - i); out.close(); } private static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
0c7b804970acb42215869bc6a9d1dc00
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
import java.util.*; public class bb { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(), m = input.nextInt(); PriorityQueue<Integer> first = new PriorityQueue<Integer>(), second = new PriorityQueue<Integer>(); for(int i = 0; i<n; i++) first.add(input.nextInt()); for(int i = 0; i<m; i++) second.add(input.nextInt()); while(!first.isEmpty() && !second.isEmpty()) { int a = first.peek(), b = second.poll(); if(b>=a) first.poll(); } System.out.println(first.size()); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
a6b6e920ff2d4e9e6c89f87922fbedf6
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
256 megabytes
//package Div227; import java.util.Arrays; import java.util.Scanner; public class B { private static int[] b; private static int[] a; private static int to = 0, n; private static int ans; public static void delete(int xx){ // System.out.print(xx+" "); for (int i = to; i < n; i++) { if (xx>=a[i]) { // System.out.print(xx+" "); ans--; to = i+1; break; } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); int m = sc.nextInt(); a = new int[n]; b = new int[m]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } for (int i = 0; i < m; i++) { b[i] = sc.nextInt(); } Arrays.sort(b); ans = n; for (int i = 0; i < m; i++) { delete(b[i]); } System.out.println(ans<=0?"0":ans); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
55b9778711cc7fb3607aa4512c2e07ce
train_004.jsonl
1391095800
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
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; import javax.naming.BinaryRefAddr; public class pBB { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int arr[] = new int [m]; int my[] = new int [n]; st = new StringTokenizer(in.readLine()); for(int i = 0;i<n;i++) my[i] = Integer.parseInt(st.nextToken()); st = new StringTokenizer(in.readLine()); Arrays.sort(my); for(int i =0;i<m;i++){ arr[i]=Integer.parseInt(st.nextToken()); for(int j = 0; j<n;j++) if(arr[i]==my[j]){ arr[i] = my[j] = 0; } } int res = 0; int last = 0; for(int i = 0;i<n;i++){ if(my[i]==0) continue; boolean x =false; for(int j = 0;j<m;j++){ if(arr[j]>=my[i]){ arr[j] = 0; x = true; break; } } if(!x) res++; } out.println(res); in.close(); out.close(); } }
Java
["3 5\n1 2 3\n1 2 2 3 3", "3 5\n1 2 3\n1 1 1 1 1", "3 1\n2 3 4\n1"]
1 second
["0", "2", "3"]
NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Java 7
standard input
[ "two pointers", "greedy", "brute force" ]
bf0422de4347a308d68a52421fbad0f3
The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 &lt; a2 &lt; ... &lt; an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.
1,200
Print a single integer — the answer to the problem.
standard output
PASSED
e92fd942a15030eb39b4cbc7f67182c5
train_004.jsonl
1481726100
Vladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions: the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are ck cards with number k on them in the subsequence, than for all pairs of integers the condition |ci - cj| ≤ 1 must hold. if there is at least one card with number x on it in the subsequence, then all cards with number x in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1, 1, 2, 2] satisfies this condition while the subsequence [1, 2, 2, 1] doesn't. Note that [1, 1, 2, 2] doesn't satisfy the first condition. Please help Vladik to find the length of the longest subsequence that satisfies both conditions.
256 megabytes
import java.io.*; import java.util.*; public class Main { static PrintWriter out; final static int INF = (int) 1e9; final static int MOD = (int) 1e9 + 7; final static long LINF = (long) 1e18; final static double PI = Math.acos(-1.0); final static double EPS = (double) 1e-9; static void solve() { int n = Input.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = Input.nextInt() - 1; } int[][][] nxt = new int[n][n + 1][8]; for (int[][] x : nxt) for (int[] y : x) Arrays.fill(y, n); for (int i = 0; i < n; i++) { int[] cnt = new int[8]; for (int k = 0; k < 8; k++) { nxt[i][0][k] = i - 1; } for (int j = i; j < n; j++) { cnt[a[j]]++; for (int k = 0; k < 8; k++) { nxt[i][cnt[k]][k] = Math.min(nxt[i][cnt[k]][k], j); } } } int ans = 0; for (int k = 0; k <= n; k++) { int[][] dp = new int[n + 1][1 << 8]; for (int[] x : dp) Arrays.fill(x, -INF); dp[0][0] = 0; for (int i = 0; i < n; i++) { for (int msk = 0; msk < (1 << 8); msk++) if (dp[i][msk] >= 0) { for (int j = 0; j < 8; j++) { if (((msk >> j) & 1) == 0) { int nmsk = msk ^ (1 << j); int ni = nxt[i][k][j]; if (ni < n) { dp[ni + 1][nmsk] = Math.max(dp[ni + 1][nmsk], dp[i][msk] + k); } if (k < n) { ni = nxt[i][k + 1][j]; if (ni < n) { dp[ni + 1][nmsk] = Math.max(dp[ni + 1][nmsk], dp[i][msk] + k + 1); } } } } } } for (int i = 0; i <= n; i++) { ans = Math.max(ans, dp[i][(1 << 8) - 1]); } } out.println(ans); } public static void main(String[] args) { try { out = new PrintWriter(System.out); //out = new PrintWriter(new FileWriter("a.out")); } catch (Exception ex) { } long stime = System.currentTimeMillis(); solve(); if (System.getProperty("ONLINE_JUDGE") == null) { out.println("\nTime elapsed: " + (System.currentTimeMillis() - stime) + "ms"); } out.close(); } static class Input { static StringTokenizer token = null; static BufferedReader in; static { try { if (System.getProperty("ONLINE_JUDGE") == null) { in = new BufferedReader(new FileReader("in.txt")); } else { in = new BufferedReader(new InputStreamReader(System.in)); } } catch (Exception ex) { } } static int nextInt() { return Integer.parseInt(nextString()); } static long nextLong() { return Long.parseLong(nextString()); } static double nextDouble() { return Double.parseDouble(nextString()); } static String nextString() { try { while (token == null || !token.hasMoreTokens()) { token = new StringTokenizer(in.readLine()); } } catch (IOException e) { } return token.nextToken(); } } }
Java
["3\n1 1 1", "8\n8 7 6 5 4 3 2 1", "24\n1 8 1 2 8 2 3 8 3 4 8 4 5 8 5 6 8 6 7 8 7 8 8 8"]
2 seconds
["1", "8", "17"]
NoteIn the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition.
Java 8
standard input
[ "dp", "binary search", "bitmasks", "brute force" ]
a0a4caebc8e2ca87e30f33971bff981d
The first line contains single integer n (1 ≤ n ≤ 1000) — the number of cards in Vladik's sequence. The second line contains the sequence of n positive integers not exceeding 8 — the description of Vladik's sequence.
2,200
Print single integer — the length of the longest subsequence of Vladik's sequence that satisfies both conditions.
standard output
PASSED
36eaf1e865edd05334c6bc642023efab
train_004.jsonl
1481726100
Vladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions: the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are ck cards with number k on them in the subsequence, than for all pairs of integers the condition |ci - cj| ≤ 1 must hold. if there is at least one card with number x on it in the subsequence, then all cards with number x in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1, 1, 2, 2] satisfies this condition while the subsequence [1, 2, 2, 1] doesn't. Note that [1, 1, 2, 2] doesn't satisfy the first condition. Please help Vladik to find the length of the longest subsequence that satisfies both conditions.
256 megabytes
//package round384; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class E { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); for(int i = 0;i < n;i++){ a[i]--; } int K = 8; int[][] reach = new int[n][n+1]; for(int i = 0;i < n;i++)Arrays.fill(reach[i], n); for(int i = n-1;i >= 0;i--){ for(int j = i+1;j < n;j++){ if(a[j] == a[i]){ for(int k = 1;k < n;k++){ reach[i][k+1] = reach[j][k]; } break; } } reach[i][1] = i; } int max = 0; for(int base = 1;base*K <= n;base++){ int[][] dp = new int[n+1][1<<K]; for(int i = 1;i < 1<<K;i++){ for(int j = 0;j <= n;j++)dp[j][i] = Integer.MIN_VALUE / 10; } for(int i = n-1;i >= 0;i--){ for(int j = 0;j < 1<<K;j++){ dp[i][j] = dp[i+1][j]; } { int r = reach[i][base]; if(r < n){ for(int j = 0;j < 1<<K;j++){ if(j<<~a[i]>=0){ dp[i][j|1<<a[i]] = Math.max(dp[i][j|1<<a[i]], dp[r+1][j] + base); } } } } { int r = reach[i][base+1]; if(r < n){ for(int j = 0;j < 1<<K;j++){ if(j<<~a[i]>=0){ dp[i][j|1<<a[i]] = Math.max(dp[i][j|1<<a[i]], dp[r+1][j] + base+1); } } } } } max = Math.max(max, dp[0][(1<<K)-1]); } max = Math.max(max, (int)Arrays.stream(a).distinct().count()); out.println(max); } void run() throws Exception { // int n = 1000, m = 99999; // Random gen = new Random(); // StringBuilder sb = new StringBuilder(); // sb.append(n + " "); // for (int i = 0; i < n; i++) { // sb.append(gen.nextInt(8)+1 + " "); // } // INPUT = sb.toString(); is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new E().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3\n1 1 1", "8\n8 7 6 5 4 3 2 1", "24\n1 8 1 2 8 2 3 8 3 4 8 4 5 8 5 6 8 6 7 8 7 8 8 8"]
2 seconds
["1", "8", "17"]
NoteIn the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition.
Java 8
standard input
[ "dp", "binary search", "bitmasks", "brute force" ]
a0a4caebc8e2ca87e30f33971bff981d
The first line contains single integer n (1 ≤ n ≤ 1000) — the number of cards in Vladik's sequence. The second line contains the sequence of n positive integers not exceeding 8 — the description of Vladik's sequence.
2,200
Print single integer — the length of the longest subsequence of Vladik's sequence that satisfies both conditions.
standard output
PASSED
21433aef07d25b5b711cde84e5fbf438
train_004.jsonl
1481726100
Vladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions: the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are ck cards with number k on them in the subsequence, than for all pairs of integers the condition |ci - cj| ≤ 1 must hold. if there is at least one card with number x on it in the subsequence, then all cards with number x in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1, 1, 2, 2] satisfies this condition while the subsequence [1, 2, 2, 1] doesn't. Note that [1, 1, 2, 2] doesn't satisfy the first condition. Please help Vladik to find the length of the longest subsequence that satisfies both conditions.
256 megabytes
import java.io.*; import java.util.*; public final class vladik_and_cards { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static Random rnd=new Random(); static int[][][] val; static int[][] dp; static int[] a; static int maxn=128,n; static boolean[] v; static void clear() { dp=new int[n][1<<8]; for(int i=0;i<n;i++) { for(int j=0;j<(1<<8);j++) { dp[i][j]=-1; } } } static int solve(int idx,int mask,int curr) { if(idx>=n) { return (mask==255?0:-10000); } if(dp[idx][mask]!=-1) { return dp[idx][mask]; } else { int max=solve(idx+1,mask,curr); for(int i=0;i<8;i++) { if((mask&(1<<i))==0) { if(val[i][curr][idx]!=-1) { max=Math.max(max,curr+solve(val[i][curr][idx]+1,mask|(1<<i),curr)); } if(val[i][curr-1][idx]!=-1) { max=Math.max(max,curr-1+solve(val[i][curr-1][idx]+1,mask|(1<<i),curr)); } } } dp[idx][mask]=max;return max; } } public static void main(String args[]) throws Exception { n=sc.nextInt();a=new int[n];val=new int[8][maxn][n];v=new boolean[8];int max=0; for(int i=0;i<n;i++) { a[i]=sc.nextInt()-1; if(!v[a[i]]) { v[a[i]]=true;max++; } } for(int i=0;i<8;i++) { for(int j=0;j<maxn;j++) { for(int k=0;k<n;k++) { val[i][j][k]=-1; } } } for(int i=0;i<8;i++) { for(int j=0;j<n;j++) { int curr=1; for(int k=j;k<n;k++) { if(curr>=maxn) { break; } if(a[k]==i) { val[i][curr++][j]=k; } } } } /* for(int i=0;i<8;i++) { for(int j=0;j<maxn;j++) { for(int k=0;k<n;k++) { System.out.println(i+" "+j+" "+k+" "+val[i][j][k]); } } } */ for(int i=2;i<128;i++) { clear();max=Math.max(max,solve(0,0,i)); } out.println(max);out.close(); } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["3\n1 1 1", "8\n8 7 6 5 4 3 2 1", "24\n1 8 1 2 8 2 3 8 3 4 8 4 5 8 5 6 8 6 7 8 7 8 8 8"]
2 seconds
["1", "8", "17"]
NoteIn the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition.
Java 8
standard input
[ "dp", "binary search", "bitmasks", "brute force" ]
a0a4caebc8e2ca87e30f33971bff981d
The first line contains single integer n (1 ≤ n ≤ 1000) — the number of cards in Vladik's sequence. The second line contains the sequence of n positive integers not exceeding 8 — the description of Vladik's sequence.
2,200
Print single integer — the length of the longest subsequence of Vladik's sequence that satisfies both conditions.
standard output
PASSED
1cd46a569b38ce69cd78fbdcb0515088
train_004.jsonl
1481726100
Vladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions: the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are ck cards with number k on them in the subsequence, than for all pairs of integers the condition |ci - cj| ≤ 1 must hold. if there is at least one card with number x on it in the subsequence, then all cards with number x in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1, 1, 2, 2] satisfies this condition while the subsequence [1, 2, 2, 1] doesn't. Note that [1, 1, 2, 2] doesn't satisfy the first condition. Please help Vladik to find the length of the longest subsequence that satisfies both conditions.
256 megabytes
import java.util.*; public class ProE { static int n,ans,l,r,mid; static Pair p; static int[] aa=new int[1005]; static int[] cc=new int[1005]; static int[] bb=new int[10]; static int[][] next=new int[1005][10]; static int[][] mm=new int[10][1005]; static int[][] dp=new int[1005][300]; static int[][] vis=new int[1005][300]; static Queue<Pair> qq=new PriorityQueue<Pair>(); static class Pair implements Comparable<Pair> { int id,s; Pair(int a,int b) { id=a;s=b; } public int compareTo(Pair p) { return id-p.id; } } static boolean judge(int x) { int y=x/8,z,u,s; qq.clear(); qq.add(new Pair(0,0)); for(int i=0;i<=n;i++) for(int j=0;j<256;j++) { vis[i][j]=dp[i][j]=0; } while(!qq.isEmpty()) { p=qq.poll(); if(vis[p.id][p.s]==1) continue; vis[p.id][p.s]=1; for(int i=0;i<8;i++) { if((p.s&(1<<i))>0) continue; z=next[p.id][i+1];s=p.s|(1<<i); if(cc[z]+y>bb[i+1]) continue; u=mm[i+1][cc[z]+y-1]; dp[u][s]=Math.max(dp[u][s],dp[p.id][p.s]+y); qq.add(new Pair(u,s)); if(cc[z]+y+1>bb[i+1]) continue; u=mm[i+1][cc[z]+y]; dp[u][s]=Math.max(dp[u][s],dp[p.id][p.s]+y+1); qq.add(new Pair(u,s)); } } for(int i=1;i<=n;i++) if(dp[i][255]>=x) return true; return false; } public static void main(String[] args) { Scanner in=new Scanner(System.in); n=in.nextInt(); for(int i=1;i<=n;i++) aa[i]=in.nextInt(); Arrays.fill(bb,n+1); for(int i=n;i>=0;i--) { for(int j=1;j<=8;j++) next[i][j]=bb[j]; bb[aa[i]]=i; } Arrays.fill(bb,0); for(int i=1;i<=n;i++) { mm[aa[i]][bb[aa[i]]]=i; cc[i]=bb[aa[i]]++; } cc[n+1]=n+1; l=9;r=n;ans=-1; while(l<=r) { mid=(l+r)/2; if(judge(mid)) { ans=mid;l=mid+1;} else r=mid-1; } if(ans==-1) { ans=0; for(int i=1;i<=8;i++) if(bb[i]>0) ans++; } System.out.println(ans); } }
Java
["3\n1 1 1", "8\n8 7 6 5 4 3 2 1", "24\n1 8 1 2 8 2 3 8 3 4 8 4 5 8 5 6 8 6 7 8 7 8 8 8"]
2 seconds
["1", "8", "17"]
NoteIn the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition.
Java 8
standard input
[ "dp", "binary search", "bitmasks", "brute force" ]
a0a4caebc8e2ca87e30f33971bff981d
The first line contains single integer n (1 ≤ n ≤ 1000) — the number of cards in Vladik's sequence. The second line contains the sequence of n positive integers not exceeding 8 — the description of Vladik's sequence.
2,200
Print single integer — the length of the longest subsequence of Vladik's sequence that satisfies both conditions.
standard output
PASSED
47545182e33c91565334e8a1b43c20e1
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.util.*; public final class Snowman { public static void main(String[] args) { Scanner br=new Scanner(System.in); int n=br.nextInt(); int ans=0; int[] a=new int[n]; TreeSet<Man>ts=new TreeSet<Man>(); for(int i=0;i<n;i++) a[i]=br.nextInt(); Arrays.sort(a); int temp,c; for(int i=0;i<n;) { temp=a[i]; c=0; while(i<n && temp==a[i]) { i++; c++; } ts.add(new Man(temp,c)); } StringBuilder s=new StringBuilder(""); int[] k=new int[3]; while(true && ts.size()>=3) { Man m1=ts.pollLast(); Man m2=ts.pollLast(); Man m3=ts.pollLast(); if(m1.f>0 && m2.f>0 && m3.f>0) { ans++; k[0]=m1.n; k[1]=m2.n; k[2]=m3.n; Arrays.sort(k); s.append(k[2]+" "+k[1]+" "+k[0]+"\n"); } else break; ts.add(new Man(m1.n,m1.f-1)); ts.add(new Man(m2.n,m2.f-1)); ts.add(new Man(m3.n,m3.f-1)); } System.out.println(ans+"\n"+s); } } class Man implements Comparable<Man> { int n,f; public Man(int n,int f) { this.n=n; this.f=f; } public int compareTo(Man that) { if (this.f-that.f==0) return this.n-that.n; return this.f-that.f; } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
212b0b4dc5efc0a71aed3720f6f6d393
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.PriorityQueue; import java.util.StringTokenizer; public class NewYearSnowmen { static Ball a,b,c; public static void sort() { Ball temp; if (a.r>b.r) { temp = a; a = b; b = temp; } if (b.r>c.r) { temp = c; c = b; b = temp; } if (a.r>b.r) { temp = a; a = b; b = temp; } } 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()); st = new StringTokenizer(br.readLine()); HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for (int i=0;i<n;i++) { int r = Integer.parseInt(st.nextToken()); if (!hm.containsKey(r)) hm.put(r, 1); else hm.put(r, hm.get(r)+1); } PriorityQueue<Ball> q = new PriorityQueue<Ball>(); for(Map.Entry<Integer, Integer> entry : hm.entrySet()) { int key = entry.getKey(); int value = entry.getValue(); q.add(new Ball(key,value)); } int count = 0; StringBuilder sb = new StringBuilder(); while (q.size()>=3) { a = q.poll(); b = q.poll(); c = q.poll(); sort(); sb.append(c.r+" "+b.r+" "+a.r+"\n"); a.occ--; b.occ--; c.occ--; if (a.occ>0) q.add(a); if (b.occ>0) q.add(b); if (c.occ>0) q.add(c); count++; // System.out.println("HI"); } System.out.println(count); System.out.println(sb); } static class Ball implements Comparable { int r; int occ; public Ball(int r,int occ) { this.r = r; this.occ = occ; } @Override public int compareTo(Object o) { Ball b = (Ball) o; return b.occ-this.occ; } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
aeca1cadda529e79e3e02353cfc904e0
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.*; import java.util.*; public class B_New_Year_Snowmen { public static void main(String[] args) throws Exception { Scan in = new Scan(); StringBuilder out = new StringBuilder(); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); List<Ball> list = new ArrayList<>(); int best = -1; for (int i = 0; i < n; i++) { if (i == n - 1 || a[i] != a[i + 1]) { list.add(new Ball(a[i], (i - best))); best = i; } } PriorityQueue<Ball> q = new PriorityQueue<>(); q.addAll(list); List<snowMan> ans = new ArrayList<snowMan>(); Ball b1, b2, b3; while (q.size() >= 3) { b1 = q.poll(); b2 = q.poll(); b3 = q.poll(); ans.add(new snowMan(b1.ball, b2.ball, b3.ball)); for (Ball b : new Ball[]{b1, b2, b3}) { --b.cnt; if (b.cnt > 0) { q.add(b); } } } out.append(ans.size() + "\n"); for (snowMan sm : ans) { out.append(sm.sm3 + " " + sm.sm2 + " " + sm.sm1 + "\n"); } System.out.print(out); } static class snowMan { final int sm1, sm2, sm3; public snowMan(int sm1, int sm2, int sm3) { if (sm1 > sm2) { int tmp = 0; tmp = sm1; sm1 = sm2; sm2 = tmp; } if (sm1 > sm3) { int tmp = 0; tmp = sm1; sm1 = sm3; sm3 = tmp; } if (sm2 > sm3) { int tmp = 0; tmp = sm2; sm2 = sm3; sm3 = tmp; } this.sm1 = sm1; this.sm2 = sm2; this.sm3 = sm3; } } static class Ball implements Comparable<Ball> { int ball, cnt; public Ball(int ball, int cnt) { this.ball = ball; this.cnt = cnt; } public int compareTo(Ball b) { return b.cnt - cnt; } } static class Scan { BufferedReader br; StringTokenizer st; Scan() { // To read from the standard input br = new BufferedReader(new InputStreamReader(System.in)); } // You can add a constructor to read from a file ///// String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } //You can add nextDouble() etc... boolean hasNext() throws IOException { // if input is terminated by EOF String s = br.readLine(); if (s == null) return false; st = new StringTokenizer(s); return true; } } //end FastReader }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
175a1972611b21993c74417d8ab1dad9
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static boolean eof = false; static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) throws IOException { tokenizer = null; // reader = new BufferedReader(new FileReader("ideal.in")); // writer = new PrintWriter(new FileWriter("ideal.out")); reader = new BufferedReader(new InputStreamReader(System.in, "ISO-8859-1")); writer = new PrintWriter(System.out); banana(); reader.close(); writer.close(); } static boolean isDebug = true; static Map<Integer, P> mapka = new HashMap<Integer, P>(); static class P { int data, count; public P(int data) { this.data = data; count = 1; } } static void banana() throws IOException { int n = nextInt(); TreeSet<P> pq = new TreeSet<P>(new Comparator<P>() { @Override public int compare(P a, P b) { if (a.count == b.count) return a.data - b.data; return b.count - a.count; } }); for (int i = 0; i < n; ++i) { int cur = nextInt(); if (mapka.containsKey(cur)) { P r = mapka.get(cur); pq.remove(r); r.count++; pq.add(r); } else { P c = new P(cur); mapka.put(cur, c); pq.add(c); } } List<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>(); int counter = 0; while (pq.size() > 2) { ++counter; P cur1 = pq.pollFirst(); P cur2 = pq.pollFirst(); P cur3 = pq.pollFirst(); cur1.count--; cur2.count--; cur3.count--; ArrayList<Integer> to; a.add(to = new ArrayList<Integer>()); if (cur1.count != 0) pq.add(cur1); if (cur2.count != 0) pq.add(cur2); if (cur3.count != 0) pq.add(cur3); to.add(cur1.data); to.add(cur2.data); to.add(cur3.data); Collections.sort(to); } writer.println(counter); for (int i = 0; i < counter; ++i) { writer.println(a.get(i).get(2) + " " + a.get(i).get(1) + " " + a.get(i).get(0)); } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
bc1d3b3ef90a6c33109d05afb146e11d
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int max = (int) (1e5 + 1); int n = sc.nextInt(); int[] r = sc.nextIntArray(n); int ans = 0; StringBuilder sb = new StringBuilder(); HashMap<Integer, Integer> occ = new HashMap<>(); for (int x : r) occ.put(x, occ.getOrDefault(x, 0) + 1); Queue<Integer> adjList[] = new LinkedList[max]; for (int i = 1; i < max; i++) adjList[i] = new LinkedList<>(); for (int x : occ.keySet()) adjList[occ.get(x)].add(x); TreeSet<Integer> pq = new TreeSet<>(); for (int i = max - 1; i > 0; i--) if (!adjList[i].isEmpty()) pq.add(i); while (!pq.isEmpty()) { int cur = pq.last(); while (!adjList[cur].isEmpty()) { int a = adjList[cur].remove(); if (adjList[cur].isEmpty()) pq.remove(cur); if (pq.isEmpty()) break; Integer next = pq.last(); int b = adjList[next].remove(); if (adjList[next].isEmpty()) pq.remove(next); if (pq.isEmpty()) break; Integer nextnext = pq.last(); int c = adjList[nextnext].remove(); if (adjList[nextnext].isEmpty()) pq.remove(nextnext); ans++; sb.append(putInOrder(a, b, c)); if (cur != 1) { adjList[cur - 1].add(a); pq.add(cur - 1); } if (next != 1) { adjList[next - 1].add(b); pq.add(next - 1); } if (nextnext != 1) { adjList[nextnext - 1].add(c); pq.add(nextnext - 1); } } } out.println(ans); out.println(sb); out.close(); out.flush(); } static String putInOrder(int a, int b, int c) { int[] tmp = {a, b, c}; Arrays.sort(tmp); return tmp[2] + " " + tmp[1] + " " + tmp[0] + "\n"; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
c0087d5e71f99291dfabb8eda3986088
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.HashMap; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int max = (int) (1e5 + 1); int n = sc.nextInt(); int[] r = sc.nextIntArray(n); int ans = 0; StringBuilder sb = new StringBuilder(); HashMap<Integer, Integer> occ = new HashMap<>(); for (int x : r) occ.put(x, occ.getOrDefault(x, 0) + 1); PriorityQueue<Tuple> pq = new PriorityQueue<>(); for (int x : occ.keySet()) pq.add(new Tuple(x, occ.get(x))); while (pq.size() >= 3) { ans++; Tuple a = pq.remove(); Tuple b = pq.remove(); Tuple c = pq.remove(); sb.append(putInOrder(a.val, b.val, c.val)); a.decrement(); b.decrement(); c.decrement(); if (a.freq > 0) pq.add(a); if (b.freq > 0) pq.add(b); if (c.freq > 0) pq.add(c); } out.println(ans); out.println(sb); out.close(); out.flush(); } static String putInOrder(int a, int b, int c) { int[] tmp = {a, b, c}; Arrays.sort(tmp); return tmp[2] + " " + tmp[1] + " " + tmp[0] + "\n"; } static class Tuple implements Comparable<Tuple> { int val, freq; public Tuple(int val, int freq) { this.val = val; this.freq = freq; } @Override public int compareTo(Tuple o) { return freq == o.freq ? o.val - val : o.freq - freq; } void decrement() { freq--; } @Override public String toString() { return "Tuple{" + "val=" + val + ", freq=" + freq + '}'; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
03ab62a8ecfcd461abd444703f1d07ee
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.PriorityQueue; import java.util.StringTokenizer; import javafx.util.Pair; public class Solve7 { public static void main(String[] args) throws IOException { PrintWriter pw = new PrintWriter(System.out); new Solve7().solve(pw); pw.flush(); pw.close(); } public void solve(PrintWriter pw) throws IOException { FastReader sc = new FastReader(); int n = sc.nextInt(); HashMap<Integer, Integer> hm = new HashMap(); for (int i = 0; i < n; i++) { int x = sc.nextInt(); hm.put(x, hm.getOrDefault(x, 0) + 1); } Comparator<Pair<Integer, Integer>> cmp = new Comparator<Pair<Integer, Integer>>() { @Override public int compare(Pair<Integer, Integer> p1, Pair<Integer, Integer> p2) { return p2.getValue() - p1.getValue(); } }; PriorityQueue<Pair<Integer, Integer>> q = new PriorityQueue(cmp); for (Map.Entry<Integer, Integer> pair : hm.entrySet()) { q.add(new Pair(pair.getKey(), pair.getValue())); } int s = 0; StringBuilder sb = new StringBuilder(); while (q.size() > 2) { Pair<Integer, Integer>[] temp = new Pair[3]; Integer[] b = new Integer[3]; for (int i = 0; i < 3; i++) { temp[i] = q.poll(); temp[i] = new Pair(temp[i].getKey(), temp[i].getValue() - 1); b[i] = temp[i].getKey(); } ++s; Arrays.sort(b); sb.append(b[2]).append(" ").append(b[1]).append(" ").append(b[0]).append("\n"); for (int i = 0; i < 3; i++) { if (!temp[i].getValue().equals(0)) { q.add(temp[i]); } } } pw.println(s); if (s != 0) { pw.println(sb.toString().trim()); } } static class FastReader { StringTokenizer st; BufferedReader br; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (Exception e) { } } public String next() { if (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } } 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() throws IOException { return br.readLine(); } public boolean hasNext() throws IOException { if (st != null && st.hasMoreTokens()) { return true; } String s = br.readLine(); if (s == null || s.isEmpty()) { return false; } st = new StringTokenizer(s); return true; } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
94531376f64ee7f21109154ac4594732
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Map.Entry; import java.util.Arrays; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeMap; public class P { static class Pair implements Comparable<Pair> { int v, count; Pair(int i, int j) { v = i; count = j; } @Override public int compareTo(Pair o) { if (count == o.count) return o.v - v; return o.count - count; } } static int[] getSorted(int x, int y, int z) { int[] a = new int[3]; a[0] = x; a[1] = y; a[2] = z; Arrays.sort(a); return a; } public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); Integer[] a = new Integer[N]; TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); for (int i = 0; i < N; ++i) { Integer occ = map.get(a[i] = sc.nextInt()); if (occ == null) occ = 0; map.put(a[i], occ + 1); } PriorityQueue<Pair> pq = new PriorityQueue<>(); int ans = 0; StringBuilder sb = new StringBuilder(); for (Entry<Integer, Integer> entry : map.entrySet()) pq.add(new Pair(entry.getKey(), entry.getValue())); while (pq.size() >= 3) { Pair f = pq.remove(), s = pq.remove(), th = pq.remove(); int[] sorted = getSorted(f.v, s.v, th.v); ans++; sb.append(sorted[2] + " " + sorted[1] + " " + sorted[0]); sb.append("\n"); if (f.count - 1 > 0) { pq.add(new Pair(f.v, f.count - 1)); } if (s.count - 1 > 0) { pq.add(new Pair(s.v, s.count - 1)); } if (th.count - 1 > 0) { pq.add(new Pair(th.v, th.count - 1)); } } out.println(ans); out.println(sb); out.flush(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
cb8897b688368dbb55bd3be9082b679f
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Map.Entry; import java.util.Arrays; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeMap; public class P { static class Pair implements Comparable<Pair> { int v, count; Pair(int i, int j) { v = i; count = j; } @Override public int compareTo(Pair o) { if (count == o.count) return o.v - v; return o.count - count; } } static int[] getSorted(int x, int y, int z) { int[] a = new int[3]; a[0] = x; a[1] = y; a[2] = z; Arrays.sort(a); return a; } public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); Integer[] a = new Integer[N]; TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); for (int i = 0; i < N; ++i) { Integer occ = map.get(a[i] = sc.nextInt()); if (occ == null) occ = 0; map.put(a[i], occ + 1); } PriorityQueue<Pair> pq = new PriorityQueue<>(); int ans = 0; StringBuilder sb = new StringBuilder(); for (Entry<Integer, Integer> entry : map.entrySet()) pq.add(new Pair(entry.getKey(), entry.getValue())); while (pq.size() >= 3) { Pair f = pq.remove(), s = pq.remove(), th = pq.remove(); int[] sorted = getSorted(f.v, s.v, th.v); ans++; sb.append(sorted[2] + " " + sorted[1] + " " + sorted[0]); sb.append("\n"); if (f.count - 1 > 0) { pq.add(new Pair(f.v, f.count - 1)); } if (s.count - 1 > 0) { pq.add(new Pair(s.v, s.count - 1)); } if (th.count - 1 > 0) { pq.add(new Pair(th.v, th.count - 1)); } } out.println(ans); out.println(sb); out.flush(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
6fa0934de5a8bd57191e180a1c2818df
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Map.Entry; import java.util.Arrays; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeMap; public class P { static class Pair implements Comparable<Pair> { int v, count; Pair(int i, int j) { v = i; count = j; } @Override public int compareTo(Pair o) { if (count == o.count) return o.v - v; return o.count - count; } } static int[] getSorted(int x, int y, int z) { int[] a = new int[3]; a[0] = x; a[1] = y; a[2] = z; Arrays.sort(a); return a; } public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); Integer[] a = new Integer[N]; TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); for (int i = 0; i < N; ++i) { Integer occ = map.get(a[i] = sc.nextInt()); if (occ == null) occ = 0; map.put(a[i], occ + 1); } PriorityQueue<Pair> pq = new PriorityQueue<>(); int ans = 0; StringBuilder sb = new StringBuilder(); for (Entry<Integer, Integer> entry : map.entrySet()) pq.add(new Pair(entry.getKey(), entry.getValue())); while (pq.size() >= 3) { Pair f = pq.remove(), s = pq.remove(), th = pq.remove(); int[] sorted = getSorted(f.v, s.v, th.v); ans++; sb.append(sorted[2] + " " + sorted[1] + " " + sorted[0]); sb.append("\n"); if (f.count - 1 > 0) { pq.add(new Pair(f.v, f.count - 1)); } if (s.count - 1 > 0) { pq.add(new Pair(s.v, s.count - 1)); } if (th.count - 1 > 0) { pq.add(new Pair(th.v, th.count - 1)); } } out.println(ans); out.println(sb); out.flush(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
c19f69f3170da08895477efe3584365b
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
//package sheet_C; import java.io.*; import java.util.*; import java.util.Map.Entry; public class NewYearSnowmen { public static void main(String[]args)throws Throwable{ PrintWriter pw=new PrintWriter(System.out,true); MyScanner sc=new MyScanner(); int n=sc.nextInt(); TreeMap<Integer, Integer> map=new TreeMap<Integer, Integer>(); for(int i=0;i<n;i++){ int x=sc.nextInt(); if(map.containsKey(x)) map.put(x,map.get(x)+1); else map.put(x, 1); } PriorityQueue<pair> q=new PriorityQueue<pair>(); for(Entry<Integer, Integer> e : map.entrySet()) q.add(new pair(e.getKey(), e.getValue())); ArrayList<Triple> ans=new ArrayList<Triple>(); while(q.size()>=3){ pair x=q.poll(); pair y=q.poll(); pair z=q.poll(); int [] a={x.x,y.x,z.x}; Arrays.sort(a); ans.add(new Triple(a[2],a[1],a[0])); if(--x.cnt>0) q.add(x); if(--y.cnt>0) q.add(y); if(--z.cnt>0) q.add(z); } pw.println(ans.size()); for(int i=0;i<ans.size();i++) pw.println(ans.get(i)); pw.flush(); pw.close(); } static class pair implements Comparable<pair>{ int x,cnt; pair(int x,int c){ this.x=x; cnt=c; } public int compareTo(pair o) { return o.cnt-this.cnt; } } static class Triple{ int x,y,z; Triple(int a,int b,int c){x=a;y=b;z=c;} public String toString(){ return x+" "+y+" "+z; } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
13aabee328a40fcbea1a48e6c8554d41
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.util.StringTokenizer; import java.util.Collections; import java.util.Collection; import java.util.Set; import java.util.HashSet; import java.util.Map; import java.util.HashMap; import java.util.Arrays; import java.util.ArrayList; import java.util.Queue; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Stack; import java.util.Vector; import java.util.Hashtable; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.IOException; import java.io.FileReader; import java.math.BigInteger; public class Main { static PrintWriter writer; static StringTokenizer sz; static BufferedReader reader; public static void main(String[] args) throws Exception { declare(); int n = Integer.parseInt(reader.readLine()); ht = new Hashtable<Integer,Integer>(); int v; count = 0; keys = new ArrayList<Integer>(); readLine(); for (int i=1;i <= n;++i) { v = readInt(); if (ht.containsKey(v)) { ht.put(v, ht.get(v) + 1); } else { ht.put(v, 1); keys.add(v); ++count; } } sb = new StringBuilder(); ans = 0; pq = new PriorityQueue<Val>(); for (int i=0;i < count;++i) pq.add(new Val(v = keys.get(i), ht.get(v))); while (count > 2) test(); writer.println(ans); writer.println(sb); close(); } static class Val implements Comparable<Val> { int val,freq; public Val(int v, int f) { val = v; freq = f; } @Override public int compareTo(Main.Val o) { if (freq != o.freq) return o.freq - freq; return o.val - val; } } static StringBuilder sb; static int count,ans; static ArrayList<Integer> keys; static Hashtable<Integer,Integer> ht; static PriorityQueue<Val> pq; private static void test() { ArrayList<Integer> line = new ArrayList<Integer>(); ArrayList<Val> temp = new ArrayList<Val>(); int v,freq; Val obj; for (int i=0;i < 3;++i) { obj = pq.poll(); v = obj.val; freq = obj.freq; line.add(v); if (freq == 1) --count; else temp.add(new Val(v, freq - 1)); } Collections.sort(line); ++ans; for (int i=2;i > -1;--i) sb.append(line.get(i) + " "); for (Val el:temp) pq.add(el); sb.append("\n"); } private static String readString() throws IOException { return reader.readLine(); } private static void readLine() throws IOException { sz = new StringTokenizer(reader.readLine()); } private static int readInt() throws IOException { return Integer.parseInt(sz.nextToken()); } private static long readLong() throws IOException { return Long.parseLong(sz.nextToken()); } private static void declare() { writer = new PrintWriter(System.out); reader = new BufferedReader( new InputStreamReader(System.in)); } private static void declareFile() throws IOException { writer = new PrintWriter("output.txt"); reader = new BufferedReader( new FileReader("input.txt")); } private static void close() throws IOException { writer.flush(); writer.close(); reader.close(); } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
2a08492fa4e49834b4bb8492c3703757
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.PriorityQueue; public class Main { public static int[] readInts(String cad) { String read[] = cad.split(" "); int res[] = new int[read.length]; for (int i = 0; i < read.length; i++) { res[i] = Integer.parseInt(read[i]); } return res; } public static long[] readLongs(String cad) { String read[] = cad.split(" "); long res[] = new long[read.length]; for (int i = 0; i < read.length; i++) { res[i] = Long.parseLong(read[i]); } return res; } static void printArrayInt(int[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) System.out.print(" "); System.out.print(array[i]); } System.out.println(); } static void printMatrixInt(int[][] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[0].length; j++) { if (j > 0) System.out.print(" "); System.out.print(array[i][j]); } System.out.println(); } } public static int max(int arr[]) { int max = arr[0]; for (int i = 1; i < arr.length; i++) { max = Math.max(max, arr[i]); } return max; } public static int min(int arr[]) { int min = arr[0]; for (int i = 1; i < arr.length; i++) { min = Math.min(min, arr[i]); } return min; } public static class Node implements Comparable<Node> { int number; int c; public Node(int number, int c) { this.number = number; this.c = c; } @Override public int compareTo(Node o) { return o.c - c; } } public static void main(String[] args) throws IOException { BufferedReader in; StringBuilder out = new StringBuilder(); File f = new File("entrada"); if (f.exists()) { in = new BufferedReader(new FileReader(f)); } else in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); int v[] = readInts(in.readLine()); ArrayList<Node> snow = new ArrayList<Node>(v.length); HashMap<Integer, Integer> tabla = new HashMap<Integer, Integer>(); PriorityQueue<Node> q = new PriorityQueue<Node>(); int k = 0; if (n < 3) { System.out.println(0); return; } else { for (int i = 0; i < v.length; i++) { int date; if (tabla.containsKey(v[i])) { date = tabla.get(v[i]); snow.get(date).c++; } else { tabla.put(v[i], k++); snow.add(new Node(v[i], 1)); } } for (int i = 0; i < snow.size(); i++) { q.add(snow.get(i)); } Node s; Node s2; Node s3; int cont = 0; while (q.size() >= 3) { s = q.poll(); s2 = q.poll(); s3 = q.poll(); if (s.number > s2.number && s.number > s3.number) { if (s2.number > s3.number) out.append(s.number + " " + s2.number + " " + s3.number + "\n"); else out.append(s.number + " " + s3.number + " " + s2.number + "\n"); } else if (s2.number > s.number && s2.number > s3.number) { if (s3.number > s.number) out.append(s2.number + " " + s3.number + " " + s.number + "\n"); else out.append(s2.number + " " + s.number + " " + s3.number + "\n"); } else { if (s.number > s2.number) out.append(s3.number + " " + s.number + " " + s2.number + "\n"); else out.append(s3.number + " " + s2.number + " " + s.number + "\n"); } if (--s.c > 0) q.add(s); if (--s2.c > 0) q.add(s2); if (--s3.c > 0) q.add(s3); cont++; } System.out.println(cont); System.out.print(out); } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
0afcd9daf3a95d85a7fa3243ad134ec6
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
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.PriorityQueue; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Tarek */ 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); CNewYearSnowmen solver = new CNewYearSnowmen(); solver.solve(1, in, out); out.close(); } static class CNewYearSnowmen { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); PriorityQueue<ball> k = new PriorityQueue<ball>(); int[][] ans = new int[n][3]; int c = 0; for (int i = 0; i < n; ) { int j = i; while (j < n && a[j] == a[i]) { j++; } k.add(new ball(a[i], j - i)); i = j; } while (true) { if (k.size() < 3) break; ball t1 = k.poll(); ball t2 = k.poll(); ball t3 = k.poll(); ans[c][0] = t1.v; ans[c][1] = t2.v; ans[c][2] = t3.v; c++; t1.count--; t2.count--; t3.count--; if (t1.count > 0) k.add(t1); if (t2.count > 0) k.add(t2); if (t3.count > 0) k.add(t3); } out.println(c); for (int i = 0; i < c; i++) { Arrays.sort(ans[i]); out.println(ans[i][2] + " " + ans[i][1] + " " + ans[i][0]); } } } static class ball implements Comparable<ball> { int v; int count; public ball(int i, int j) { v = i; count = j; } public int compareTo(ball o) { return o.count - count; } } 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
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
42f93273f73c88e190fce15aaa89ec9e
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
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.PriorityQueue; import java.util.StringTokenizer; import java.util.HashMap; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); HashMap<Integer, Integer> r = new HashMap<>(); for (int i = 0; i < n; i++) { int cur = in.nextInt(); r.put(cur, r.getOrDefault(cur, 0) + 1); } PriorityQueue<ball> rLeft = new PriorityQueue<>((ball f, ball s) -> s.qty - f.qty); for (int key : r.keySet()) { rLeft.offer(new ball(key, r.get(key))); } ArrayList<Integer[]> ans = new ArrayList<>(); while (rLeft.size() >= 3) { ball b1 = rLeft.poll(); ball b2 = rLeft.poll(); ball b3 = rLeft.poll(); if (b1.qty > 1) { b1.qty--; rLeft.offer(b1); } if (b2.qty > 1) { b2.qty--; rLeft.offer(b2); } if (b3.qty > 1) { b3.qty--; rLeft.offer(b3); } Integer[] cur = new Integer[]{b1.r, b2.r, b3.r}; Arrays.sort(cur, (Integer f, Integer s) -> s - f); ans.add(cur); } out.println(ans.size()); for (Integer[] cur : ans) { for (int val : cur) { out.print(val + " "); } out.println(); } } class ball { int r; int qty; ball(int r1, int q) { r = r1; qty = q; } } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
df7da830c79ec546b5221cfac560c53c
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeMap; public class CF_140C { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); PrintWriter out = new PrintWriter(System.out); PriorityQueue<Integer>[] snow = new PriorityQueue[n / 3]; for (int i = 0; i < n / 3; i++) snow[i] = new PriorityQueue<>(); TreeMap<Integer, Integer> tm = new TreeMap<>(); for (int j = 0; j < n; j++) { int x = sc.nextInt(); Integer c = tm.get(x); if (c == null) c = 0; tm.put(x, c + 1); } PriorityQueue<pair> pq = new PriorityQueue<>(); for (Entry<Integer, Integer> e : tm.entrySet()) { int c = e.getValue(); int x = e.getKey(); pq.add(new pair(x, c)); } int count = 0; PriorityQueue<Integer>Elem = new PriorityQueue<>(); StringBuilder sb = new StringBuilder(); while (pq.size()>=3) { pair p1 = pq.poll(); pair p2 = pq.poll(); pair p3 = pq.poll(); Elem.add(-p1.v); Elem.add(-p2.v); Elem.add(-p3.v); sb.append(-Elem.poll() + " " + -Elem.poll() + " " + -Elem.poll()+'\n'); count++; p1.c--; p2.c--; p3.c--; if(p1.c>0) pq.add(p1); if(p2.c>0) pq.add(p2); if(p3.c>0) pq.add(p3); } out.println(count); out.print(sb); out.flush(); out.close(); } static class pair implements Comparable<pair> { int v, c; public pair(int a, int b) { v = a; c = b; } @Override public int compareTo(pair o) { return o.c - c; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String f) throws FileNotFoundException { br = new BufferedReader(new FileReader(f)); } 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(); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int[] nextIntArray1(int n) throws IOException { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } public int[] shuffle(int[] a, int n) { int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); int t = b[i]; b[i] = b[j]; b[j] = t; } return b; } public int[] nextIntArraySorted(int n) throws IOException { int[] a = nextIntArray(n); a = shuffle(a, n); Arrays.sort(a); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public long[] nextLongArray1(int n) throws IOException { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } public long[] nextLongArraySorted(int n) throws IOException { long[] a = nextLongArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); long t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); return a; } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
d00f8c742aeaa074d793a99776c8f45f
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; public class Main { public static void main(String[] args) throws InterruptedException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD task = new TaskD(); task.solve(in, out); out.close(); } static class TaskD { int n; TreeMap<Integer, Integer> cnt = new TreeMap<>(); public void solve(InputReader in, PrintWriter out) throws InterruptedException { n = in.nextInt(); for (int i = 0; i < n; i++) { int x = in.nextInt(); if (cnt.containsKey(x)) { int v = cnt.get(x); cnt.put(x, v+1); } else { cnt.put(x, 1); } } ArrayList<Integer> list = new ArrayList<>(); int low = 0, high = 100001; int ans = 0; while (low <= high) { list.clear(); int k = (low + high) / 2; int sum = 0; for (Map.Entry<Integer, Integer> ent : cnt.entrySet()) { sum += Math.min(k, ent.getValue()); } if (sum < 3 * k) { high = k - 1; } else { low = k + 1; ans = k; } } for (Map.Entry<Integer, Integer> ent : cnt.entrySet()) { for (int i = 0; i < ans && i < ent.getValue(); i++) { list.add(ent.getKey()); } } out.println(ans); boolean marked[] = new boolean[list.size()]; Arrays.fill(marked, false); int to = list.size() - 2 * ans; for (int i = 0; i < to; i++) { if (marked[i]) { continue; } int[] ar = new int[3]; ar[0] = list.get(i); ar[1] = list.get(i+ans); ar[2] = list.get(i+2*ans); Arrays.sort(ar); out.println(ar[2] + " " + ar[1] + " " + ar[0]); marked[i] = marked[i+ans] = marked[i+2*ans] = true; } } void addToArray(ArrayList ar, Number v) { if (ar == null) { ar = new ArrayList(); } ar.add(v); } } 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 char nextChar() {return next().charAt(0);} public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
909786eee6b5e62f26fc90651967db06
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
//package acc; import java.util.*; import java.io.*; public class ACC { //************Main*****************// static int sum=0; static List snow[]=new ArrayList[3]; static void fun(int x,int y,int z,int n){ int arr1[]=new int[3]; arr1[0]=x;arr1[1]=y;arr1[2]=z; Arrays.sort(arr1); sum+=n; while(n--!=0) { snow[0].add(arr1[0]); snow[1].add(arr1[1]); snow[2].add(arr1[2]); } } public static void main(String[] args) throws IOException { // PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); // Scanner in=new Scanner (System.in); InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); snow[0]=new ArrayList<>(); snow[1]=new ArrayList<>(); snow[2]=new ArrayList<>(); int n=in.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) arr[i]=in.nextInt(); Arrays.sort(arr); PriorityQueue<Pair> p=new PriorityQueue<>(); int x=1; for(int i=1;i<n;i++){ if(arr[i]!=arr[i-1]){ p.add(new Pair(-x,arr[i-1])); x=1; } else x++; } p.add(new Pair(-x,arr[n-1])); while(true){ if(p.size()<3) break; Pair y=p.poll(); Pair y1=p.poll(); Pair y2=p.poll(); if(y2.x>=0) break; fun(y.y,y1.y,y2.y,1); p.add(new Pair(y.x+1,y.y)); p.add(new Pair(y2.x+1,y2.y)); p.add(new Pair(y1.x+1,y1.y)); } out.println(sum); for(int i=0;i<sum;i++) out.println(snow[2].get(i)+" "+snow[1].get(i)+" "+snow[0].get(i)); out.close(); } } class Pair implements Comparable<Pair>{ int x,y; public Pair(int X,int Y){ super(); x=X; y=Y; } @Override public int compareTo(Pair p){ if((x)==(p.x)) return Integer.compare((y), (p.y)); return Integer.compare((x), (p.x)); } } 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
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
9c8707539dbaa84a9319fba7fc127f9a
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.*; import java.net.URL; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine(), " :"); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } class Obj implements Comparable<Obj> { int val; int cnt; public Obj(int val, int cnt) { this.val = val; this.cnt = cnt; } @Override public int compareTo(Obj o) { if (cnt != o.cnt) return o.cnt - cnt; return val - o.val; } } void solve() throws IOException { int n = readInt(); int[] a = readIntArray(n); Arrays.sort(a); PriorityQueue<Obj> pq = new PriorityQueue<>(); for (int i = 0; i < a.length; i++) { int j = i; while (j < a.length && a[i] == a[j]) j++; pq.add(new Obj(a[i], j - i)); i = j - 1; } ArrayList<String> list = new ArrayList<>(); while (pq.size() >= 3) { Obj a1 = pq.poll(); Obj a2 = pq.poll(); Obj a3 = pq.poll(); int[] res = {a1.val, a2.val, a3.val}; Arrays.sort(res); String s = ""; for (int i = 2; i >= 0; i--) { s += res[i] + " "; } list.add(s); a1.cnt--; a2.cnt--; a3.cnt--; if (a1.cnt > 0) pq.add(a1); if (a2.cnt > 0) pq.add(a2); if (a3.cnt > 0) pq.add(a3); } out.println(list.size()); for (String s : list) { out.println(s); } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
8f98970b131ce754e60d305805c01270
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Solution{ static class Answer{ int f; int s; int l; public Answer(int f,int s,int l){ this.f = f; this.s = s; this.l = l; } } static class Ball{ int r; int nb; int ind; public Ball(int r,int nb,int ind){ this.r = r; this.nb = nb; this.ind = ind; } } public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = Integer.parseInt(st.nextToken()); TreeMap<Integer,Integer> tm = new TreeMap<Integer,Integer>(); for(int i=0;i<n;i++){ if(!tm.containsKey(a[i])) tm.put(a[i],1); else { int num = tm.get(a[i]); tm.put(a[i],num+1); } } TreeSet<Ball> ts = new TreeSet<Ball>(new Comparator<Ball>(){ public int compare(Ball b1,Ball b2){ if(b1.nb-b2.nb!=0) return b1.nb-b2.nb; else if(b1.r-b2.r!=0) return b1.r-b2.r; else return b1.ind-b2.ind; } }); LinkedList<Answer> reponse = new LinkedList<Answer>(); TreeSet<Ball> l = new TreeSet<Ball>(new Comparator<Ball>(){ public int compare(Ball b1,Ball b2){ if(b2.r-b1.r!=0) return b2.r-b1.r; else if(b1.nb-b2.nb!=0) return b1.nb-b2.nb; else return b1.ind-b2.ind; } }); TreeSet<Ball> lp = new TreeSet<Ball>(new Comparator<Ball>(){ public int compare(Ball b1,Ball b2){ if(b2.r-b1.r!=0) return b2.r-b1.r; else if(b1.nb-b2.nb!=0) return b1.nb-b2.nb; else return b1.ind-b2.ind; } }); int ind = 0; for(Map.Entry<Integer,Integer> e:tm.entrySet()){ int r = e.getKey(); int nb = e.getValue(); ts.add(new Ball(r,nb,ind)); ind++; } LinkedList<Integer> swit = new LinkedList<Integer>(); while(!ts.isEmpty()){ while(!ts.isEmpty()){ l.add(ts.pollLast()); if(l.size()==3) break; } if(l.size()==3){ int min = 1; for(Ball b:l) swit.add(b.r); reponse.add(new Answer(swit.get(0),swit.get(1),swit.get(2))); swit.clear(); for(Ball b:l){ if(b.nb==min) continue; lp.add(new Ball(b.r,b.nb-min,b.ind)); } l.clear(); for(Ball b:lp) { ts.add(b); } lp.clear(); } } /* for(Map.Entry<Integer,Integer> e:tm.entrySet()){ int r = e.getKey(); int nb = e.getValue(); l.addFirst(new Ball(r,nb)); if(l.size()==3){ int min = n; for(Ball b:l){ min = (int) Math.min(min,b.nb); } for(int i=0;i<min;i++){ reponse.add(new Answer(l.get(0).r,l.get(1).r,l.get(2).r)); } for(Ball b:l){ if(b.nb==min) continue; lp.add(new Ball(b.r,b.nb-min)); } l.clear(); for(Ball b:lp) l.add(b); lp.clear(); } } */ out.println(reponse.size()); for(Answer rep : reponse){ out.println(rep.f+" "+rep.s+" "+rep.l); } out.flush(); } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
21a9099579fbee229b22a2e8f159cacd
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.PriorityQueue; import java.util.Scanner; import java.util.TreeMap; public class SnowMen { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); TreeMap<Integer, Integer> map = new TreeMap<>(); ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int x = sc.nextInt(); if (map.get(x) == null) { map.put(x, 1); list.add(x); } else { int y = map.get(x); map.put(x, y + 1); } } PriorityQueue<pair> pq = new PriorityQueue<>(); int count = 0; for (int i = 0; i < list.size(); i++) { int x = map.get(list.get(i)); pq.add(new pair(list.get(i), -x)); } StringBuilder sb = new StringBuilder(); while (pq.size() >= 3) { int[] array = new int[3]; pair p1 = pq.poll(); pair p2 = pq.poll(); pair p3 = pq.poll(); int x = -p3.y; array[0] = p1.x; array[1] = p2.x; array[2] = p3.x; p1.y++; p2.y++; p3.y++; if (p2.y < 0) pq.add(p2); if (p1.y < 0) pq.add(p1); if (p3.y < 0) pq.add(p3); Arrays.sort(array); count ++; sb.append(array[2] + " " + array[1] + " " + array[0] + "\n"); } System.out.println(count); System.out.print(sb.toString()); } static class pair implements Comparable<pair> { int x, y; public pair(int a, int numm) { x = a; y = numm; } @Override public int compareTo(pair o) { // TODO Auto-generated method stub if (y != o.y) return y > o.y ? 1 : -1; return 0; } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
30834d11b1e001ef39cf0fe78b096085
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.OutputStreamWriter; import java.util.PriorityQueue; import java.io.BufferedWriter; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.List; import java.util.Map; import java.util.function.Function; import java.io.IOException; import java.util.TreeMap; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.Set; import java.util.function.BiFunction; import java.util.NoSuchElementException; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { class O{ int num; int occurance; } public void solve(int testNumber, InputReader in, OutputWriter out){ int n = in.ri(); TreeMap<Integer, Integer> helper = new TreeMap<>(); PriorityQueue<O> tm = new PriorityQueue<>(Comparator.comparing((O o) -> o.occurance).reversed()); for(int i = 0; i < n; i++) helper.merge(in.ri(), 1, Integer::sum); for(Map.Entry<Integer, Integer> e : helper.entrySet()) { O o = new O(); o.num = e.getKey(); o.occurance = e.getValue(); tm.add(o); } ArrayList<ArrayList<Integer>> res = new ArrayList<>(); while(tm.size() > 2){ ArrayList<O> entries = new ArrayList<>(); ArrayList<Integer> temp = new ArrayList<>(); for(int i = 0; i < 3; i++) entries.add(tm.poll()); for(O e : entries){ temp.add(e.num); if (e.occurance > 1){ e.occurance--; tm.add(e); } } res.add(temp); } out.printLine(res.size()); for(ArrayList<Integer> a : res) { Collections.sort(a, Comparator.<Integer>reverseOrder()); for(int el : a) out.print(el + " "); out.printLine(); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int ri(){ return readInt(); } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine() { writer.println(); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
8974edc772033af0be70247474f41494
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.OutputStreamWriter; import java.util.PriorityQueue; import java.io.BufferedWriter; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.List; import java.util.Map; import java.util.function.Function; import java.io.IOException; import java.util.TreeMap; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.Set; import java.util.function.BiFunction; import java.util.NoSuchElementException; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { class O{ int num; int occurance; } public void solve(int testNumber, InputReader in, OutputWriter out){ int n = in.ri(); TreeMap<Integer, Integer> helper = new TreeMap<>(); PriorityQueue<O> tm = new PriorityQueue<>(Comparator.comparing((O o) -> o.occurance).reversed()); for(int i = 0; i < n; i++) helper.merge(in.ri(), 1, Integer::sum); for(Map.Entry<Integer, Integer> e : helper.entrySet()) { O o = new O(); o.num = e.getKey(); o.occurance = e.getValue(); tm.add(o); } ArrayList<ArrayList<Integer>> res = new ArrayList<>(); outer: while(true){ ArrayList<O> entries = new ArrayList<>(); ArrayList<Integer> temp = new ArrayList<>(); for(int i = 0; i < 3; i++) entries.add(tm.poll()); for(O e : entries) if (e == null) break outer; for(O e : entries){ temp.add(e.num); if (e.occurance > 1){ e.occurance--; tm.add(e); } } res.add(temp); } out.printLine(res.size()); for(ArrayList<Integer> a : res) { Collections.sort(a, Comparator.<Integer>reverseOrder()); for(int el : a) out.print(el + " "); out.printLine(); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int ri(){ return readInt(); } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine() { writer.println(); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
891c89828211ce975ee7e141bb9f5d3b
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.OutputStreamWriter; import java.util.PriorityQueue; import java.io.BufferedWriter; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.List; import java.util.Map; import java.util.function.Function; import java.io.IOException; import java.util.TreeMap; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.Set; import java.util.function.BiFunction; import java.util.NoSuchElementException; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { class O{ int num, occurance; public O(int num, int occurance){this.num = num; this.occurance = occurance;} } public void solve(int testNumber, InputReader in, OutputWriter out){ int n = in.ri(); TreeMap<Integer, Integer> helper = new TreeMap<>(); PriorityQueue<O> tm = new PriorityQueue<>(Comparator.comparing((O o) -> o.occurance).reversed()); for(int i = 0; i < n; i++) helper.merge(in.ri(), 1, Integer::sum); for(Map.Entry<Integer, Integer> e : helper.entrySet()) tm.add(new O(e.getKey(), e.getValue())); ArrayList<ArrayList<Integer>> res = new ArrayList<>(); while(tm.size() > 2){ ArrayList<O> entries = new ArrayList<>(); ArrayList<Integer> temp = new ArrayList<>(); for(int i = 0; i < 3; i++) entries.add(tm.poll()); for(O e : entries){ temp.add(e.num); if (e.occurance > 1){ e.occurance--; tm.add(e); } } res.add(temp); } out.printLine(res.size()); for(ArrayList<Integer> a : res) { Collections.sort(a, Comparator.<Integer>reverseOrder()); for(int el : a) out.print(el + " "); out.printLine(); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int ri(){ return readInt(); } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine() { writer.println(); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
e83177f822719da21f477ac351a9c8b2
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.awt.color.*; import java.util.*; import java.awt.Point; import java.math.*; import java.io.*; @SuppressWarnings("unused") public class implementation {int[] b; String g="";int c=0;int M=1000000000+7;ArrayList<Integer> list=new ArrayList<Integer>();String s;int[] size;int[] id; int[]ab;int[] data;int mod=100000;LinkedList<Integer> queue=new LinkedList<Integer>();int dis=0;int max=0;ArrayList<Integer>[] arr; public static void main(String[] args) { new implementation().solve(); } long[] fact;long[] inv; public void solve(){ int n=sc.nextInt(); PriorityQueue<Node> pq=new PriorityQueue<Node>(n+100,new sortbyweight()); PriorityQueue<Node> qq=new PriorityQueue<Node>(n+100,new sortbyweight()); HashMap<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int i=0;i<n;i++) { int a=sc.nextInt(); if(map.get(a)==null) { map.put(a, 1); } else { map.put(a, map.get(a)+1); } } for (Map.Entry<Integer, Integer> entry : map.entrySet()) { Node b=new Node(entry.getKey(),entry.getValue()); pq.add(b); qq.add(b); } if(pq.size()<3) { System.out.println(0); } else { StringBuilder sb=new StringBuilder(); Node p,q,r;int c=0; while(true){ p=pq.poll();q=pq.poll();r=pq.poll(); if(p.color<1||r.color<1||q.color<1) break; Node g=new Node(p.x,p.color-1);Node g2=new Node(q.x,q.color-1);Node g3=new Node(r.x,r.color-1); pq.add(g);pq.add(g2);pq.add(g3); c++; } System.out.println(c); while(true){ p=qq.poll();q=qq.poll();r=qq.poll(); if(p.color<1||r.color<1||q.color<1) break; int yy=Math.max(p.x, Math.max(q.x, r.x)); int rr=Math.min(p.x, Math.min(r.x, q.x)); int uu=p.x+q.x+r.x-yy-rr; System.out.println(yy+" "+uu+" "+rr); Node g=new Node(p.x,p.color-1);Node g2=new Node(q.x,q.color-1);Node g3=new Node(r.x,r.color-1); qq.add(g);qq.add(g2);qq.add(g3); } } } public class Node{ int x;int color;int y; Node par; public Node(int a,int b) { x=a;color=b; } } class sortbyweight implements Comparator<Node>{ @Override public int compare(Node a, Node b) { // TODO Auto-generated method stub if(a.color<b.color) return 1; else return -1; }} FastReader sc=new FastReader(); static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }}
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
233403808ccac447664bc458f27356b0
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; /** * Built using CHelper plug-in Actual solution is at the top */ public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true); TaskB solver = new TaskB(); solver.solve(1, in, out); out.flush(); out.close(); } } class Pair<A, B> { A first; B second; Pair(A first, B second) { this.first = first; this.second = second; } } class TaskB { int INF = (int) 1e9 + 7; int MAX_N = (int) 2e4 + 5; long mod = (long) 1e8; List<Integer> ans; public void solve(int testNumber, InputReader in, PrintWriter pw) { int n = in.nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } Arrays.sort(arr); int l = 0, r = n / 3 + 1; while (r - l > 1) { int mid = (l + r) / 2; boolean ok = check(mid, arr, n); if (ok) { l = mid; } else { r = mid; } } pw.println(l); check(l, arr, n); for (int i = 0; i < ans.size(); i += 3) { pw.println(ans.get(i) + " " + ans.get(i + 1) + " " + ans.get(i + 2)); } } boolean check(int mid, int arr[], int n) { int start[] = new int[mid]; int end[] = new int[mid]; int counter = 0; boolean taken[] = new boolean[n]; List<Integer> rest = new ArrayList<Integer>(); for (int i = 0; i < mid && i < n; i++) { start[counter++] = arr[i]; taken[i] = true; } counter = mid - 1; for (int i = n - 1; counter >= 0 && i >= 0; i--) { if (taken[i]) { continue; } end[counter--] = arr[i]; taken[i] = true; } if (counter > 0) { return false; } for (int i = 0; i < n; i++) { if (!taken[i]) { rest.add(arr[i]); } } ans = new ArrayList<Integer>(); int ptr = 0; for (int i = 0; i < mid; i++) { ans.add(end[i]); int first = start[i]; int last = end[i]; while (ptr < rest.size() && rest.get(ptr) <= first) { ptr++; } if (ptr == rest.size()) { return false; } if (rest.get(ptr) >= last) { return false; } ans.add(rest.get(ptr++)); ans.add(start[i]); } return true; } // int sum(int k) { // int sum=0; // for(int i=k;i>=1;i) { // sum+=ft[k]; // } // } long fib(int N) { long fib[] = new long[N + 1]; fib[0] = 1; fib[1] = 1; for (int i = 2; i <= N; i++) { fib[i] = (fib[i - 1] + fib[i - 2]) % mod; } return fib[N] % mod; } long sum(int i, int j, long arr[]) { long sum = 0; for (int k = i; k <= j; k++) { sum += arr[k]; } return sum; } boolean FirstRow_Col(Pair<Integer, Integer> pair) { return pair.first == 0 || pair.second == 0; } int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } public int getInt(int num) { int ret = -1; switch (num) { case 0: ret = 6; break; case 1: ret = 2; break; case 2: ret = 5; break; case 3: ret = 5; break; case 4: ret = 4; break; case 5: ret = 5; break; case 6: ret = 6; break; case 7: ret = 3; break; case 8: ret = 7; break; case 9: ret = 6; break; } return ret; } public int isPow(long num) { int count = 0; while (num > 0) { num /= 2; count++; } return count; } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
dc1a1ae9496eefbc93bae65f51964f81
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; /** * Built using CHelper plug-in Actual solution is at the top */ public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true); TaskB solver = new TaskB(); solver.solve(1, in, out); out.flush(); out.close(); } } class Pair<A, B> { A first; B second; Pair(A first, B second) { this.first = first; this.second = second; } } class TaskB { int INF = (int) 1e9 + 7; int MAX_N = (int) 2e4 + 5; long mod = (long) 1e8; List<Integer> ans; public void solve(int testNumber, InputReader in, PrintWriter pw) { int n = in.nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } Arrays.sort(arr); int l = 0, r = n / 3 + 1; while (r - l > 1) { int mid = (l + r) / 2; boolean ok = check(mid, arr, n); if (ok) { l = mid; } else { r = mid; } } pw.println(l); check(l, arr, n); for (int i = 0; i < ans.size(); i += 3) { pw.println(ans.get(i) + " " + ans.get(i + 1) + " " + ans.get(i + 2)); } } boolean check(int mid, int arr[], int n) { int start[] = new int[mid]; int end[] = new int[mid]; int counter = 0; boolean taken[] = new boolean[n]; List<Integer> rest = new ArrayList<Integer>(); for (int i = 0; i < mid && i < n; i++) { start[counter++] = arr[i]; taken[i] = true; } counter = mid - 1; for (int i = n - 1; counter >= 0 && i >= 0; i--) { if (taken[i]) { continue; } end[counter--] = arr[i]; taken[i] = true; } if (counter > 0) { return false; } for (int i = 0; i < n; i++) { if (!taken[i]) { rest.add(arr[i]); } } ans = new ArrayList<Integer>(); int ptr = 0; for (int i = 0; i < mid; i++) { ans.add(end[i]); int first = start[i]; int last = end[i]; while (ptr < rest.size() && rest.get(ptr) <= first) { ptr++; } if (ptr >= rest.size()) { return false; } if (rest.get(ptr) >= last) { return false; } ans.add(rest.get(ptr++)); ans.add(start[i]); } return true; } // int sum(int k) { // int sum=0; // for(int i=k;i>=1;i) { // sum+=ft[k]; // } // } long fib(int N) { long fib[] = new long[N + 1]; fib[0] = 1; fib[1] = 1; for (int i = 2; i <= N; i++) { fib[i] = (fib[i - 1] + fib[i - 2]) % mod; } return fib[N] % mod; } long sum(int i, int j, long arr[]) { long sum = 0; for (int k = i; k <= j; k++) { sum += arr[k]; } return sum; } boolean FirstRow_Col(Pair<Integer, Integer> pair) { return pair.first == 0 || pair.second == 0; } int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } public int getInt(int num) { int ret = -1; switch (num) { case 0: ret = 6; break; case 1: ret = 2; break; case 2: ret = 5; break; case 3: ret = 5; break; case 4: ret = 4; break; case 5: ret = 5; break; case 6: ret = 6; break; case 7: ret = 3; break; case 8: ret = 7; break; case 9: ret = 6; break; } return ret; } public int isPow(long num) { int count = 0; while (num > 0) { num /= 2; count++; } return count; } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
fff03122b43028a6982ec7a97ab9e83c
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeMap; public class CF2 { static public void main(String[] args) { WozReader wr = new CF2().new WozReader(); PrintWriter pw = new PrintWriter(System.out); int n = wr.nextInt(); TreeMap<Integer, Integer> map = new TreeMap<>(); for (int i = 0; i < n; i++) { int num = wr.nextInt(); if (map.containsKey(num)) map.put(num, map.get(num)+1); else map.put(num, 1); } PriorityQueue<Height> pq = new PriorityQueue<>(); for (Map.Entry<Integer, Integer> en : map.entrySet()) { pq.add(new Height(en.getKey(), en.getValue())); } ArrayList<Snowman> snowmen = new ArrayList<>(); while (!pq.isEmpty()) { Height h1 = pq.poll(); Height h2 = pq.poll(); Height h3 = pq.poll(); if (h3 != null) snowmen.add(new Snowman(h1.height, h2.height, h3.height)); if (h1.quantity > 1) pq.add(new Height(h1.height, h1.quantity-1)); if (h2 != null && h2.quantity > 1) pq.add(new Height(h2.height, h2.quantity-1)); if (h3 != null && h3.quantity > 1) pq.add(new Height(h3.height, h3.quantity-1)); } pw.println(snowmen.size()); for (int i = 0; i < snowmen.size(); i++) pw.println(snowmen.get(i)); pw.flush(); } class WozReader { BufferedReader br; StringTokenizer st; public WozReader() { 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 String nextLine() { String line = ""; try { line = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return line; } } } class Snowman { int h1, h2, h3; public Snowman(int a, int b, int c) { int[] arr = { a, b, c }; Arrays.sort(arr); h1 = arr[0]; //smallest h2 = arr[1]; h3 = arr[2]; //biggest } public String toString() { return String.format("%d %d %d", h3, h2, h1); } } class Height implements Comparable<Height> { int height; int quantity; public Height(int h, int q) { height = h; quantity = q; } public int compareTo(Height h) { return h.quantity - this.quantity; } public String toString() { return height + " " + quantity; } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
4d2b8564be1b80b95a141d013318d5fc
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
/* * * @Author Ajudiya_13(Bhargav Girdharbhai Ajudiya) * Dhirubhai Ambani Institute of Information And Communication Technology * */ import java.util.*; import java.io.*; import java.lang.*; public class Code225 { public static ArrayList<pair> arr; public static int binarySearch(ArrayList<pair> arr,int n) { int start = 1; int end = n/3; int ans = 0; while(start<=end) { int mid = (start+end)/2; int sum = 0; for(int i=arr.size()-1;i>=0;i--) sum += Math.min(arr.get(i).x,mid); if(sum>=3*mid) { ans = mid; start = mid+1; } else end = mid-1; } return ans; } public static int[] construct(int k) { int index = 0; int[] ans = new int[3*k]; for(int i=arr.size()-1;i>=0;i--) { pair p = arr.get(i); for(int j=0;j<Math.min(k,p.x);j++) { if(index<3*k) ans[index] = p.y; else return ans; index++; } } return ans; } public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(); HashMap<Integer,Integer> freq = new HashMap<Integer,Integer>(); arr = new ArrayList<pair>(); for(int i=0;i<n;i++) { int x = in.nextInt(); if(freq.containsKey(x)) freq.put(x, freq.get(x)+1); else freq.put(x, 1); } for(int p : freq.keySet()) arr.add(new pair(freq.get(p),p)); Collections.sort(arr); int k = binarySearch(arr, n); int[] ans = construct(k); pw.println(k); for(int i=0;i<k;i++) { int[] a = new int[3]; a[0] = ans[i]; a[1] = ans[i+k]; a[2] = ans[i+2*k]; Arrays.sort(a); pw.println(a[2] + " " + a[1] + " " +a[0]); } pw.flush(); pw.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static ArrayList<Integer> primeFactorization(int n) { ArrayList<Integer> a =new ArrayList<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static int modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
22dc5ff7c69ac8c68f7b4c8dc30d0b27
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
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.PriorityQueue; import java.util.HashMap; import java.io.InputStreamReader; import java.util.AbstractCollection; 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 MaxHeap */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); SnowMen solver = new SnowMen(); solver.solve(1, in, out); out.close(); } static class SnowMen { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); PriorityQueue<IntPair> pq = new PriorityQueue<>(new Comparator<IntPair>() { public int compare(IntPair a, IntPair b) { if (a.getSecond() == b.getSecond()) { return Integer.compare(b.getFirst(), a.getFirst()); } return Integer.compare(b.getSecond(), a.getSecond()); } }); HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { int cur = in.nextInt(); map.put(cur, map.getOrDefault(cur, 0) + 1); } for (int i : map.keySet()) { pq.add(new IntPair(i, map.get(i))); } if (pq.size() < 3) { out.println(0); return; } StringBuilder ans = new StringBuilder(); int number = 0; while (!pq.isEmpty()) { IntPair first = pq.poll(); IntPair second = pq.poll(); IntPair third = pq.poll(); ans.append(getOrder(first.getFirst(), second.getFirst(), third.getFirst()) + "\n"); ++number; first.setSecond(first.getSecond() - 1); if (first.getSecond() > 0) pq.add(first); third.setSecond(third.getSecond() - 1); if (third.getSecond() > 0) pq.add(third); second.setSecond(second.getSecond() - 1); if (second.getSecond() > 0) pq.add(second); if (pq.size() < 3) break; } out.println(number); out.println(ans.toString().trim()); } String getOrder(int a, int b, int c) { int[] ans = new int[]{a, b, c}; Arrays.sort(ans); return ans[2] + " " + ans[1] + " " + ans[0]; } } static class FastReader { BufferedReader reader; StringTokenizer st; public FastReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { String line = reader.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class IntPair implements Comparable<IntPair> { int first; int second; public IntPair(int first, int second) { this.first = first; this.second = second; } public int compareTo(IntPair a) { if (second == a.second) { return Integer.compare(first, a.first); } return Integer.compare(second, a.second); } public String toString() { return "<" + first + ", " + second + ">"; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IntPair a = (IntPair) o; if (first != a.first) return false; return second == a.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public int getFirst() { return first; } public int getSecond() { return second; } public void setSecond(int second) { this.second = second; } } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
b439f322aae9a0d7944e3771ee25d659
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.util.*; public final class Snowman { public static void main(String[] args) { Scanner br=new Scanner(System.in); int n=br.nextInt(); int ans=0; int[] a=new int[n]; TreeSet<Man>ts=new TreeSet<Man>(); for(int i=0;i<n;i++) a[i]=br.nextInt(); Arrays.sort(a); int temp,c; for(int i=0;i<n;) { temp=a[i]; c=0; while(i<n && temp==a[i]) { i++; c++; } ts.add(new Man(temp,c)); } StringBuilder s=new StringBuilder(""); int[] k=new int[3]; while(true && ts.size()>=3) { Man m1=ts.pollLast(); Man m2=ts.pollLast(); Man m3=ts.pollLast(); if(m1.f>0 && m2.f>0 && m3.f>0) { ans++; k[0]=m1.n; k[1]=m2.n; k[2]=m3.n; Arrays.sort(k); s.append(k[2]+" "+k[1]+" "+k[0]+"\n"); } else break; ts.add(new Man(m1.n,m1.f-1)); ts.add(new Man(m2.n,m2.f-1)); ts.add(new Man(m3.n,m3.f-1)); } System.out.println(ans+"\n"+s); } } class Man implements Comparable<Man> { int n,f; public Man(int n,int f) { this.n=n; this.f=f; } public int compareTo(Man that) { if (this.f-that.f==0) return this.n-that.n; return this.f-that.f; } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
a15f3df7278363d792a1a2fb74d9c9ec
train_004.jsonl
1325689200
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; public class Test { public static void main(String[] args) { Map<Integer,Integer> count = new HashMap<>(); Queue<SMGroup> groups = new PriorityQueue<SMGroup>(new Comparator<SMGroup>() { @Override public int compare(SMGroup t, SMGroup t1) { if (t.size < t1.size) return 1; if (t.size > t1.size) return -1; return 0; } }); StringBuilder result = new StringBuilder(); int k = 0; try (PrintWriter print = new PrintWriter(System.out); Scanner scanner = new Scanner(System.in)){ int n = scanner.nextInt(); for (int i = 0; i < n; i++) { int temp = scanner.nextInt(); if(count.containsKey(temp)) count.put(temp, count.get(temp) + 1); else count.put(temp, 1); } Iterator it = count.entrySet().iterator(); while (it.hasNext()){ Map.Entry e = (Map.Entry)it.next(); groups.add(new SMGroup((int)e.getKey(), (int)e.getValue())); } while (groups.size() > 2){ SMGroup groupOne = groups.poll(); SMGroup groupTwo = groups.poll(); SMGroup groupThree = groups.poll(); groupOne.size--; groupTwo.size--; groupThree.size--; k++; int [] array = {groupOne.value,groupTwo.value,groupThree.value}; Arrays.sort(array); result.append(array[2] + " " + array[1] + " " + array[0] + "\n"); if (groupOne.size != 0) groups.add(groupOne); if (groupTwo.size != 0) groups.add(groupTwo); if (groupThree.size != 0) groups.add(groupThree); } print.print(k + "\n" + result); } } } class SMGroup { int value; int size; public SMGroup(int value, int size) { this.value = value; this.size = size; } public void minus (int num){ size-= num; } }
Java
["7\n1 2 3 4 5 6 7", "3\n2 2 3"]
2 seconds
["2\n3 2 1\n6 5 4", "0"]
null
Java 8
standard input
[ "data structures", "binary search", "greedy" ]
551e66a4b3da71682652d84313adb8ab
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.
1,800
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.
standard output
PASSED
e1533e2639c698f05bc0dddbca4be3bb
train_004.jsonl
1572873300
You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; public class paymentwithoutchange implements Runnable{ public static void main(String[] args) { try{ new Thread(null, new paymentwithoutchange(), "process", 1<<26).start(); } catch(Exception e){ System.out.println(e); } } public void run() { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); //PrintWriter out = new PrintWriter("file.out"); Task solver = new Task(); int t = scan.nextInt(); //int t = 1; for(int i = 1; i <= t; i++) solver.solve(i, scan, out); out.close(); } static class Task { static final int inf = Integer.MAX_VALUE; public void solve(int testNumber, FastReader sc, PrintWriter out) { int a=sc.nextInt(); int b=sc.nextInt(); int n=sc.nextInt(); int s=sc.nextInt(); if((long)a*n+(long)b>=s&&(long)s%n<=(long)b) { out.println("YES"); return; } out.println("NO"); return; } } static long binpow(long a, long b, long m) { a %= m; long res = 1; while (b > 0) { if ((b & 1) == 1) res = res * a % m; a = a * a % m; b >>= 1; } return res; } static void sort(int[] x){ shuffle(x); Arrays.sort(x); } static void sort(long[] x){ shuffle(x); Arrays.sort(x); } static class tup implements Comparable<tup>, Comparator<tup>{ int a, b; tup(int a,int b){ this.a=a; this.b=b; } public tup() { } @Override public int compareTo(tup o){ return Integer.compare(b,o.b); } @Override public int compare(tup o1, tup o2) { return Integer.compare(o1.b, o2.b); } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; tup other = (tup) obj; return a==other.a && b==other.b; } @Override public String toString() { return a + " " + b; } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"]
1 second
["YES\nNO\nNO\nYES"]
null
Java 11
standard input
[ "math" ]
e2434fd5f9d16d59e646b6e69e37684a
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value.
1,000
For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
standard output
PASSED
c75122d484959989a6fcb670f1d3f4a9
train_004.jsonl
1572873300
You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases.
256 megabytes
import java.util.Scanner; public class Payment_Without_Change { public static void main(String args[]) { Scanner reader = new Scanner(System.in); int q = reader.nextInt(); String[] answer = new String[q]; for (int i = 0; i < q; i++) { int a = reader.nextInt(); int b = reader.nextInt(); int n = reader.nextInt(); int s = reader.nextInt(); if (a > s / n) a = s / n; if (a * n + b >= s) answer[i] = "YES"; else answer[i] = "NO"; } reader.close(); for (String s : answer) System.out.println(s); } }
Java
["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"]
1 second
["YES\nNO\nNO\nYES"]
null
Java 11
standard input
[ "math" ]
e2434fd5f9d16d59e646b6e69e37684a
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value.
1,000
For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
standard output
PASSED
4deecc53d75fe843274485ba23ef76b5
train_004.jsonl
1572873300
You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases.
256 megabytes
import java.util.*; public class Solution{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int q = sc.nextInt(); for(int i=0; i<q; i++){ sc.nextLine(); long a = sc.nextLong(); long b = sc.nextLong(); long n = sc.nextLong(); long s = sc.nextLong(); if(s%n > b){ System.out.println("No"); } else{ if(a*n + b >= s){ System.out.println("Yes"); } else{ System.out.println("No"); } } } } }
Java
["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"]
1 second
["YES\nNO\nNO\nYES"]
null
Java 11
standard input
[ "math" ]
e2434fd5f9d16d59e646b6e69e37684a
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value.
1,000
For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
standard output
PASSED
62c7dcf2ef3da717d5fdf6bca0480ca7
train_004.jsonl
1572873300
You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases.
256 megabytes
import java.util.*; public class Solution{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int q = sc.nextInt(); for(int i=0; i<q; i++){ sc.nextLine(); long a = sc.nextLong(); long b = sc.nextLong(); long n = sc.nextLong(); long s = sc.nextLong(); if(s%n > b){ System.out.println("No"); } else{ if(a*n + b >= s){ System.out.println("Yes"); } else{ System.out.println("No"); } } } } }
Java
["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"]
1 second
["YES\nNO\nNO\nYES"]
null
Java 11
standard input
[ "math" ]
e2434fd5f9d16d59e646b6e69e37684a
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value.
1,000
For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
standard output