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
52d3396a657f3e65b158bad9f4f51c31
train_002.jsonl
1289232000
One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day n?
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class test { // static boolean sf[]; public static void main(String[] args) { // int test = fs.nextInt(); int test = 1; for (int cases = 0; cases < test; cases++) { int n=fs.nextInt(); int k=fs.nextInt(); int ar[]=getintarray(n); int maxp=k; for(int i=0;i<n-1;i++) { int x=ar[i]; int max=-1; for(int j=i+1;j<n;j++) { if(ar[j]>x) { max=Integer.max(ar[j], max); } } if(max==-1) { continue; } else { int left=k%x; int used=k/x; used=used*max; used+=left; maxp=Integer.max(maxp, used); } } op.print(maxp); op.flush(); } } // static ArrayList<Integer> gf(int x) { // ArrayList<Integer> al = new ArrayList<Integer>(); // while (x != 1) { // al.add(sf[x]); // x = x / sf[x]; // } // return al; // } static long expmodulo(long a, long b, long c) { long x = 1; long y = a; while (b > 0) { if (b % 2 == 1) { x = (x * y) % c; } y = (y * y) % c; // squaring the base b /= 2; } return (long) x % c; } static int modInverse(int a, int m) { int m0 = m; int y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient int q = a / m; int t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } static int countBits(int number) { return (int) (Math.log(number) / Math.log(2) + 1); } static int countDifferentBits(int a, int b) { int count = 0; for (int i = 0; i < 32; i++) { if (((a >> i) & 1) != ((b >> i) & 1)) { ++count; } } return count; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static void sortMyMapusingValues(HashMap<String, Integer> hm) { List<Map.Entry<String, Integer>> capitalList = new LinkedList<>(hm.entrySet()); Collections.sort(capitalList, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); HashMap<String, Integer> result = new HashMap<>(); for (Map.Entry<String, Integer> entry : capitalList) { result.put(entry.getKey(), entry.getValue()); } } static boolean ispowerof2(long num) { if ((num & (num - 1)) == 0) return true; return false; } static void primeFactors(int n) { while (n % 2 == 0) { System.out.print(2 + " "); n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { System.out.print(i + " "); n /= i; } } if (n > 2) System.out.print(n); } static boolean isPrime(long n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; long sq = (long) Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static class Graph { HashMap<Integer, LinkedList<Integer>> hm = new HashMap<Integer, LinkedList<Integer>>(); private void addVertex(int vertex) { hm.put(vertex, new LinkedList<>()); } private void addEdge(int source, int dest, boolean bi) { if (!hm.containsKey(source)) addVertex(source); if (!hm.containsKey(dest)) addVertex(dest); hm.get(source).add(dest); if (bi) { hm.get(dest).add(source); } } private boolean uniCycle(int i, HashSet<Integer> visited, int parent) { visited.add(i); LinkedList<Integer> list = hm.get(i); Iterator<Integer> it = list.iterator(); while (it.hasNext()) { Integer integer = (Integer) it.next(); if (!visited.contains(integer)) { if (uniCycle(integer, visited, i)) return true; } else if (integer != parent) { return true; } } return false; } private boolean uniCyclic() { HashSet<Integer> visited = new HashSet<Integer>(); Set<Integer> set = hm.keySet(); for (Integer integer : set) { if (!visited.contains(integer)) { if (uniCycle(integer, visited, -1)) { return true; } } } return false; } private boolean isbiCycle(int i, HashSet<Integer> visited, HashSet<Integer> countered) { if (countered.contains(i)) return true; if (visited.contains(i)) return false; visited.add(i); countered.add(i); LinkedList<Integer> list = hm.get(i); Iterator<Integer> it = list.iterator(); while (it.hasNext()) { Integer integer = (Integer) it.next(); if (isbiCycle(integer, visited, countered)) { return true; } } countered.remove(i); return false; } private boolean isbiCyclic() { HashSet<Integer> visited = new HashSet<Integer>(); HashSet<Integer> countered = new HashSet<Integer>(); Set<Integer> set = hm.keySet(); for (Integer integer : set) { if (isbiCycle(integer, visited, countered)) { return true; } } return false; } } static class Node { Node left, right; int data; public Node(int data) { this.data = data; } public void insert(int val) { if (val <= data) { if (left == null) { left = new Node(val); } else { left.insert(val); } } else { if (right == null) { right = new Node(val); } else { right.insert(val); } } } public boolean contains(int val) { if (data == val) { return true; } else if (val < data) { if (left == null) { return false; } else { return left.contains(val); } } else { if (right == null) { return false; } else { return right.contains(val); } } } public void inorder() { if (left != null) { left.inorder(); } System.out.print(data + " "); if (right != null) { right.inorder(); } } public int maxDepth() { if (left == null) return 0; if (right == null) return 0; else { int ll = left.maxDepth(); int rr = right.maxDepth(); if (ll > rr) return (ll + 1); else return (rr + 1); } } public int countNodes() { if (left == null) return 1; if (right == null) return 1; else { return left.countNodes() + right.countNodes() + 1; } } public void preorder() { System.out.print(data + " "); if (left != null) { left.inorder(); } if (right != null) { right.inorder(); } } public void postorder() { if (left != null) { left.inorder(); } if (right != null) { right.inorder(); } System.out.print(data + " "); } public void levelorder(Node node) { LinkedList<Node> ll = new LinkedList<Node>(); ll.add(node); getorder(ll); } public void getorder(LinkedList<Node> ll) { while (!ll.isEmpty()) { Node node = ll.poll(); System.out.print(node.data + " "); if (node.left != null) ll.add(node.left); if (node.right != null) ll.add(node.right); } } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } private static final Scanner sc = new Scanner(System.in); private static final FastReader fs = new FastReader(); private static final OutputWriter op = new OutputWriter(System.out); static int[] getintarray(int n) { int ar[] = new int[n]; for (int i = 0; i < n; i++) { ar[i] = fs.nextInt(); } return ar; } static long[] getlongarray(int n) { long ar[] = new long[n]; for (int i = 0; i < n; i++) { ar[i] = fs.nextLong(); } return ar; } static int[][] get2darray(int n, int m) { int ar[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ar[i][j] = fs.nextInt(); } } return ar; } static Pair[] getpairarray(int n) { Pair ar[] = new Pair[n]; for (int i = 0; i < n; i++) { ar[i] = new Pair(fs.nextInt(), fs.nextInt()); } return ar; } static void printarray(int ar[]) { for (int i : ar) { op.print(i + " "); } op.flush(); } static int fact(int n) { int fact = 1; for (int i = 2; i <= n; i++) { fact *= i; } return fact; } // // function to find largest prime factor }
Java
["2 4\n3 7", "4 10\n4 3 2 1", "4 10\n4 2 3 1"]
2 seconds
["8", "10", "15"]
null
Java 11
standard input
[ "brute force" ]
2c9133650d831fa6ab4c11661bcb9cbb
The first line contains two integers n and b (1 ≤ n, b ≤ 2000) — the number of days and the initial number of money in bourles. The next line contains n integers ai (1 ≤ ai ≤ 2000) — the prices of Martian dollars.
1,400
Print the single number — which maximal sum of money in bourles can Vasya get by the end of day n.
standard output
PASSED
2b6b44feb7604b04cef3ed5944693676
train_002.jsonl
1289232000
One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day n?
256 megabytes
/** * @author egaeus * @mail sebegaeusprogram@gmail.com * @veredict Not sended * @url <https://codeforces.com/problemset/problem/41/B> * @category ? * @date 14/06/2020 **/ import java.io.*; import java.util.*; import static java.lang.Integer.*; import static java.lang.Math.*; public class CF41B { public static void main(String args[]) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (String ln; (ln = in.readLine()) != null && !ln.equals(""); ) { StringTokenizer st = new StringTokenizer(ln); int N = parseInt(st.nextToken()); long B = parseInt(st.nextToken()); long s = B; long[] arr = new long[N]; st = new StringTokenizer(in.readLine()); for (int i = 0; i < N; i++) { arr[i] = parseInt(st.nextToken()); } for (int i = 0; i < N; i++) for (int j = i + 1; j < N; j++) { s = Math.max(s, (B / arr[i]) * arr[j] + B % arr[i]); } System.out.println(s); } } }
Java
["2 4\n3 7", "4 10\n4 3 2 1", "4 10\n4 2 3 1"]
2 seconds
["8", "10", "15"]
null
Java 11
standard input
[ "brute force" ]
2c9133650d831fa6ab4c11661bcb9cbb
The first line contains two integers n and b (1 ≤ n, b ≤ 2000) — the number of days and the initial number of money in bourles. The next line contains n integers ai (1 ≤ ai ≤ 2000) — the prices of Martian dollars.
1,400
Print the single number — which maximal sum of money in bourles can Vasya get by the end of day n.
standard output
PASSED
006cb72588d71ca88dfa87ba5c37d079
train_002.jsonl
1289232000
One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day n?
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { static class Pair { public int x, y, id; public Pair() { x = y = 0; } public Pair(int x, int y, int i) { this.x = x; this.y = y; id = i; } } static long INF = (long) (1000000000); public static void main(String[] args) throws IOException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n; n = in.nextInt(); int b = in.nextInt(); int A[]=new int[2005]; for(int i=1;i<=n;i++) { A[i]=in.nextInt(); } int mi = (int)1e9; int ans = b; for(int i=1;i<=n;i++) { if(i>1) { ans = Math.max((b/mi)*A[i]+b%mi,ans); } mi = Math.min(mi, A[i]); } out.print(ans); out.flush(); } static class InputReader { StreamTokenizer tokenizer; public InputReader(InputStream stream) { tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(stream))); tokenizer.ordinaryChars(33, 126); tokenizer.wordChars(33, 126); } public String next() throws IOException { tokenizer.nextToken(); return tokenizer.sval; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean hasNext() throws IOException { int res = tokenizer.nextToken(); tokenizer.pushBack(); return res != StreamTokenizer.TT_EOF; } } }
Java
["2 4\n3 7", "4 10\n4 3 2 1", "4 10\n4 2 3 1"]
2 seconds
["8", "10", "15"]
null
Java 11
standard input
[ "brute force" ]
2c9133650d831fa6ab4c11661bcb9cbb
The first line contains two integers n and b (1 ≤ n, b ≤ 2000) — the number of days and the initial number of money in bourles. The next line contains n integers ai (1 ≤ ai ≤ 2000) — the prices of Martian dollars.
1,400
Print the single number — which maximal sum of money in bourles can Vasya get by the end of day n.
standard output
PASSED
c5a1732c4aa545944c7b9b228a59662a
train_002.jsonl
1289232000
One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day n?
256 megabytes
import java.io.*; import java.util.*; public class MyClass { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[]) { FastReader fr = new FastReader(); int n = fr.nextInt(), b = fr.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i += 1) nums[i] = fr.nextInt(); int i = 0, low = 10000000, gain = 0; while (i < n) { low = Math.min(low, nums[i]); int j = i + 1; while (j < n && nums[j - 1] <= nums[j]) j += 1; gain = Math.max(gain, b / low * (nums[j - 1] - low)); i = j; } System.out.println(b + gain); } }
Java
["2 4\n3 7", "4 10\n4 3 2 1", "4 10\n4 2 3 1"]
2 seconds
["8", "10", "15"]
null
Java 11
standard input
[ "brute force" ]
2c9133650d831fa6ab4c11661bcb9cbb
The first line contains two integers n and b (1 ≤ n, b ≤ 2000) — the number of days and the initial number of money in bourles. The next line contains n integers ai (1 ≤ ai ≤ 2000) — the prices of Martian dollars.
1,400
Print the single number — which maximal sum of money in bourles can Vasya get by the end of day n.
standard output
PASSED
e741afdb447d4444fc63b93878e7fe6b
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.util.Scanner; import java.util.TreeSet; public class Numbers { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(), k = scan.nextInt(); if(n == 1){ if(k > 0) System.out.println(-1); else System.out.println(1); } else if(n/2 > k) System.out.println(-1); else { int rem = k-(n/2-1); int[] a = new int[n]; if(n%2==0){a[n-2] = rem; a[n-1] = rem*2;} else {a[n-3] = rem; a[n-2] = rem*2;} TreeSet<Integer> u = new TreeSet<>(); u.add(rem); u.add(rem*2); int curr = 1; for(int i = 0; i < n/2-1; i++){ while(u.contains(curr) || u.contains(curr+1)) curr++; a[i*2] = curr; a[i*2+1] = curr+1; u.add(curr); u.add(curr+1); } while(u.contains(curr)) curr++; if(n%2==1)a[n-1] = curr; for(int i = 0; i < n; i++) System.out.print(a[i]+" "); } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
452fd50c432b1cb4e5eba86e12856e20
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.util.*; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); if (k < n / 2 || (n == 1 && k > 0) ) { System.out.println(-1); } else if (n == 1) { System.out.println(1); } else { int x = k - (n - 2) / 2; System.out.print(x + " " + x*2); int y = x*2 + 1; for (int i = 2; i < n; i++) { System.out.print(" " + y++); } } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
ec184e160e55c7c3255eadbafd97ec1e
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.util.*; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); if(n==1) { if(k!=0) { System.out.print(-1); return; } else { System.out.print(1); return; } } if(k<n/2) { System.out.println(-1); return; } int x = k-(n-2)/2; System.out.print(x + " " + 2*x + " "); for(int i=2; i<n; ++i) { System.out.print(2*x+i + " "); } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
e9442d9b750be20f293f08f9bd8e51af
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.util.*; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); if (k < n / 2 || (n == 1 && k > 0) ) { System.out.println(-1); return; } if (n == 1) { System.out.println(1); return; } int x = k - (n - 2) / 2; System.out.print(x + " " + x*2); int y = x*2 + 1; for (int i = 2; i < n; i++) { System.out.print(" " + y++); } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
691c36e6b2ca21a79a240603f464ee97
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.util.*; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); if(n==1) { if(k!=0) { System.out.print("-1"); return; } else if(k==0) { System.out.print("1"); return; } } if(k<n/2) { System.out.println("-1"); return; } int x = k-(n-2)/2; System.out.print(x + " " + x*2 + " "); for(int i=2; i<n; ++i) { System.out.print(x*2+i + " "); } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
8d7844a908868bdaabdf584c48839b0c
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner jin = new Scanner(System.in); long n = jin.nextLong(); long k = jin.nextLong(); if (n == 1 && k == 0) { System.out.println(1); return; } if (n == 1 && k > 0 || k < n / 2) { System.out.println(-1); return; } long t = k - n / 2 + 1; System.out.print(t + " " + 2 * t); long d = 2 * t + 1; for (int i = 2; i < n; ++i) { System.out.print(" " + d++); } System.out.println(); } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
4b03e0939deba70241dbf1ecb5130a70
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main2 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), k = sc.nextInt(); if(n < 2) System.out.println(k==0?1:-1); else if(k < n / 2) System.out.println(-1); else { StringBuilder sb = new StringBuilder(); int x = k + 1 - n / 2; sb.append(x).append(" ").append(x<<1); for(int i = 1, j = 1; j < n>>1; i+=2, j++) if(i != x && i != x<< 1 && i + 1 != x && i + 1 != x<<1) sb.append(" ").append(i).append(" ").append(i+1); else j--; if(n%2 == 1) sb.append(" 500000000"); System.out.println(sb); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(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 boolean ready() throws IOException {return br.ready();} } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
7209c37ad6535678c36494778cf54d6c
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.awt.Point; import java.awt.geom.Line2D; import java.io.BufferedReader; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.io.InputStream; import java.math.BigInteger; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); long var=System.currentTimeMillis(); solver.solve(1, in, out); /*if(System.getProperty("ONLINE_JUDGE")==null){ out.println("["+(double)(System.currentTimeMillis()-var)/1000+"]"); }*/ out.close(); } } class Pair { int x,y,index; Pair(int x,int y,int index){ this.x=x; this.y=y; this.index=index; } } class Edge{ int u; int v; int time; public Edge(int u,int v){ this.u=u; this.v=v; time=Integer.MAX_VALUE; } public int other(int x){ if(u==x)return v; return u; } } class TaskC { static long mod=1000000007; //static boolean prime[]=new boolean[1000010]; /*static{ //System.out.println("lifhgifwrek"); for(int i=2;i<=Math.sqrt(prime.length);i++){ for(int j=i*i;j<prime.length;j+=i){ prime[j]=true; } } // System.out.println("end"); prime[0]=true; prime[1]=true; }*/ public void solve(int testNumber, FastScanner in, PrintWriter out) throws IOException { int n=in.nextInt(); int k=in.nextInt(); int ans[]=new int[n+1]; if(k<n/2 || n==1){ if(k==0 && n==1){ out.println(1); return; } out.println(-1); return; } if(n%2==0){ ans[n-1]=k-((n-2)/2); ans[n]=2*ans[n-1]; } else{ ans[n-2]=k-((n-2)/2); ans[n-1]=2*ans[n-2]; } if(n%2==0){ int assign=1; for(int i=1;i<n-1;i+=2){ if(ans[n-1]!=assign && ans[n]!=assign && ans[n-1]!=(assign+1) && ans[n]!=(assign+1)){ ans[i]=assign; ans[i+1]=assign+1; assign+=2; } else{ ans[i]=ans[n]+1; ans[i+1]=ans[n]+2; assign+=ans[i+1]+1; } } } else{ int assign=1; for(int i=1;i<n-2;i+=2){ if(ans[n-1]!=assign && ans[n-2]!=assign && ans[n-1]!=(assign+1) && ans[n-2]!=(assign+1)){ ans[i]=assign; ans[i+1]=assign+1; assign+=2; } else{ ans[i]=ans[n-1]+1; ans[i+1]=ans[n-1]+2; assign+=ans[i+1]+1; } } ans[n]=ans[n-1]+3; } for(int i=1;i<=n;i++) out.print(ans[i]+" ");; out.println(); } long pow(long x,long y,long mod){ if(y<=0){ return 1; } if(y==1){ return x%mod; } long temp=pow(x,y/2,mod); if(y%2==0){ return (temp*temp)%mod; } else{ return (((temp*temp)%mod)*x)%mod; } } /* long DP(int id,int mask){ //System.out.println("hi"+dp[id][mask]+" "+id+" "+Integer.toBinaryString(mask)); if(id==0 && mask==0){ dp[0][mask]=1; return 1; } else if(id==0){ dp[0][mask]=0; return 0; } if(dp[id][mask]!=-1){ return dp[id][mask]; } long ans=0; for(int i=0;i<n;i++){ if((mask & (1<<i))!=0 && c[i][id]>=1){ ans+=DP(id-1,mask ^ (1 << i)); ans%=mod; } } ans+=DP(id-1,mask); ans%=mod; dp[id][mask]=ans; return ans; }*/ static long greatestCommonDivisor (long m, long n){ long x; long y; while(m%n != 0){ x = n; y = m%n; m = x; n = y; } return n; } int no_of_primes(int m,int n){ int count=0,i,j; int primes []=new int[n-m+2]; if(m==1) primes[0] = 1; for(i=2; i<=Math.sqrt(n); i++) { j = m/i; j *= i; if(j<m) j+=i; for(; j<=n; j+=i) { if(j!=i) primes[j-m] = 1; } } for(i=0; i<=n-m; i++) if(primes[i]==0) count++; return count; } } class SegTree { int n; long t[]; SegTree(int n,long t[]){ this.n=n; this.t=t; } void build() { // build the tree for (int i = n - 1; i > 0; --i) t[i]=t[i<<1]+t[i<<1|1]; } void modify(int p, long value) { // set value at position p for (t[p += n] = value; p > 1; p >>= 1) t[p>>1] = t[p] + t[p^1]; } long query(int l, int r) { // sum on interval [l, r) long res=0; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l&1)!=0) res=res+t[l++]; if ((r&1)!=0) res=res+t[--r]; } return res; } // // // } class FastScanner { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int snumChars; private SpaceCharFilter filter; public FastScanner(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 String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class UF { private int[] parent; // parent[i] = parent of i private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31) private int count; // number of components public UF(int N) { if (N < 0) throw new IllegalArgumentException(); count = N; parent = new int[N]; rank = new byte[N]; for (int i = 0; i < N; i++) { parent[i] = i; rank[i] = 0; } } public int find(int p) { if (p < 0 || p >= parent.length) throw new IndexOutOfBoundsException(); while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } public int count() { return count; } public boolean connected(int p, int q) { return find(p) == find(q); } public boolean union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return false; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; return true; } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
37787495ad4c346de61a7d30bb6b80c8
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
//package CF; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws Exception { Scanner bf = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = bf.nextInt(), k = bf.nextInt(); int even = n - (n%2); if(k*2 < even || n == 1 && k > 0) out.println(-1); else{ int tmp = (k-(even-2)/2); if(n > 1){ out.print(tmp + " " + 2*tmp + " "); n-=2; } int num = 1; while(n > 0){ while(num == tmp || num == tmp*2) num++; out.print(num++ + " "); n--; if(n > 0){ while(num == tmp || num == tmp*2) num++; out.print(num++ + " "); } n--; } } out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader fileReader) { br = new BufferedReader(fileReader); } 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 boolean ready() throws IOException { return br.ready(); } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
3cd200e17bfe84aa265bf5c54552ffac
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Don Li */ public class MashmokhNumbers { int N = (int) 2e6 + 5; boolean[] prime = new boolean[N]; int p = N - 1, q = 1, t; void solve() { int n = in.nextInt(), k = in.nextInt(); if (k < n / 2) { out.println(-1); return; } if (n == 1) { if (k == 0) { out.println(1); } else { out.println(-1); } return; } Arrays.fill(prime, true); prime[0] = prime[1] = false; int sqrt = (int) (Math.sqrt(N) + 0.5); for (int i = 2; i < sqrt; i++) { if (prime[i]) { for (int j = i * i; j < N; j += i) { prime[j] = false; } } } int[] a = new int[n]; t = k - (n / 2 - 1); a[0] = t; a[1] = t * 2; for (int i = 2; i < n; i += 2) { a[i] = nextPrime(); if (i + 1 < n) a[i + 1] = nextComposit(); } for (int i = 0; i < n; i++) { if (i > 0) out.print(' '); out.print(a[i]); } } int nextPrime() { while (!prime[p] || p == t || p == 2 * t) p--; return p--; } int nextComposit() { while (prime[q] || q == t || q == 2 * t) q++; return q++; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new MashmokhNumbers().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
bc47c36b4665fdd7d534018b111a7c0f
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
//package com.a2onlinejudge.ladder.CodeforcesDiv2C; import java.io.*; import java.util.*; public final class MashmokhAndNumbers { public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); Solver solver = new Solver(in, out); solver.solve(); out.flush(); in.close(); out.close(); } static class Solver { int n, k; InputReader in; OutputWriter out; public Solver(InputReader in, OutputWriter out) { this.in = in; this.out = out; } void solve() { n = in.nextInt(); k = in.nextInt(); if (n == 1) { if (k == 0) out.println(1); else out.println(-1); } else if (k < n / 2) out.println(-1); else { int x = k - (n - 2) / 2; out.print(x + " " + (x <<= 1) + " "); x++; for (int i = 2; i < n; i++, x++) out.print(x + " "); /* if ((n & 1) > 0) out.print(x);*/ } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int arraySize) { int array[] = new int[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextInt(); return array; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } long result = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); result *= 10; result += c & 15; c = read(); } while (!isSpaceChar(c)); return result * sign; } public long[] nextLongArray(int arraySize) { long array[] = new long[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextLong(); return array; } public float nextFloat() // problematic { float result, div; byte c; result = 0; div = 1; c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean isNegative = (c == '-'); if (isNegative) c = (byte) read(); do { result = result * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') result += (c - '0') / (div *= 10); if (isNegative) return -result; return result; } public double nextDouble() // not completely accurate { double ret = 0, div = 1; byte c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean neg = (c == '-'); if (neg) c = (byte) read(); do { ret = ret * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String nextLine() { int c = read(); StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (!isNewLine(c)); return result.toString(); } public boolean isNewLine(int c) { return c == '\n'; } public void close() { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } static class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter( stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(int x) { writer.println(x); } public void print(int x) { writer.print(x); } public void println(char x) { writer.println(x); } public void print(char x) { writer.print(x); } public void println(int array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(int array[], int size) { for (int i = 0; i < size; i++) print(array[i] + " "); } public void println(long x) { writer.println(x); } public void print(long x) { writer.print(x); } public void println(long array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(long array[], int size) { for (int i = 0; i < size; i++) print(array[i]); } public void println(float num) { writer.println(num); } public void print(float num) { writer.print(num); } public void println(double num) { writer.println(num); } public void print(double num) { writer.print(num); } public void println(String s) { writer.println(s); } public void print(String s) { writer.print(s); } public void println() { writer.println(); } public void printSpace() { writer.print(" "); } public void printf(String format, Object args) { writer.printf(format, args); } public void flush() { writer.flush(); } public void close() { writer.close(); } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
b7ad45ef8d411303bb9ad9d488947dcd
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.io.*; import java.util.*; public class CF415C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); if (n == 1) System.out.println(k == 0 ? 1 : -1); else if (k < n / 2) System.out.println(-1); else { StringBuilder sb = new StringBuilder(); int a = k - n / 2 + 1; sb.append(a); for (int i = 0; i < n - 1; i++) sb.append(" " + (a * 2 + i)); System.out.println(sb); } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
ede1ed675539decddcfa6294050de4df
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author Aditya Joshi */ public class Main { public static void main(String[] args) { MyScanner sc = new MyScanner(); int n = sc.nextInt(); boolean odd = false; if(n % 2 != 0) { n = n - 1; odd = true; } long k = sc.nextLong(); if(k == 0 && n == 0) { System.out.println(1); } else if(k == 0) { System.out.println(-1); } else { if(n > (2 * k) || (n + 1 == 1) || (n == 1)) { System.out.println(-1); } else if((2 * k) == n) { StringBuilder t = new StringBuilder(); int cnt = 1; int iterations = 0; while(iterations < (n/2)) { long c = cnt + 1; t.append(cnt).append(" ").append(c).append(" "); //System.out.println("Added " + cnt + "and " + (c)); cnt += 2; iterations++; } if(odd) t.append(cnt); System.out.println(t.toString()); } else { StringBuilder t = new StringBuilder(); // n < 2 * k long x = ((2 * k) + 2 - n)/2; // x and 2*x are hereby forbidden to be part of t. t.append(x).append(" ").append(x * 2).append(" "); k = k - x; int iterations = 0; long cnt = 1; while(iterations < ((n - 2)/2)) { if((cnt != x && (cnt != 2*x) && (1+cnt != x && (1+cnt != 2*x)))) { long c = cnt + 1; t.append(cnt).append(" ").append(c).append(" "); iterations++; } cnt += 2; } if(odd){ if((cnt != x && (cnt != 2*x) && (1+cnt != x && (1+cnt != 2*x)))) t.append(cnt); else { cnt += 2; t.append(cnt); } } System.out.println(t.toString()); } } } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
eaa436d979e874a6e77c1c9cc97951e7
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
//package vc; import java.util.Scanner; public class c { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); if(n==1) { if(k!=0) { System.out.println("-1"); return; } else if(k==0) { System.out.println("1"); return; } } if(k<n/2) { System.out.println("-1"); return; } else { int x = k-(n-2)/2; System.out.print(x+" "+ x*2); int y = x*2 + 1; for (int i=2;i<n;i++) { System.out.print(" " +y++); } } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
76b7064de3f2799260ce72b9302a7b5f
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
/* * 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. */ //package MASHNUM; import java.util.Scanner; /** * * @author nsekhar */ public class Main { public static void main(String[] args) { int n,k; Scanner sc = new Scanner(System.in); n = sc.nextInt(); k = sc.nextInt(); if(n >1 && k >=n/2) { int init = k-(n-2)/2; int j=init*2+1; System.out.print(init+" "+init*2 + " "); for(int i=2;i<n;i++) { System.out.print(j++ + " "); } } else if(n==1 && k==0) System.out.print("1 "); else System.out.print("-1 "); } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
240ee666243c3d10c646c825431f6dcb
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.util.Scanner; public class Fourthq { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner input = new Scanner (System.in); int n = input.nextInt(); int [] array = new int [n]; long k = input.nextLong(); long st = k+1-(n/2); if ((k >(int) Math.floor(n/2)-1)&&(k!=0)&&(k!=2)&&(k!=1)&&(n!=1)) {System.out.print(st+" "); for (long i = 2*st; i < st*2+ (n-1); i++ ) System.out.print(i+" ");} else if (n == 1 && k == 0){ System.out.print(1+" "); for (long i = 2*st; i < st*2+ (n-1); i++ ) System.out.print(i+" "); } // else if (n == 1 && k == 1){ // System.out.print("1"); // } else if (k == 2 && (k >(int) Math.floor(n/2)-1)){ System.out.print(1+" "); for (long i = 2*st; i < st*2+ (n-1); i++ ) System.out.print(i+" "); } else {//if (k <(int) Math.floor(n/2)-1){ System.out.print("-1"); } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
3a1ddfac70200cd41adb6d6afa662082
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.util.*; import java.io.*; public class C { static BufferedReader in; static PrintWriter out; static { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } static StringTokenizer st; static String nextString() { while(st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { System.err.println("Truble in reading"); } } return st.nextToken(); } static int nextInt() { return Integer.valueOf(nextString()); } static long nextLong() { return Long.valueOf(nextString()); } public static void main(String[] args) { int n = nextInt(); int k = nextInt(); if (k == 0) { if (n == 1) out.print("1"); else out.print("-1"); } else if (k*2+1 < n) { out.print("-1"); } else { int from = 1000000000; int cnt = n/2; List<Integer> ls = new ArrayList<>(); for(int i = from-1; i > 0 && cnt > 1; i-=2, cnt--, k--) { ls.add(i); ls.add(i-1); } if (k == 1) { ls.add(3); ls.add(5); } else { ls.add(k); ls.add(2*k); } if (n % 2 > 0) { ls.add(from); } if (ls.size() != n) { out.print("-1"); } else { for(int a:ls) { out.print(a); out.print(" "); } } } close(); } static void close() { try { in.close(); } catch (IOException e) { } out.flush(); out.close(); } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
b468744c0cba4e3f153549b79301d972
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class Codeforces_240_C { public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a%b); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); StringBuilder sb = new StringBuilder(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt() , k = sc.nextInt(); int temp = n ; if (n == 1 && k == 0) {System.out.println(1);return;} if (n == 1) {System.out.println(-1);return;} int check = n/2; if (k < check) {System.out.println(-1);return;} if(n%2==1)n--; k-=((n-2)/2); int i ; for(i = 0 ; i < n-2 ; ++i) System.out.print((i+1)+" "); while((++i)%k!=0); System.out.print(i+" "+(i+k)+" "); if(temp%2==1) System.out.print(k==1?(i+k+1):(i+1)); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
5a0a578edcbf515890b1d054d68ea926
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.util.*; import java.io.*; public class Main { 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); Task solver = new Task(); solver.main(in, out); out.close(); } } class Task { final int maxn = 211111; int[] a = new int[maxn]; HashSet<Integer> hash = new HashSet<Integer>(); void main(InputReader in, PrintWriter out) throws Exception { int n, i, k; n = in.nextInt(); k = in.nextInt(); int least = n >> 1; if (k < least) { out.println(-1); return; } if (n == 1 && k > 0) { out.println(-1); return; } int p = least - 1; k -= p; a[1] = k; a[2] = k * 2; int tk = 1; if (k > maxn) { tk = 1; } else { tk = maxn * 2; } for (i = 3; i <= n; ++i) { a[i] = ++tk; } for (i = 1; i <= n; ++i) { if (i > 1) out.print(" "); out.print(a[i]); } out.println(); } } class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } String next() { if (!hasNext()) throw new RuntimeException(); return tokenizer.nextToken(); } boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { return false; } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
4e9f77086b1bdfeed478e702051a332c
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.lang.reflect.*; 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); Task solver = new TaskC(); solver.solve(1, in, out); out.close(); } } interface Task { public void solve(int testNumber, InputReader in, OutputWriter out); } class TaskA implements Task { public void solve(int testNumber, InputReader in, OutputWriter out) { out.printLine(in.readInt(), 0, 0); } } class TaskB implements Task { long[] array; boolean[] isPrime; TreeSet<Long> set; public void solve(int testNumber, InputReader in, OutputWriter out) { int n=in.readInt(); array=IOUtils.readLongArray(in, n); isPrime=IntegerUtils.generatePrimalityTable(1000001); set=new TreeSet<Long>(); for (int i=1; i<=1000000; i++) if (isPrime[i]) set.add(1L*i*i); for (long i: array) out.printLine(set.contains(i)?"YES":"NO"); } } class TaskC implements Task { int[] primes; public void solve(int testNumber, InputReader in, OutputWriter out) { primes=IntegerUtils.generatePrimes(10000000); int n=in.readInt(), k=in.readInt(); if (k<n/2 || n<2 && k>0) { out.printLine(-1); return; } if (k==0) { out.printLine(1); return; } k-=(n-2)/2; if (k==1) n+=2; else out.print(2*k, 3*k, ""); for (int i=0; i<n-2; i++) out.print(primes[i], ""); } } class TaskD implements Task { public void solve(int testNumber, InputReader in, OutputWriter out) { int n=in.readInt(); out.printLine(1L*(n/2+1)*((n+1)/2+1)%1000000009); } } class TaskE implements Task { public void solve(int testNumber, InputReader in, OutputWriter out) { } } class TaskF implements Task { public void solve(int testNumber, InputReader in, OutputWriter out) { } } 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(char[] array) { writer.print(array); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) writer.print(' '); writer.print(array[i]); } } public void print(long[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) writer.print(' '); writer.print(array[i]); } } public void print(Collection<Integer> collection) { boolean first = true; for (int value : collection) { if (first) first = false; else writer.print(' '); writer.print(value); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(long[] array) { print(array); writer.println(); } public void printLine(Collection<Integer> collection) { print(collection); writer.println(); } public void printLine() { writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void print(char i) { writer.print(i); } public void printLine(char i) { writer.println(i); } public void printLine(char[] array) { writer.println(array); } public void printFormat(String format, Object... objects) { writer.printf(format, objects); } public void close() { writer.close(); } public void flush() { writer.flush(); } public void print(long i) { writer.print(i); } public void printLine(long i) { writer.println(i); } public void print(int i) { writer.print(i); } public void printLine(int i) { writer.println(i); } } class InputReader { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public int 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 { if (Character.isValidCodePoint(c)) res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { 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, readInt()); 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, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } public String next() { return readString(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class IOUtils { public static Pair<Integer, Integer> readIntPair(InputReader in) { int first = in.readInt(); int second = in.readInt(); return Pair.makePair(first, second); } public static Pair<Long, Long> readLongPair(InputReader in) { long first = in.readLong(); long second = in.readLong(); return Pair.makePair(first, second); } public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } public static long[] readLongArray(InputReader in, int size) { long[] array = new long[size]; for (int i = 0; i < size; i++) array[i] = in.readLong(); return array; } public static double[] readDoubleArray(InputReader in, int size) { double[] array = new double[size]; for (int i = 0; i < size; i++) array[i] = in.readDouble(); return array; } public static String[] readStringArray(InputReader in, int size) { String[] array = new String[size]; for (int i = 0; i < size; i++) array[i] = in.readString(); return array; } public static char[] readCharArray(InputReader in, int size) { char[] array = new char[size]; for (int i = 0; i < size; i++) array[i] = in.readCharacter(); return array; } public static Pair<Integer, Integer>[] readIntPairArray(InputReader in, int size) { @SuppressWarnings({ "unchecked" }) Pair<Integer, Integer>[] result = new Pair[size]; for (int i = 0; i < size; i++) result[i] = readIntPair(in); return result; } public static Pair<Long, Long>[] readLongPairArray(InputReader in, int size) { @SuppressWarnings({ "unchecked" }) Pair<Long, Long>[] result = new Pair[size]; for (int i = 0; i < size; i++) result[i] = readLongPair(in); return result; } public static void readIntArrays(InputReader in, int[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) arrays[j][i] = in.readInt(); } } public static void readLongArrays(InputReader in, long[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) arrays[j][i] = in.readLong(); } } public static void readDoubleArrays(InputReader in, double[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) arrays[j][i] = in.readDouble(); } } public static char[][] readTable(InputReader in, int rowCount, int columnCount) { char[][] table = new char[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readCharArray(in, columnCount); return table; } public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) { int[][] table = new int[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readIntArray(in, columnCount); return table; } public static double[][] readDoubleTable(InputReader in, int rowCount, int columnCount) { double[][] table = new double[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readDoubleArray(in, columnCount); return table; } public static long[][] readLongTable(InputReader in, int rowCount, int columnCount) { long[][] table = new long[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readLongArray(in, columnCount); return table; } public static String[][] readStringTable(InputReader in, int rowCount, int columnCount) { String[][] table = new String[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readStringArray(in, columnCount); return table; } public static String readText(InputReader in) { StringBuilder result = new StringBuilder(); while (true) { int character = in.read(); if (character == '\r') continue; if (character == -1) break; result.append((char) character); } return result.toString(); } public static void readStringArrays(InputReader in, String[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) arrays[j][i] = in.readString(); } } public static void printTable(OutputWriter out, char[][] table) { for (char[] row : table) out.printLine(new String(row)); } } class ArrayUtils { private static int[] tempInt = new int[0]; private static long[] tempLong = new long[0]; public static Integer[] generateOrder(int size) { Integer[] order = new Integer[size]; for (int i = 0; i < size; i++) order[i] = i; return order; } public static void fill(short[][] array, short value) { for (short[] row : array) Arrays.fill(row, value); } public static void fill(long[][] array, long value) { for (long[] row : array) Arrays.fill(row, value); } public static void fill(double[][] array, double value) { for (double[] row : array) Arrays.fill(row, value); } public static void fill(double[][][] array, double value) { for (double[][] row : array) fill(row, value); } public static void fill(double[][][][] array, double value) { for (double[][][] row : array) fill(row, value); } public static void fill(double[][][][][] array, double value) { for (double[][][][] row : array) fill(row, value); } public static void fill(long[][][] array, long value) { for (long[][] row : array) fill(row, value); } public static void fill(long[][][][] array, long value) { for (long[][][] row : array) fill(row, value); } public static void fill(long[][][][][] array, long value) { for (long[][][][] row : array) fill(row, value); } public static void fillColumn(long[][] array, int index, long value) { for (long[] row : array) row[index] = value; } public static void fillColumn(int[][] array, int index, int value) { for (int[] row : array) row[index] = value; } public static void fill(int[][] array, int value) { for (int[] row : array) Arrays.fill(row, value); } public static void fill(boolean[][] array, boolean value) { for (boolean[] row : array) Arrays.fill(row, value); } public static void fill(boolean[][][] array, boolean value) { for (boolean[][] row : array) fill(row, value); } public static long sumArray(int[] array) { long result = 0; for (int element : array) result += element; return result; } public static int[] range(int from, int to) { int[] result = new int[Math.max(from, to) - Math.min(from, to) + 1]; int index = 0; if (to > from) { for (int i = from; i <= to; i++) result[index++] = i; } else { for (int i = from; i >= to; i--) result[index++] = i; } return result; } public static void fill(int[][][] array, int value) { for (int[][] subArray : array) fill(subArray, value); } public static void fill(short[][][] array, short value) { for (short[][] subArray : array) fill(subArray, value); } public static void fill(int[][][][] array, int value) { for (int[][][] subArray : array) fill(subArray, value); } public static void fill(short[][][][] array, short value) { for (short[][][] subArray : array) fill(subArray, value); } public static void fill(int[][][][][] array, int value) { for (int[][][][] subArray : array) fill(subArray, value); } public static void fill(short[][][][][] array, short value) { for (short[][][][] subArray : array) fill(subArray, value); } public static void fill(int[][][][][][] array, int value) { for (int[][][][][] subArray : array) fill(subArray, value); } public static void fill(short[][][][][][] array, short value) { for (short[][][][][] subArray : array) fill(subArray, value); } public static void fill(int[][][][][][][] array, int value) { for (int[][][][][][] subArray : array) fill(subArray, value); } public static void fill(short[][][][][][][] array, short value) { for (short[][][][][][] subArray : array) fill(subArray, value); } public static Integer[] order(int size, Comparator<Integer> comparator) { Integer[] order = generateOrder(size); Arrays.sort(order, comparator); return order; } public static <T> void fill(T[][] array, T value) { for (T[] row : array) Arrays.fill(row, value); } public static void fill(char[][] array, char value) { for (char[] row : array) Arrays.fill(row, value); } public static void fill(byte[][] array, byte value) { for (byte[] row : array) Arrays.fill(row, value); } public static void fill(byte[][][] array, byte value) { for (byte[][] row : array) fill(row, value); } public static void fill(byte[][][][] array, byte value) { for (byte[][][] row : array) fill(row, value); } public static long multiply(int[] first, int[] second) { long result = 0; for (int i = 0; i < first.length; i++) result += (long) first[i] * second[i]; return result; } public static int[] createOrder(int size) { int[] order = new int[size]; for (int i = 0; i < size; i++) order[i] = i; return order; } public static int[] sort(int[] array, IntComparator comparator) { return sort(array, 0, array.length, comparator); } public static int[] sort(int[] array, int from, int to, IntComparator comparator) { Integer[] intArray = new Integer[to - from]; for (int i = from; i < to; i++) intArray[i - from] = array[i]; Arrays.sort(intArray, comparator); for (int i=from; i<to; i++) array[i]=intArray[i-from]; return array; } private static void ensureCapacityInt(int size) { if (tempInt.length >= size) return; size = Math.max(size, tempInt.length << 1); tempInt = new int[size]; } private static void ensureCapacityLong(int size) { if (tempLong.length >= size) return; size = Math.max(size, tempLong.length << 1); tempLong = new long[size]; } private static void sortImpl(int[] array, int from, int to, int[] temp, int fromTemp, int toTemp, IntComparator comparator) { if (to - from <= 1) return; int middle = (to - from) >> 1; int tempMiddle = fromTemp + middle; sortImpl(temp, fromTemp, tempMiddle, array, from, from + middle, comparator); sortImpl(temp, tempMiddle, toTemp, array, from + middle, to, comparator); int index = from; int index1 = fromTemp; int index2 = tempMiddle; while (index1 < tempMiddle && index2 < toTemp) { if (comparator.compare(temp[index1], temp[index2]) <= 0) array[index++] = temp[index1++]; else array[index++] = temp[index2++]; } if (index1 != tempMiddle) System.arraycopy(temp, index1, array, index, tempMiddle - index1); if (index2 != toTemp) System.arraycopy(temp, index2, array, index, toTemp - index2); } public static int[] order(final int[] array) { return sort(createOrder(array.length), new IntComparator() { public int compare(Integer first, Integer second) { if (array[first] < array[second]) return -1; if (array[first] > array[second]) return 1; return 0; } }); } public static int[] order(final long[] array) { return sort(createOrder(array.length), new IntComparator() { public int compare(Integer first, Integer second) { if (array[first] < array[second]) return -1; if (array[first] > array[second]) return 1; return 0; } }); } public static int[] unique(int[] array) { return unique(array, 0, array.length); } public static int[] unique(int[] array, int from, int to) { if (from == to) return new int[0]; int count = 1; for (int i = from + 1; i < to; i++) { if (array[i] != array[i - 1]) count++; } int[] result = new int[count]; result[0] = array[from]; int index = 1; for (int i = from + 1; i < to; i++) { if (array[i] != array[i - 1]) result[index++] = array[i]; } return result; } public static char[] unique(char[] array) { return unique(array, 0, array.length); } public static char[] unique(char[] array, int from, int to) { if (from == to) return new char[0]; int count = 1; for (int i = from + 1; i < to; i++) { if (array[i] != array[i - 1]) count++; } char[] result = new char[count]; result[0] = array[from]; int index = 1; for (int i = from + 1; i < to; i++) { if (array[i] != array[i - 1]) result[index++] = array[i]; } return result; } public static int maxElement(int[] array) { return maxElement(array, 0, array.length); } public static int maxElement(int[] array, int from, int to) { int result = Integer.MIN_VALUE; for (int i = from; i < to; i++) result = Math.max(result, array[i]); return result; } public static int[] order(final double[] array) { return sort(createOrder(array.length), new IntComparator() { public int compare(Integer first, Integer second) { return Double.compare(array[first], array[second]); } }); } public static int[] reversePermutation(int[] permutation) { int[] result = new int[permutation.length]; for (int i = 0; i < permutation.length; i++) result[permutation[i]] = i; return result; } public static void reverse(int[] array) { for (int i = 0, j = array.length - 1; i < j; i++, j--) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } public static void reverse(char[] array) { for (int i = 0, j = array.length - 1; i < j; i++, j--) { char temp = array[i]; array[i] = array[j]; array[j] = temp; } } private static long maxElement(long[] array, int from, int to) { long result = Long.MIN_VALUE; for (int i = from; i < to; i++) result = Math.max(result, array[i]); return result; } public static int minPosition(int[] array) { return minPosition(array, 0, array.length); } public static int maxPosition(int[] array) { return maxPosition(array, 0, array.length); } public static int minPosition(int[] array, int from, int to) { if (from >= to) return -1; int min = array[from]; int result = from; for (int i = from + 1; i < to; i++) { if (array[i] < min) { min = array[i]; result = i; } } return result; } public static int maxPosition(int[] array, int from, int to) { if (from >= to) return -1; int max = array[from]; int result = from; for (int i = from + 1; i < to; i++) { if (array[i] > max) { max = array[i]; result = i; } } return result; } public static int[] multiplyPermutations(int[] first, int[] second) { int count = first.length; int[] result = new int[count]; for (int i = 0; i < count; i++) { result[i] = first[second[i]]; } return result; } public static int[] compress(int[]... arrays) { int totalLength = 0; for (int[] array : arrays) totalLength += array.length; int[] all = new int[totalLength]; int delta = 0; for (int[] array : arrays) { System.arraycopy(array, 0, all, delta, array.length); delta += array.length; } sort(all, IntComparator.DEFAULT); all = unique(all); for (int[] array : arrays) { for (int i = 0; i < array.length; i++) array[i] = Arrays.binarySearch(all, array[i]); } return all; } public static int minElement(int[] array) { return array[minPosition(array)]; } public static long[] partialSums(int[] array) { long[] result = new long[array.length + 1]; for (int i = 0; i < array.length; i++) result[i + 1] = result[i] + array[i]; return result; } public static void orderBy(int[] base, int[]... arrays) { int[] order = ArrayUtils.order(base); order(order, base); for (int[] array : arrays) order(order, array); } public static void orderBy(long[] base, long[]... arrays) { int[] order = ArrayUtils.order(base); order(order, base); for (long[] array : arrays) order(order, array); } public static void order(int[] order, int[] array) { ensureCapacityInt(order.length); for (int i = 0; i < order.length; i++) tempInt[i] = array[order[i]]; System.arraycopy(tempInt, 0, array, 0, array.length); } public static void order(int[] order, long[] array) { ensureCapacityLong(order.length); for (int i = 0; i < order.length; i++) tempLong[i] = array[order[i]]; System.arraycopy(tempLong, 0, array, 0, array.length); } public static long[] asLong(int[] array) { long[] result = new long[array.length]; for (int i = 0; i < array.length; i++) result[i] = array[i]; return result; } public static int count(int[] array, int value) { int result = 0; for (int i : array) { if (i == value) result++; } return result; } public static int count(char[] array, char value) { int result = 0; for (char i : array) { if (i == value) result++; } return result; } public static int count(boolean[] array, boolean value) { int result = 0; for (boolean i : array) { if (i == value) result++; } return result; } public static int[] merge(int[] first, int[] second) { int[] result = new int[first.length + second.length]; int firstIndex = 0; int secondIndex = 0; int index = 0; while (firstIndex < first.length && secondIndex < second.length) { if (first[firstIndex] < second[secondIndex]) result[index++] = first[firstIndex++]; else result[index++] = second[secondIndex++]; } System.arraycopy(first, firstIndex, result, index, first.length - firstIndex); System.arraycopy(second, secondIndex, result, index, second.length - secondIndex); return result; } public static boolean nextPermutation(int[] array) { return nextPermutation(array, IntComparator.DEFAULT); } private static boolean nextPermutation(int[] array, IntComparator comparator) { int size = array.length; int last = array[size - 1]; for (int i = size - 2; i >= 0; i--) { int current = array[i]; if (comparator.compare(last, current) > 0) { for (int j = size - 1; j > i; j--) { if (comparator.compare(array[j], current) > 0) { swap(array, i, j); inPlaceReverse(array, i + 1, size); return true; } } } last = current; } return false; } private static void inPlaceReverse(int[] array, int first, int second) { for (int i = first, j = second - 1; i < j; i++, j--) swap(array, i, j); } private static void swap(int[] array, int first, int second) { if (first == second) return; int temp = array[first]; array[first] = array[second]; array[second] = temp; } public static <V> void reverse(V[] array) { for (int i = 0, j = array.length - 1; i < j; i++, j--) { V temp = array[i]; array[i] = array[j]; array[j] = temp; } } public static IntComparator compareBy(final int[]... arrays) { return new IntComparator() { public int compare(Integer first, Integer second) { for (int[] array : arrays) { if (array[first] != array[second]) return Integer.compare(array[first], array[second]); } return 0; } }; } public static long minElement(long[] array) { return array[minPosition(array)]; } public static long maxElement(long[] array) { return array[maxPosition(array)]; } public static int minPosition(long[] array) { return minPosition(array, 0, array.length); } public static int maxPosition(long[] array) { return maxPosition(array, 0, array.length); } public static int minPosition(long[] array, int from, int to) { if (from >= to) return -1; long min = array[from]; int result = from; for (int i = from + 1; i < to; i++) { if (array[i] < min) { min = array[i]; result = i; } } return result; } public static int maxPosition(long[] array, int from, int to) { if (from >= to) return -1; long max = array[from]; int result = from; for (int i = from + 1; i < to; i++) { if (array[i] > max) { max = array[i]; result = i; } } return result; } public static int[] createArray(int count, int value) { int[] array = new int[count]; Arrays.fill(array, value); return array; } public static long[] createArray(int count, long value) { long[] array = new long[count]; Arrays.fill(array, value); return array; } public static double[] createArray(int count, double value) { double[] array = new double[count]; Arrays.fill(array, value); return array; } public static boolean[] createArray(int count, boolean value) { boolean[] array = new boolean[count]; Arrays.fill(array, value); return array; } public static char[] createArray(int count, char value) { char[] array = new char[count]; Arrays.fill(array, value); return array; } public static <T> T[] createArray(int count, T value) { @SuppressWarnings("unchecked") T[] array = (T[]) Array.newInstance(value.getClass(), count); Arrays.fill(array, value); return array; } } class Graph { public static final int REMOVED_BIT = 0; protected int vertexCount; protected int edgeCount; private int[] firstOutbound; private int[] firstInbound; private Edge[] edges; private int[] nextInbound; private int[] nextOutbound; private int[] from; private int[] to; private long[] weight; private long[] capacity; private int[] reverseEdge; private int[] flags; public Graph(int vertexCount) { this(vertexCount, vertexCount); } public Graph(int vertexCount, int edgeCapacity) { this.vertexCount = vertexCount; firstOutbound = new int[vertexCount]; Arrays.fill(firstOutbound, -1); from = new int[edgeCapacity]; to = new int[edgeCapacity]; nextOutbound = new int[edgeCapacity]; flags = new int[edgeCapacity]; } public static Graph createGraph(int vertexCount, int[] from, int[] to) { Graph graph = new Graph(vertexCount, from.length); for (int i = 0; i < from.length; i++) graph.addSimpleEdge(from[i], to[i]); return graph; } public static Graph createWeightedGraph(int vertexCount, int[] from, int[] to, long[] weight) { Graph graph = new Graph(vertexCount, from.length); for (int i = 0; i < from.length; i++) graph.addWeightedEdge(from[i], to[i], weight[i]); return graph; } public static Graph createFlowGraph(int vertexCount, int[] from, int[] to, long[] capacity) { Graph graph = new Graph(vertexCount, from.length * 2); for (int i = 0; i < from.length; i++) graph.addFlowEdge(from[i], to[i], capacity[i]); return graph; } public static Graph createFlowWeightedGraph(int vertexCount, int[] from, int[] to, long[] weight, long[] capacity) { Graph graph = new Graph(vertexCount, from.length * 2); for (int i = 0; i < from.length; i++) graph.addFlowWeightedEdge(from[i], to[i], weight[i], capacity[i]); return graph; } public static Graph createTree(int[] parent) { Graph graph = new Graph(parent.length + 1, parent.length); for (int i = 0; i < parent.length; i++) graph.addSimpleEdge(parent[i], i + 1); return graph; } public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) { ensureEdgeCapacity(edgeCount + 1); if (firstOutbound[fromID] != -1) nextOutbound[edgeCount] = firstOutbound[fromID]; else nextOutbound[edgeCount] = -1; firstOutbound[fromID] = edgeCount; if (firstInbound != null) { if (firstInbound[toID] != -1) nextInbound[edgeCount] = firstInbound[toID]; else nextInbound[edgeCount] = -1; firstInbound[toID] = edgeCount; } this.from[edgeCount] = fromID; this.to[edgeCount] = toID; if (capacity != 0) { if (this.capacity == null) this.capacity = new long[from.length]; this.capacity[edgeCount] = capacity; } if (weight != 0) { if (this.weight == null) this.weight = new long[from.length]; this.weight[edgeCount] = weight; } if (reverseEdge != -1) { if (this.reverseEdge == null) { this.reverseEdge = new int[from.length]; Arrays.fill(this.reverseEdge, 0, edgeCount, -1); } this.reverseEdge[edgeCount] = reverseEdge; } if (edges != null) edges[edgeCount] = createEdge(edgeCount); return edgeCount++; } protected final GraphEdge createEdge(int id) { return new GraphEdge(id); } public final int addFlowWeightedEdge(int from, int to, long weight, long capacity) { if (capacity == 0) { return addEdge(from, to, weight, 0, -1); } else { int lastEdgeCount = edgeCount; addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge()); return addEdge(from, to, weight, capacity, lastEdgeCount); } } protected int entriesPerEdge() { return 1; } public final int addFlowEdge(int from, int to, long capacity) { return addFlowWeightedEdge(from, to, 0, capacity); } public final int addWeightedEdge(int from, int to, long weight) { return addFlowWeightedEdge(from, to, weight, 0); } public final int addSimpleEdge(int from, int to) { return addWeightedEdge(from, to, 0); } public final int vertexCount() { return vertexCount; } public final int edgeCount() { return edgeCount; } protected final int edgeCapacity() { return from.length; } public final Edge edge(int id) { initEdges(); return edges[id]; } public final int firstOutbound(int vertex) { int id = firstOutbound[vertex]; while (id != -1 && isRemoved(id)) id = nextOutbound[id]; return id; } public final int nextOutbound(int id) { id = nextOutbound[id]; while (id != -1 && isRemoved(id)) id = nextOutbound[id]; return id; } public final int firstInbound(int vertex) { initInbound(); int id = firstInbound[vertex]; while (id != -1 && isRemoved(id)) id = nextInbound[id]; return id; } public final int nextInbound(int id) { initInbound(); id = nextInbound[id]; while (id != -1 && isRemoved(id)) id = nextInbound[id]; return id; } public final int source(int id) { return from[id]; } public final int destination(int id) { return to[id]; } public final long weight(int id) { if (weight == null) return 0; return weight[id]; } public final long capacity(int id) { if (capacity == null) return 0; return capacity[id]; } public final long flow(int id) { if (reverseEdge == null) return 0; return capacity[reverseEdge[id]]; } public final void pushFlow(int id, long flow) { if (flow == 0) return; if (flow > 0) { if (capacity(id) < flow) throw new IllegalArgumentException("Not enough capacity"); } else { if (flow(id) < -flow) throw new IllegalArgumentException("Not enough capacity"); } capacity[id] -= flow; capacity[reverseEdge[id]] += flow; } public int transposed(int id) { return -1; } public final int reverse(int id) { if (reverseEdge == null) return -1; return reverseEdge[id]; } public final void addVertices(int count) { ensureVertexCapacity(vertexCount + count); Arrays.fill(firstOutbound, vertexCount, vertexCount + count, -1); if (firstInbound != null) Arrays.fill(firstInbound, vertexCount, vertexCount + count, -1); vertexCount += count; } protected final void initEdges() { if (edges == null) { edges = new Edge[from.length]; for (int i = 0; i < edgeCount; i++) edges[i] = createEdge(i); } } public final void removeVertex(int vertex) { int id = firstOutbound[vertex]; while (id != -1) { removeEdge(id); id = nextOutbound[id]; } initInbound(); id = firstInbound[vertex]; while (id != -1) { removeEdge(id); id = nextInbound[id]; } } private void initInbound() { if (firstInbound == null) { firstInbound = new int[firstOutbound.length]; Arrays.fill(firstInbound, 0, vertexCount, -1); nextInbound = new int[from.length]; for (int i = 0; i < edgeCount; i++) { nextInbound[i] = firstInbound[to[i]]; firstInbound[to[i]] = i; } } } public final boolean flag(int id, int bit) { return (flags[id] >> bit & 1) != 0; } public final void setFlag(int id, int bit) { flags[id] |= 1 << bit; } public final void removeFlag(int id, int bit) { flags[id] &= -1 - (1 << bit); } public final void removeEdge(int id) { setFlag(id, REMOVED_BIT); } public final void restoreEdge(int id) { removeFlag(id, REMOVED_BIT); } public final boolean isRemoved(int id) { return flag(id, REMOVED_BIT); } public final Iterable<Edge> outbound(final int id) { initEdges(); return new Iterable<Edge>() { public Iterator<Edge> iterator() { return new EdgeIterator(id, firstOutbound, nextOutbound); } }; } public final Iterable<Edge> inbound(final int id) { initEdges(); initInbound(); return new Iterable<Edge>() { public Iterator<Edge> iterator() { return new EdgeIterator(id, firstInbound, nextInbound); } }; } protected void ensureEdgeCapacity(int size) { if (from.length < size) { int newSize = Math.max(size, 2 * from.length); if (edges != null) edges = resize(edges, newSize); from = resize(from, newSize); to = resize(to, newSize); nextOutbound = resize(nextOutbound, newSize); if (nextInbound != null) nextInbound = resize(nextInbound, newSize); if (weight != null) weight = resize(weight, newSize); if (capacity != null) capacity = resize(capacity, newSize); if (reverseEdge != null) reverseEdge = resize(reverseEdge, newSize); flags = resize(flags, newSize); } } private void ensureVertexCapacity(int size) { if (firstOutbound.length < size) { int newSize = Math.max(size, 2 * from.length); firstOutbound = resize(firstOutbound, newSize); if (firstInbound != null) firstInbound = resize(firstInbound, newSize); } } protected final int[] resize(int[] array, int size) { int[] newArray = new int[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private long[] resize(long[] array, int size) { long[] newArray = new long[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private Edge[] resize(Edge[] array, int size) { Edge[] newArray = new Edge[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } public final boolean isSparse() { return vertexCount == 0 || edgeCount * 20 / vertexCount <= vertexCount; } protected class GraphEdge implements Edge { protected int id; protected GraphEdge(int id) { this.id = id; } public int getSource() { return source(id); } public int getDestination() { return destination(id); } public long getWeight() { return weight(id); } public long getCapacity() { return capacity(id); } public long getFlow() { return flow(id); } public void pushFlow(long flow) { Graph.this.pushFlow(id, flow); } public boolean getFlag(int bit) { return flag(id, bit); } public void setFlag(int bit) { Graph.this.setFlag(id, bit); } public void removeFlag(int bit) { Graph.this.removeFlag(id, bit); } public int getTransposedID() { return transposed(id); } public Edge getTransposedEdge() { int reverseID = getTransposedID(); if (reverseID == -1) return null; initEdges(); return edge(reverseID); } public int getReverseID() { return reverse(id); } public Edge getReverseEdge() { int reverseID = getReverseID(); if (reverseID == -1) return null; initEdges(); return edge(reverseID); } public int getID() { return id; } public void remove() { removeEdge(id); } public void restore() { restoreEdge(id); } } public class EdgeIterator implements Iterator<Edge> { private int edgeID; private final int[] next; private int lastID = -1; public EdgeIterator(int id, int[] first, int[] next) { this.next = next; edgeID = nextEdge(first[id]); } private int nextEdge(int id) { while (id != -1 && isRemoved(id)) id = next[id]; return id; } public boolean hasNext() { return edgeID != -1; } public Edge next() { if (edgeID == -1) throw new NoSuchElementException(); lastID = edgeID; edgeID = nextEdge(next[lastID]); return edges[lastID]; } public void remove() { if (lastID == -1) throw new IllegalStateException(); removeEdge(lastID); lastID = -1; } } } class MiscUtils { public static final int[] DX4 = { 1, 0, -1, 0 }; public static final int[] DY4 = { 0, -1, 0, 1 }; public static final int[] DX8 = { 1, 1, 1, 0, -1, -1, -1, 0 }; public static final int[] DY8 = { -1, 0, 1, 1, 1, 0, -1, -1 }; public static final int[] DX_KNIGHT = { 2, 1, -1, -2, -2, -1, 1, 2 }; public static final int[] DY_KNIGHT = { 1, 2, 2, 1, -1, -2, -2, -1 }; private static final String[] ROMAN_TOKENS = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; private static final int[] ROMAN_VALUES = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; public static long josephProblem(long n, int k) { if (n == 1) return 0; if (k == 1) return n - 1; if (k > n) return (josephProblem(n - 1, k) + k) % n; long count = n / k; long result = josephProblem(n - count, k); result -= n % k; if (result < 0) result += n; else result += result / (k - 1); return result; } public static boolean isValidCell(int row, int column, int rowCount, int columnCount) { return row >= 0 && row < rowCount && column >= 0 && column < columnCount; } public static List<Integer> getPath(int[] last, int destination) { List<Integer> path = new ArrayList<Integer>(); while (destination != -1) { path.add(destination); destination = last[destination]; } inPlaceReverse(path); return path; } private static void inPlaceReverse(List<Integer> list) { for (int i = 0, j = list.size() - 1; i < j; i++, j--) swap(list, i, j); } private static void swap(List<Integer> list, int first, int second) { if (first == second) return; int temp = list.get(first); list.set(first, list.get(second)); list.set(second, temp); } public static List<Integer> getPath(int[][] lastIndex, int[][] lastPathNumber, int destination, int pathNumber) { List<Integer> path = new ArrayList<Integer>(); while (destination != -1 || pathNumber != 0) { path.add(destination); int nextDestination = lastIndex[destination][pathNumber]; pathNumber = lastPathNumber[destination][pathNumber]; destination = nextDestination; } inPlaceReverse(path); return path; } public static long maximalRectangleSum(long[][] array) { int n = array.length; int m = array[0].length; long[][] partialSums = new long[n + 1][m + 1]; for (int i = 0; i < n; i++) { long rowSum = 0; for (int j = 0; j < m; j++) { rowSum += array[i][j]; partialSums[i + 1][j + 1] = partialSums[i][j + 1] + rowSum; } } long result = Long.MIN_VALUE; for (int i = 0; i < m; i++) { for (int j = i; j < m; j++) { long minPartialSum = 0; for (int k = 1; k <= n; k++) { long current = partialSums[k][j + 1] - partialSums[k][i]; result = Math.max(result, current - minPartialSum); minPartialSum = Math.min(minPartialSum, current); } } } return result; } public static int parseIP(String ip) { String[] components = ip.split("[.]"); int result = 0; for (int i = 0; i < 4; i++) result += (1 << (24 - 8 * i)) * Integer.parseInt(components[i]); return result; } public static String buildIP(int mask) { StringBuilder result = new StringBuilder(); for (int i = 0; i < 4; i++) { if (i != 0) result.append('.'); result.append(mask >> (24 - 8 * i) & 255); } return result.toString(); } public static long binarySearch(long from, long to, Function<Long, Boolean> function) { while (from < to) { long argument = from + (to - from) / 2; if (function.value(argument)) to = argument; else from = argument + 1; } return from; } public static <T> boolean equals(T first, T second) { return first == null && second == null || first != null && first.equals(second); } public static boolean isVowel(char ch) { ch = Character.toUpperCase(ch); return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' || ch == 'Y'; } public static boolean isStrictVowel(char ch) { ch = Character.toUpperCase(ch); return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'; } public static String convertToRoman(int number) { StringBuilder result = new StringBuilder(); for (int i = 0; i < ROMAN_TOKENS.length; i++) { while (number >= ROMAN_VALUES[i]) { number -= ROMAN_VALUES[i]; result.append(ROMAN_TOKENS[i]); } } return result.toString(); } public static int convertFromRoman(String number) { int result = 0; for (int i = 0; i < ROMAN_TOKENS.length; i++) { while (number.startsWith(ROMAN_TOKENS[i])) { number = number.substring(ROMAN_TOKENS[i].length()); result += ROMAN_VALUES[i]; } } return result; } public static int distance(int x1, int y1, int x2, int y2) { int dx = x1 - x2; int dy = y1 - y2; return dx * dx + dy * dy; } public static <T extends Comparable<T>> T min(T first, T second) { if (first.compareTo(second) <= 0) return first; return second; } public static <T extends Comparable<T>> T max(T first, T second) { if (first.compareTo(second) <= 0) return second; return first; } public static void decreaseByOne(int[]... arrays) { for (int[] array : arrays) { for (int i = 0; i < array.length; i++) array[i]--; } } public static int[] getIntArray(String s) { String[] tokens = s.split(" "); int[] result = new int[tokens.length]; for (int i = 0; i < result.length; i++) result[i] = Integer.parseInt(tokens[i]); return result; } } class IntegerUtils { public static long gcd(long a, long b) { a = Math.abs(a); b = Math.abs(b); while (b != 0) { long temp = a % b; a = b; b = temp; } return a; } public static int gcd(int a, int b) { a = Math.abs(a); b = Math.abs(b); while (b != 0) { int temp = a % b; a = b; b = temp; } return a; } public static int[] generatePrimes(int upTo) { int[] isPrime = generateBitPrimalityTable(upTo); List<Integer> primes = new ArrayList<Integer>(); for (int i = 0; i < upTo; i++) { if ((isPrime[i >> 5] >>> (i & 31) & 1) == 1) primes.add(i); } int[] array = new int[primes.size()]; for (int i = 0; i < array.length; i++) array[i] = primes.get(i); return array; } public static boolean[] generatePrimalityTable(int upTo) { boolean[] isPrime = new boolean[upTo]; if (upTo < 2) return isPrime; Arrays.fill(isPrime, true); isPrime[0] = isPrime[1] = false; for (int i = 2; i * i < upTo; i++) { if (isPrime[i]) { for (int j = i * i; j < upTo; j += i) isPrime[j] = false; } } return isPrime; } public static int[] generateBitPrimalityTable(int upTo) { int[] isPrime = new int[(upTo + 31) >> 5]; if (upTo < 2) return isPrime; Arrays.fill(isPrime, -1); isPrime[0] &= -4; for (int i = 2; i * i < upTo; i++) { if ((isPrime[i >> 5] >>> (i & 31) & 1) == 1) { for (int j = i * i; j < upTo; j += i) isPrime[j >> 5] &= -1 - (1 << (j & 31)); } } return isPrime; } public static int[] generateDivisorTable(int upTo) { int[] divisor = new int[upTo]; for (int i = 1; i < upTo; i++) divisor[i] = i; for (int i = 2; i * i < upTo; i++) { if (divisor[i] == i) { for (int j = i * i; j < upTo; j += i) divisor[j] = i; } } return divisor; } public static long powerInFactorial(long n, long p) { long result = 0; while (n != 0) { result += n /= p; } return result; } public static int sumDigits(CharSequence number) { int result = 0; for (int i = number.length() - 1; i >= 0; i--) result += digitValue(number.charAt(i)); return result; } public static int digitValue(char digit) { if (Character.isDigit(digit)) return digit - '0'; if (Character.isUpperCase(digit)) return digit + 10 - 'A'; return digit + 10 - 'a'; } public static int longCompare(long a, long b) { if (a < b) return -1; if (a > b) return 1; return 0; } public static long[][] generateBinomialCoefficients(int n) { long[][] result = new long[n + 1][n + 1]; for (int i = 0; i <= n; i++) { result[i][0] = 1; for (int j = 1; j <= i; j++) result[i][j] = result[i - 1][j - 1] + result[i - 1][j]; } return result; } public static long[][] generateBinomialCoefficients(int n, long module) { long[][] result = new long[n + 1][n + 1]; if (module == 1) return result; for (int i = 0; i <= n; i++) { result[i][0] = 1; for (int j = 1; j <= i; j++) { result[i][j] = result[i - 1][j - 1] + result[i - 1][j]; if (result[i][j] >= module) result[i][j] -= module; } } return result; } public static long[] generateBinomialRow(int n, long module) { long[] result = generateReverse(n + 1, module); result[0] = 1; for (int i = 1; i <= n; i++) result[i] = result[i - 1] * (n - i + 1) % module * result[i] % module; return result; } public static int[] representationInBase(long number, int base) { long basePower = base; int exponent = 1; while (number >= basePower) { basePower *= base; exponent++; } int[] representation = new int[exponent]; for (int i = 0; i < exponent; i++) { basePower /= base; representation[i] = (int) (number / basePower); number %= basePower; } return representation; } public static int trueDivide(int a, int b) { return (a - trueMod(a, b)) / b; } public static long trueDivide(long a, long b) { return (a - trueMod(a, b)) / b; } public static int trueMod(int a, int b) { a %= b; a += b; a %= b; return a; } public static long trueMod(long a, long b) { a %= b; a += b; a %= b; return a; } public static long factorial(int n) { long result = 1; for (int i = 2; i <= n; i++) result *= i; return result; } public static long factorial(int n, long mod) { long result = 1; for (int i = 2; i <= n; i++) result = result * i % mod; return result % mod; } public static List<Pair<Long, Integer>> factorize(long number) { List<Pair<Long, Integer>> result = new ArrayList<Pair<Long, Integer>>(); for (long i = 2; i * i <= number; i++) { if (number % i == 0) { int power = 0; do { power++; number /= i; } while (number % i == 0); result.add(Pair.makePair(i, power)); } } if (number != 1) result.add(Pair.makePair(number, 1)); return result; } public static List<Long> getDivisors(long number) { List<Pair<Long, Integer>> primeDivisors = factorize(number); return getDivisorsImpl(primeDivisors, 0, 1, new ArrayList<Long>()); } private static List<Long> getDivisorsImpl( List<Pair<Long, Integer>> primeDivisors, int index, long current, List<Long> result) { if (index == primeDivisors.size()) { result.add(current); return result; } long p = primeDivisors.get(index).first; int power = primeDivisors.get(index).second; for (int i = 0; i <= power; i++) { getDivisorsImpl(primeDivisors, index + 1, current, result); current *= p; } return result; } public static long power(long base, long exponent) { if (exponent == 0) return 1; long result = power(base, exponent >> 1); result = result * result; if ((exponent & 1) != 0) result = result * base; return result; } public static long power(long base, long exponent, long mod) { if (base >= mod) base %= mod; if (exponent == 0) return 1 % mod; long result = power(base, exponent >> 1, mod); result = result * result % mod; if ((exponent & 1) != 0) result = result * base % mod; return result; } public static long lcm(long a, long b) { return a / gcd(a, b) * b; } public static long[] generateFibonacci(long upTo) { int count = 0; long last = 0; long current = 1; while (current <= upTo) { long next = last + current; last = current; current = next; count++; } return generateFibonacci(count, -1); } public static long[] generateFibonacci(int count, long module) { long[] result = new long[count]; if (module == -1) { if (count != 0) result[0] = 1; if (count > 1) result[1] = 1; for (int i = 2; i < count; i++) result[i] = result[i - 1] + result[i - 2]; } else { if (count != 0) result[0] = 1 % module; if (count > 1) result[1] = 1 % module; for (int i = 2; i < count; i++) result[i] = (result[i - 1] + result[i - 2]) % module; } return result; } public static long[] generateHappy(int digits) { long[] happy = new long[(1 << (digits + 1)) - 2]; happy[0] = 4; happy[1] = 7; int first = 0; int last = 2; for (int i = 2; i <= digits; i++) { for (int j = 0; j < last - first; j++) { happy[last + 2 * j] = 10 * happy[first + j] + 4; happy[last + 2 * j + 1] = 10 * happy[first + j] + 7; } int next = last + 2 * (last - first); first = last; last = next; } return happy; } public static long[] generateFactorial(int count, long module) { long[] result = new long[count]; if (module == -1) { if (count != 0) result[0] = 1; for (int i = 1; i < count; i++) result[i] = result[i - 1] * i; } else { if (count != 0) result[0] = 1 % module; for (int i = 1; i < count; i++) result[i] = (result[i - 1] * i) % module; } return result; } public static long reverse(long number, long module) { return power(number, module - 2, module); } public static boolean isPrime(long number) { if (number < 2) return false; for (long i = 2; i * i <= number; i++) { if (number % i == 0) return false; } return true; } public static long[] generateReverse(int upTo, long module) { long[] result = new long[upTo]; if (upTo > 1) result[1] = 1; for (int i = 2; i < upTo; i++) result[i] = (module - module / i * result[((int) (module % i))] % module) % module; return result; } public static long[] generateReverseFactorials(int upTo, long module) { long[] result = generateReverse(upTo, module); if (upTo > 0) result[0] = 1; for (int i = 1; i < upTo; i++) result[i] = result[i] * result[i - 1] % module; return result; } public static long[] generatePowers(long base, int count, long mod) { long[] result = new long[count]; if (count != 0) result[0] = 1 % mod; for (int i = 1; i < count; i++) result[i] = result[i - 1] * base % mod; return result; } public static long nextPrime(long from) { if (from <= 2) return 2; from += 1 - (from & 1); while (!isPrime(from)) from += 2; return from; } public static long binomialCoefficient(int n, int m, long mod) { if (m < 0 || m > n) return 0; if (2 * m > n) m = n - m; long result = 1; for (int i = n - m + 1; i <= n; i++) result = result * i % mod; return result * BigInteger.valueOf(factorial(m, mod)) .modInverse(BigInteger.valueOf(mod)).longValue() % mod; } public static boolean isSquare(long number) { long sqrt = Math.round(Math.sqrt(number)); return sqrt * sqrt == number; } public static long findCommon(long aRemainder, long aMod, long bRemainder, long bMod) { long modGCD = gcd(aMod, bMod); long gcdRemainder = aRemainder % modGCD; if (gcdRemainder != bRemainder % modGCD) return -1; aMod /= modGCD; aRemainder /= modGCD; bMod /= modGCD; bRemainder /= modGCD; long aReverse = BigInteger.valueOf(aMod) .modInverse(BigInteger.valueOf(bMod)).longValue(); long bReverse = BigInteger.valueOf(bMod) .modInverse(BigInteger.valueOf(aMod)).longValue(); long mod = aMod * bMod; return (bReverse * aRemainder % mod * bMod + aReverse * bRemainder % mod * aMod) % mod * modGCD + gcdRemainder; } public static long[] generatePowers(long base, long maxValue) { if (maxValue <= 0) return new long[0]; int size = 1; long current = 1; while (maxValue / base >= current) { current *= base; size++; } return generatePowers(base, size, Long.MAX_VALUE); } } interface IntComparator extends Comparator<Integer> { public static final IntComparator DEFAULT = new IntComparator() { public int compare(Integer first, Integer second) { if (first < second) return -1; if (first > second) return 1; return 0; } }; public static final IntComparator REVERSE = new IntComparator() { public int compare(Integer first, Integer second) { if (first < second) return 1; if (first > second) return -1; return 0; } }; public int compare(Integer first, Integer second); } class BidirectionalGraph extends Graph { public int[] transposedEdge; public BidirectionalGraph(int vertexCount) { this(vertexCount, vertexCount); } public BidirectionalGraph(int vertexCount, int edgeCapacity) { super(vertexCount, 2 * edgeCapacity); transposedEdge = new int[2 * edgeCapacity]; } public static BidirectionalGraph createGraph(int vertexCount, int[] from, int[] to) { BidirectionalGraph graph = new BidirectionalGraph(vertexCount, from.length); for (int i = 0; i < from.length; i++) graph.addSimpleEdge(from[i], to[i]); return graph; } public static BidirectionalGraph createWeightedGraph(int vertexCount, int[] from, int[] to, long[] weight) { BidirectionalGraph graph = new BidirectionalGraph(vertexCount, from.length); for (int i = 0; i < from.length; i++) graph.addWeightedEdge(from[i], to[i], weight[i]); return graph; } public static BidirectionalGraph createFlowGraph(int vertexCount, int[] from, int[] to, long[] capacity) { BidirectionalGraph graph = new BidirectionalGraph(vertexCount, from.length * 2); for (int i = 0; i < from.length; i++) graph.addFlowEdge(from[i], to[i], capacity[i]); return graph; } public static BidirectionalGraph createFlowWeightedGraph(int vertexCount, int[] from, int[] to, long[] weight, long[] capacity) { BidirectionalGraph graph = new BidirectionalGraph(vertexCount, from.length * 2); for (int i = 0; i < from.length; i++) graph.addFlowWeightedEdge(from[i], to[i], weight[i], capacity[i]); return graph; } @Override public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) { int lastEdgeCount = edgeCount; super.addEdge(fromID, toID, weight, capacity, reverseEdge); super.addEdge(toID, fromID, weight, capacity, reverseEdge == -1 ? -1 : reverseEdge + 1); this.transposedEdge[lastEdgeCount] = lastEdgeCount + 1; this.transposedEdge[lastEdgeCount + 1] = lastEdgeCount; return lastEdgeCount; } @Override protected int entriesPerEdge() { return 2; } @Override public final int transposed(int id) { return transposedEdge[id]; } @Override protected void ensureEdgeCapacity(int size) { if (size > edgeCapacity()) { super.ensureEdgeCapacity(size); transposedEdge = resize(transposedEdge, edgeCapacity()); } } } class Pair<U, V> implements Comparable<Pair<U, V>> { public final U first; public final V second; public static <U, V> Pair<U, V> makePair(U first, V second) { return new Pair<U, V>(first, second); } private Pair(U first, V second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null); } @Override public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } public Pair<V, U> swap() { return makePair(second, first); } @Override public String toString() { return "(" + first + "," + second + ")"; } @SuppressWarnings({ "unchecked" }) public int compareTo(Pair<U, V> o) { int value = ((Comparable<U>) first).compareTo(o.first); if (value != 0) return value; return ((Comparable<V>) second).compareTo(o.second); } } interface Edge { public int getSource(); public int getDestination(); public long getWeight(); public long getCapacity(); public long getFlow(); public void pushFlow(long flow); public boolean getFlag(int bit); public void setFlag(int bit); public void removeFlag(int bit); public int getTransposedID(); public Edge getTransposedEdge(); public int getReverseID(); public Edge getReverseEdge(); public int getID(); public void remove(); public void restore(); } interface Function<A, V> { public abstract V value(A argument); }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
3cf92c891edbc047a449ca319a869e24
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.util.Scanner; public class Q415C { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int half = n/2; if(half > k || (n == 1 && k != 0)) System.out.println("-1"); else if(half == k) { for(int i = 1 ; i <= n ; i++) { System.out.print(i+" "); } } else { int extra = k-half; System.out.print((extra+1) + " "); System.out.print(2*(extra+1) + " "); for(int i = (2*(extra+1))+1 ; i < (2*(extra+1))+1+n-2 ; i++) { System.out.print(i+" "); } } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
835c346847c7c09134a71498303dc5aa
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.io.BufferedReader; import java.io.File; 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.math.BigInteger; import java.util.StringTokenizer; import java.util.TreeSet; public class MashmokhAndNumbersR415C { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); if (n == 1) { if (k == 0) System.out.println(1); else System.out.println(-1); } else { if (k < n / 2) System.out.println(-1); else { PrintWriter pw = new PrintWriter(System.out); int num = k - n / 2 + 1; pw.printf("%d %d ", num, num * 2); TreeSet<Integer> set = new TreeSet<>(); set.add(num); set.add(num * 2); for (int i = 1, j = 1; i <= n / 2 - 1; j += 2) { if (set.contains(j) || set.contains(j + 1)) continue; pw.printf("%d %d ", j, j + 1); i++; } if (n % 2 == 1) pw.println(999999999); else pw.println(); pw.flush(); } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(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
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
46042961ebd064ed8a9938332c179c87
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ static PrintWriter out=new PrintWriter(System.out); public static void main (String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String[] temp=br.readLine().trim().split(" "); int n=Integer.parseInt(temp[0]); int k=Integer.parseInt(temp[1]); printArray(n,k); out.flush(); out.close(); } public static void printArray(int n,int k) { if(n==1){ if(k==0){ out.println(1); return; } else{ out.println(-1); return; } } if(n/2>k){ out.println(-1); return; } int[] ans=new int[n]; for(int i=0;i<n;i++) { ans[i]=i+1; if(i%2!=0){ k--; } } k++; int first,second; int remainder=(n+1)%k; first=(n+1)+(k-remainder); second=first+k; ans[0]=first; ans[1]=second; for(int i=0;i<n;i++){ out.print(ans[i]+" "); } out.println(); } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
e65d3fd3ee39dd27c0ce68c6800de569
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author zodiacLeo */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { private int N = ((int) 2e6); private TreeSet<Integer> primes = new TreeSet<>(); public void solve(int testNumber, FastScanner in, FastPrinter out) { createSieve(); int n = in.nextInt(); int k = in.nextInt(); if (k == 0) { if (n == 1) { out.println(1); return; } else { out.println(-1); return; } } if (n == 1) { out.println(-1); return; } int min = n / 2; if (k < min) { out.println(-1); return; } TreeSet<Integer> used = new TreeSet<>(); int first = (k - min) + 1; int second = first * 2; used.add(first); used.add(second); StringBuilder sb = new StringBuilder(""); sb.append(first + " " + second + " "); int left = n - 2; while (left >= 2) { while (true) { int f = primes.pollFirst(); int s = primes.pollFirst(); if (used.contains(f) || used.contains(s)) { continue; } left -= 2; used.add(f); used.add(s); sb.append(f + " " + s + " "); break; } } if (left > 0) { while (true) { int f = primes.pollFirst(); if (used.contains(f)) { continue; } used.add(f); sb.append(f + " "); break; } } out.println(sb.toString().trim()); } private void createSieve() { boolean[] sieve = new boolean[N + 1]; for (int i = 2; i * i <= N; i++) { for (int j = i * i; j <= N; j += i) { sieve[j] = true; } } for (int i = 2; i < N + 1; i++) { if (!sieve[i]) { primes.add(i); } } } } static class FastScanner { public BufferedReader br; public StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
c9fb11ba3703481eec2329858198110c
train_002.jsonl
1396798800
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * * @author max19 */ public class Contest { public static void mashmohAndBimoh(){ Scanner scan = new Scanner(System.in); String condition = scan.nextLine(); String[] condNumbers = condition.split(" "); long n = Long.parseLong(condNumbers[0]); long k = Long.parseLong(condNumbers[1]); List<Long> numbers = new ArrayList<>(); long gcdAtEnd = k - n/2 + 1; if(k == 0 && n == 1){ System.out.println("1"); return; } if(gcdAtEnd <= 0 || k == 0 || n == 1){ System.out.println("-1"); return; } long counter = n - 2; numbers.add(gcdAtEnd); numbers.add(gcdAtEnd * 2); for(long i = 1; i <= counter; i++){ if(i != gcdAtEnd && i != 2*gcdAtEnd) numbers.add(i); else counter++; } StringBuilder sb = new StringBuilder(); for(long l = 0; l < numbers.size() - 1; l++) sb.append(numbers.get((int) l)).append(" "); sb.append(numbers.get(numbers.size() - 1)); System.out.println(sb.toString()); } public static int gcd(int number1, int number2) { //base case if(number2 == 0){ return number1; } return gcd(number2, number1%number2); } public static void main(String[] args){ //System.out.println(gcd(499999990, 599999988)); mashmohAndBimoh(); } }
Java
["5 2", "5 3", "7 2"]
1 second
["1 2 3 4 5", "2 4 3 7 1", "-1"]
Notegcd(x, y) is greatest common divisor of x and y.
Java 8
standard input
[ "constructive algorithms", "number theory", "greedy" ]
b85c8bfbe67a23a81bef755f9313115a
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
1,500
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
standard output
PASSED
c5f5e3b76d640646deebf894501a3200
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.lang.*; import java.util.*; public class C346 { Scanner sc = new Scanner(System.in); int n, m, x = 0, ans =0, y = 0; int [] used = new int[200005]; int [] value = new int[200005]; public void input() { n = sc.nextInt(); m = sc.nextInt(); for(int i = 0; i < n; i++) value[i] = sc.nextInt(); Arrays.sort(value, 0, n); } public void check() { for(int i = 1;; i++) { if(value[x] == i) x++; else if(value[x] != i && (ans + i) <= m) { used[y++] = i; ans = ans + i; } else break; } } public void show() { System.out.println(y); for(int i = 0; i < y; i++) System.out.print(used[i] + " "); } public static void main(String args[]) { C346 obj = new C346(); obj.input(); obj.check(); obj.show(); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
a0cdae133831d7b2bde5b8d129b0f0b3
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Scanner; import java.util.TreeSet; import org.omg.CORBA.IMP_LIMIT; public class CodeJam1 { public static void main(String[] rgs){ FasterScanner in=new FasterScanner(); PrintWriter out=new PrintWriter(System.out); int n=in.nextInt(); int m = in.nextInt(); long[] a = new long[n+2]; for(int i=0;i<n;i++){ a[i] = in.nextLong(); } a[n] = 1000000000; a[n+1] = 0; Arrays.sort(a); ArrayList<Long> ans = new ArrayList<>(); for(int i=0;i<=n;i++){ long now = a[i]+1; while(m>0 && now<a[i+1]){ if(m>=now){ ans.add(now); } m-=now; now++; } //System.out.println(m); if(m<=0){ break; } } out.println(ans.size()); for(Long l : ans){ out.print(l+" "); }out.close(); } static class Node implements Comparable<Node>{ public Node(String name, int r, int score) { super(); this.name = name; this.r = r; this.score = score; } String name; int r; int score; @Override public int compareTo(Node arg0) { // TODO Auto-generated method stub if(this.score!=arg0.score) return arg0.score - this.score; else return name.compareTo(arg0.name); } } static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
a2b625cf906a8893cad96f1fd19b9550
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long m = in.nextLong(); int count = 0; int max = (int)(2e5+1); ArrayList<Integer> op = new ArrayList<>(); boolean[] bool = new boolean[max]; for(int i = 0; i < n; i++){ int st = in.nextInt(); if (st < (int)2e5+1) bool[st] = true; } int j = 1; while(m >= j){ if(!bool[j] ){ ++count; op.add(j); m -= j; } j++; } out.println(count); for(Integer ok : op){ out.print(ok+" "); } } } 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 Integer nextInt() { return Integer.parseInt(next()); } public Long nextLong() { return Long.parseLong(next()); } public Double nextDouble() { return Double.parseDouble(next()); } public Float nextFloat() { return Float.parseFloat(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public Integer[] nextIntegerArray(int n) { Integer[] a = new Integer[n]; for(Integer i = 0; i < n; i++) a[i] = nextInt(); return a; } public Long[] nextLongArray(int n) { Long[] a = new Long[n]; for(Integer i = 0; i < n; i++) a[i] = nextLong(); return a; } public long[] nextlongArray(int n) { long[] a = new long[n]; for(Integer i = 0; i < n; i++) a[i] = nextLong(); return a; } public String[] nextStringArray(int n){ String[] s = new String[n]; for(Integer i = 0; i < n; i++) s[i] = next(); return s; } public String[] nextLineStringArray(int n){ String[] s = new String[n]; for(Integer i = 0; i < n; i++) s[i] = next(); return s; } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
725fe4e5e56ee9b738eb8f6b76f5aa4d
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.StringTokenizer; public class R346Div2C { public static void main(String[] args) { FastScanner in=new FastScanner(); int n=in.nextInt(); int m=in.nextInt(); HashSet<Integer> a=new HashSet<Integer>(); for(int i=0;i<n;i++) a.add(in.nextInt()); ArrayList<Integer> b=new ArrayList<Integer>(); for(int i=1;m>=i;i++){ if(!a.contains(i)){ m-=i; b.add(i); } } PrintWriter out=new PrintWriter(System.out); out.println(b.size()); for(int i=0;i<b.size();i++) out.print(b.get(i)+" "); out.flush(); out.close(); } static class FastScanner{ BufferedReader br; StringTokenizer st; public FastScanner(){br=new BufferedReader(new InputStreamReader(System.in));} String nextToken(){ while(st==null||!st.hasMoreElements()) try{st=new StringTokenizer(br.readLine());}catch(Exception e){} return st.nextToken(); } int nextInt(){return Integer.parseInt(nextToken());} long nextLong(){return Long.parseLong(nextToken());} double nextDouble(){return Double.parseDouble(nextToken());} } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
6d4fa6946987341549825be1ed1452fb
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class MainC { MyScanner sc = new MyScanner(); Scanner sc2 = new Scanner(System.in); long start = System.currentTimeMillis(); long fin = System.currentTimeMillis(); final int MOD = 1000000007; int[] dx = { 1, 0, 0, -1 }; int[] dy = { 0, 1, -1, 0 }; void run() { int n = sc.nextInt(); int m = sc.nextInt(); Set<Integer> set = new HashSet<>(); for (int i = 0; i < n; i++) set.add(sc.nextInt()); StringBuilder sb = new StringBuilder(); long sum = 0; int cnt = 0; for (int i = 1; sum < m; i++) { if (sum + i > m) break; if (!set.contains(i)) { cnt++; sb.append(i + " "); sum += i; } } System.out.println(cnt); System.out.println(sb); } public static void main(String[] args) { new MainC().run(); } void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void debug2(char[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j]); } System.out.println(); } } boolean inner(int h, int w, int limH, int limW) { return 0 <= h && h < limH && 0 <= w && w < limW; } void swap(int[] x, int a, int b) { int tmp = x[a]; x[a] = x[b]; x[b] = tmp; } // find minimum i (k <= a[i]) int lower_bound(int a[], int k) { int l = -1; int r = a.length; while (r - l > 1) { int mid = (l + r) / 2; if (k <= a[mid]) r = mid; else l = mid; } // r = l + 1 return r; } // find minimum i (k < a[i]) int upper_bound(int a[], int k) { int l = -1; int r = a.length; while (r - l > 1) { int mid = (l + r) / 2; if (k < a[mid]) r = mid; else l = mid; } // r = l + 1 return r; } long gcd(long a, long b) { return a % b == 0 ? b : gcd(b, a % b); } long lcm(long a, long b) { return a * b / gcd(a, b); } boolean palindrome(String s) { for (int i = 0; i < s.length() / 2; i++) { if (s.charAt(i) != s.charAt(s.length() - 1 - i)) { return false; } } return true; } class MyScanner { int nextInt() { try { int c = System.in.read(); while (c != '-' && (c < '0' || '9' < c)) c = System.in.read(); if (c == '-') return -nextInt(); int res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String next() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (Character.isWhitespace(c)) c = System.in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = System.in.read())); return res.toString(); } catch (Exception e) { return null; } } int[] nextIntArray(int n) { int[] in = new int[n]; for (int i = 0; i < n; i++) { in[i] = nextInt(); } return in; } int[][] nextInt2dArray(int n, int m) { int[][] in = new int[n][m]; for (int i = 0; i < n; i++) { in[i] = nextIntArray(m); } return in; } double[] nextDoubleArray(int n) { double[] in = new double[n]; for (int i = 0; i < n; i++) { in[i] = nextDouble(); } return in; } long[] nextLongArray(int n) { long[] in = new long[n]; for (int i = 0; i < n; i++) { in[i] = nextLong(); } return in; } char[][] nextCharField(int n, int m) { char[][] in = new char[n][m]; for (int i = 0; i < n; i++) { String s = sc.next(); for (int j = 0; j < m; j++) { in[i][j] = s.charAt(j); } } return in; } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
4ebd8aa47d2fccf502d06163e0018e2c
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); Set<Integer> a = new HashSet<>(); for (int i = 0; i < n; i++) { a.add(sc.nextInt()); } int count = 0; int cost = m; List<Integer> res = new ArrayList<>(); for (int i = 1; i <= m; i++) { if (!a.contains(i)) { cost -= i; if (cost < 0) { break; } res.add(i); count++; } } System.out.println(count); for (Integer e : res) { System.out.print(e + " "); } System.out.println(); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
41b0e3ab278df7a416221d3d3def3601
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.*; import java.io.*; public class CF659C{ private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; private static void soln(){ int n=nextInt(),m=nextInt(); int[] arr = nextIntArray(n); int ia =0 ; int i =1 ; Arrays.sort(arr); ArrayList<Integer> ans = new ArrayList<Integer>(); while(m>=0){ if(ia<n){ if(arr[ia] != i){ m=m-i; if(m>=0){ ans.add(i); } else{ break; } i++; } else{ i++; ia++; } } else{ m=m-i; if(m>=0){ ans.add(i); } else{ break; } i++; } } pw.println(ans.size()); for (int j=0; j<ans.size(); j++) { pw.print(ans.get(j) + " "); } pw.println(); } public static void main(String[] args){ InputReader(System.in); pw = new PrintWriter(System.out); soln(); pw.close(); } // To Get Input // Some Buffer Methods public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } private static int 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; } private static 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; } private static String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } private static int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } private static long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private static void pArray(int[] arr){ for (int i=0; i<arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); return; } private static void pArray(long[] arr){ for (int i=0; i<arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); return; } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
72f3db098db637f13f6e7bb6cfc0097f
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public class C { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out; public static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static float nextFloat() throws IOException { return Float.parseFloat(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { long res = 0; int n = nextInt(), m = nextInt(); int[] t = new int[n + 1]; t[0] = 0; for (int i = 0; i < n; i++) { t[i + 1] = nextInt(); } int max = 1000000000; Arrays.sort(t); int i = 1; int j = 1; List<Integer> ll = new ArrayList<>(); while (m >= i && i <= max) { if (j < t.length && t[j] == i) { i++; j++; } else { m -= i; ll.add(i); res++; i++; } } System.out.println(res); for (int k = 0; k < ll.size(); k++) { System.out.print(ll.get(k) + " "); } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
2bfc83ba7803a6c993aa53294f5b392e
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.*; public final class TanyaToys { public static void main(String[] args) { Scanner br=new Scanner(System.in); int n=br.nextInt(); int m=br.nextInt(); int[] a=new int[n]; int c=0; StringBuilder str=new StringBuilder(""); for(int i=0;i<n;i++) a[i]=br.nextInt(); Arrays.sort(a); int i,j; j=0; i=1; while(m>0) { if(j<n && a[j]==i) j++; else { if(m>=i) { m-=i; c++; str.append(i+" "); } else break; } i++; } System.out.println(c+"\n"+str); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
823438f6f9c7524d5f0a9b7a7dc69ff6
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.*; public class C { public static void main(String[] args) { Scanner s = new Scanner(System.in); HashSet<Integer> set = new HashSet<Integer>(); int n = s.nextInt(); int m = s.nextInt(); for(int i=0; i<n; i++) set.add(s.nextInt()); int count = 0; Vector<Integer> list = new Vector<Integer>(); for(int i=1; i<=1000000000; i++) { if(set.add(i) && m>=i) { m -= i; count++; list.add(i); } if(m < i) break; } System.out.println(count); for(int i=0; i<list.size(); i++) System.out.print(list.get(i) + " "); System.out.println(); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
11ed940e2eb7eaa5e9a37c0036016c35
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.*; import java.io.*; public class CF_C { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static void newST() throws IOException {st = new StringTokenizer(in.readLine());} static int stInt() {return Integer.parseInt(st.nextToken());} static long stLong() {return Long.parseLong(st.nextToken());} static String stStr() {return st.nextToken();} static int[] getInts(int n) throws IOException {newST(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = stInt(); return arr;} static int readInt() throws IOException {return Integer.parseInt(in.readLine());} static long readLong() throws IOException {return Long.parseLong(in.readLine());} static void println(Object o) {System.out.println(o);} static void println() {System.out.println();} static void print(Object o) {System.out.print(o);} public static void main(String[] args) throws Exception { newST(); int n = stInt(); int m = stInt(); newST(); int[] ns = new int[n]; for (int i = 0; i < n; i++) ns[i] = stInt(); Arrays.sort(ns); int c = 0; int[] ans = new int[1000000]; int ac = 0; for (int i = 1; i < 1000000000; i++) { if (i > m) break; if (c < n && i == ns[c]) { c++; continue; } ans[ac] = i; ac++; m -= i; } println(ac); if (ac > 0) { print(ans[0]); for (int i = 1; i < ac; i++) { print(" " + ans[i]); } } println(); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
57999118f540865d848da0c0b7d47524
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { static int mod = (int) 1e9 + 7; static int MAX = (int) 1e7; public static void main(String[] args) { FasterScanner s = new FasterScanner(); PrintWriter out = new PrintWriter(System.out); int test = 1; testloop: while (test-- > 0) { int n=s.nextInt(); int m=s.nextInt(); int[] a = s.nextIntArray(n); Arrays.sort(a); int cur=1; int i=0; ArrayList<Integer> ans = new ArrayList<>(); while(m>=cur){ if(i<n && cur==a[i]){ cur++; i++; continue; } else{ m-=cur; ans.add(cur); cur++; } } out.println(ans.size()); for(i=0;i<ans.size();i++){ out.print(ans.get(i)+" "); } } out.close(); } static class Player implements Comparable<Player>{ String name; int score; Player(String n,int v){ name = n; score = v; } @Override public int compareTo(Player o) { return o.score-score; } } static class Edge { int t, rev, f; long cap; public Edge(int t, int rev, long cap) { this.t = t; this.rev = rev; this.cap = cap; } } public static List<Edge>[] createGraph(int nodes) { List<Edge>[] graph = new List[nodes]; for (int i = 0; i < nodes; i++) graph[i] = new ArrayList<>(); return graph; } public static void addEdge(List<Edge>[] graph, int s, int t, long cap) { graph[s].add(new Edge(t, graph[t].size(), cap)); graph[t].add(new Edge(s, graph[s].size() - 1, 0)); } static boolean dinicBfs(List<Edge>[] graph, int src, int dest, int[] dist) { Arrays.fill(dist, -1); dist[src] = 0; int[] Q = new int[graph.length]; int sizeQ = 0; Q[sizeQ++] = src; for (int i = 0; i < sizeQ; i++) { int u = Q[i]; for (Edge e : graph[u]) { if (dist[e.t] < 0 && e.f < e.cap) { dist[e.t] = dist[u] + 1; Q[sizeQ++] = e.t; } } } return dist[dest] >= 0; } static long dinicDfs(List<Edge>[] graph, int[] ptr, int[] dist, int dest, int u, long l) { if (u == dest) return l; for (; ptr[u] < graph[u].size(); ++ptr[u]) { Edge e = graph[u].get(ptr[u]); if (dist[e.t] == dist[u] + 1 && e.f < e.cap) { long df = dinicDfs(graph, ptr, dist, dest, e.t, Math.min(l, e.cap - e.f)); if (df > 0) { e.f += df; graph[e.t].get(e.rev).f -= df; return df; } } } return 0; } public static long maxFlow(List<Edge>[] graph, int src, int dest) { long flow = 0; int[] dist = new int[graph.length]; while (dinicBfs(graph, src, dest, dist)) { int[] ptr = new int[graph.length]; while (true) { long df = dinicDfs(graph, ptr, dist, dest, src, Integer.MAX_VALUE); if (df == 0) break; flow += df; } } return flow; } static int ans(ArrayList<Character>[] l, char a, int n) { if (n == 1) return 1; int sum = 0; for (int i = 0; i < l[a - 'a'].size(); i++) { sum += ans(l, l[a - 'a'].get(i), n - 1); } return sum; } static void dfs1(List<Integer>[] graph, boolean[] used, List<Integer> order, int u) { used[u] = true; for (int v : graph[u]) if (!used[v]) dfs1(graph, used, order, v); order.add(u); } static void dfs2(List<Integer>[] reverseGraph, int[] comp, int u, int color) { comp[u] = color; for (int v : reverseGraph[u]) if (comp[v] == -1) dfs2(reverseGraph, comp, v, color); } public static boolean[] solve2Sat(List<Integer>[] graph) { int n = graph.length; boolean[] used = new boolean[n]; List<Integer> order = new ArrayList<>(); for (int i = 0; i < n; ++i) if (!used[i]) dfs1(graph, used, order, i); List<Integer>[] reverseGraph = new List[n]; for (int i = 0; i < n; i++) reverseGraph[i] = new ArrayList<>(); for (int i = 0; i < n; i++) for (int j : graph[i]) reverseGraph[j].add(i); int[] comp = new int[n]; Arrays.fill(comp, -1); for (int i = 0, color = 0; i < n; ++i) { int u = order.get(n - i - 1); if (comp[u] == -1) dfs2(reverseGraph, comp, u, color++); } for (int i = 0; i < n; ++i) if (comp[i] == comp[i ^ 1]) return null; boolean[] res = new boolean[n / 2]; for (int i = 0; i < n; i += 2) res[i / 2] = comp[i] > comp[i ^ 1]; return res; } public static int[] createSets(int size) { int[] p = new int[size]; for (int i = 0; i < size; i++) p[i] = i; return p; } public static int root(int[] p, int x) { return x == p[x] ? x : (p[x] = root(p, p[x])); } public static void unite(int[] p, int a, int b) { a = root(p, a); b = root(p, b); if (a != b) p[a] = b; } public static boolean nextPermutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } public static boolean isPrime(long n) { if (n <= 1) return false; for (long i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } static class SegTree { long[] val; int n; SegTree(int n) { val = new long[2 * n]; this.n = n; } void upd(int p,long l) { p += n; val[p] += l; for (; (p >>= 1) != 0;) { val[p] = val[2 * p] + val[2 * p + 1]; if(val[p]>mod) val[p]-=mod; } } long query(int l, int r) { // sum on interval [l, r) // System.out.println(l+" "+r); long res = 0; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) != 0) res = res + val[l++]; if ((r & 1) != 0) res = res+ val[--r]; if(res>mod) res-=mod; } return res; } } static boolean check(int i, int j, int n) { if (i >= 0 && j >= 0 && i < n && j < n) return true; return false; } public static int[] generateDivisorTable(int n) { int[] divisor = new int[n + 1]; for (int i = 1; i <= n; i++) divisor[i] = i; for (int i = 2; i * i <= n; i++) if (divisor[i] == i) for (int j = i * i; j <= n; j += i) divisor[j] = i; return divisor; } public static int[][] matrixMul(int[][] a, int[][] b) { int n = a.length; int m = a[0].length; int k = b[0].length; int[][] res = new int[n][k]; for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) { for (int p = 0; p < m; p++) { res[i][j] = (res[i][j] + (int) ((a[i][p] * 1l * b[p][j]) % mod)) % mod; } } } return res; } public static int[][] matrixPow(int[][] a, int p) { if (p == 0) { return matrixUnit(a.length); } else if (p % 2 == 0) { return matrixPow(matrixMul(a, a), p / 2); } else { return matrixMul(a, matrixPow(a, p - 1)); } } public static int[][] matrixUnit(int n) { int[][] res = new int[n][n]; for (int i = 0; i < n; ++i) { res[i][i] = 1; } return res; } static int[] modInv(int n, int mod) { int[] ans = new int[n]; for (int i = 1; i < n; i++) ans[i] = (int) pow(i, mod - 2, mod); return ans; } static int[] primes; public static long ncr(int n, int r) { if (n < r) return 0; if (n == r) return 1; if (r == 0) return 1; if (r < 0) return 0; long ans = 1; for (int i = 0; i < primes.length; i++) { long power = count(n, primes[i]) - count(n - r, primes[i]) - count(r, primes[i]); ans *= pow(primes[i], power, mod); ans %= mod; } return ans; } public static long pow(long x, long n, int mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (int) (res * p % mod); } } return res; } public static long count(int n, int p) { long count = 0; long z = p; while (z <= n) { count += n / z; z *= p; } return count; } public static int[] generatePrimes(int n) { boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, 2, n + 1, true); for (int i = 2; i * i <= n; i++) if (prime[i]) for (int j = i * i; j <= n; j += i) prime[j] = false; int[] primes = new int[n + 1]; int cnt = 0; for (int i = 0; i < prime.length; i++) if (prime[i]) primes[cnt++] = i; return Arrays.copyOf(primes, cnt); } static class Pairxy implements Comparable<Pairxy> { int x; int y; Pairxy(int x, int y) { this.x = x; this.y = y; } public int compareTo(Pairxy o) { return Integer.compare(this.x, o.x); } } static class Pair implements Comparable<Pair> { long val; int ind; Pair(long v, int i) { val = v; ind = i; } public int compareTo(Pair o) { if (this.val != o.val) return Long.compare(this.val, o.val); return Integer.compare(this.ind, o.ind); } } public static long C(int n, int r) { long ans = 1; int x = 1; while (x <= r) { ans *= n; ans /= x; x++; n--; } return ans; } static class DisjointSetsRank { int[] p; int[] rank; public DisjointSetsRank(int size) { p = new int[size]; for (int i = 0; i < size; i++) p[i] = i; rank = new int[size]; } public int root(int x) { return x == p[x] ? x : (p[x] = root(p[x])); } public int sameSet(int x, int y) { if (root(x) == root(y)) return 1; return 0; } public void unite(int a, int b) { a = root(a); b = root(b); if (a == b) return; if (rank[a] < rank[b]) { p[a] = b; } else { p[b] = a; if (rank[a] == rank[b]) ++rank[a]; } } } static int gcd(long m, long n) { long x; long y; while (m % n != 0) { x = n; y = m % n; m = x; n = y; } return (int) n; } static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
8b2d9c53ffaa210d3e35206b1e2abcc5
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.lang.StringBuilder; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.Scanner; public class TESTer { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int k = 0; BitSet types = new BitSet(1000000001); ArrayList<Integer> bought = new ArrayList<Integer>(); for(int i=0; i<n; i++) types.flip(in.nextInt()); for(int i=1; i<=1000000000; i++) { if(types.get(i)) continue; int j=i+1; while(j<=1000000000 && types.get(j)) j++; if(j==1000000001) break; if(m-i-j>=0) { k++; bought.add(i); m-=i; i=j-1; } else { int temp = 0; for(int c=i; c<=1000000000; c++) { if(types.get(c)) continue; if(m-c>=0) temp = c; else break; } if(temp!=0) { bought.add(temp); k++; } break; } } System.out.println(k); for(int i=0; i<bought.size(); i++) System.out.print(bought.get(i) + " "); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
334b0a8e4313985862af05c25ad1b9d5
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException { FS input = new FS(System.in); int n = input.nextInt(); int m = input.nextInt(); int M = m; Set<Integer> owns = new HashSet<Integer>(); for(int i=0; i<n; i++) owns.add(input.nextInt()); List<Integer> answer = new ArrayList<Integer>(); for(int i=1; i<=m; i++){ if(!owns.contains(i) && i <= m){ m -= i; answer.add(i); } } System.out.println(answer.size()); for(int j : answer) System.out.print(j+" "); } static class FS { BufferedReader br; StringTokenizer st; public FS(InputStream in) { br = new BufferedReader(new InputStreamReader(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
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
43428b0c5608eff94c4729aa5cb479b0
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.*; import java.util.*; /** * * @author ehab */ public class JavaApplication7 { /** * @param args the command line arguments */ static Integer ar [] ; static boolean binar(int k) { int min = 0 ; int max = ar.length - 1 ; int mid ; while(min <= max) { mid = (min+max)/2 ; if(ar[mid] == k) return true; if(ar[mid] < k) min = mid + 1; else max = mid - 1 ; } return false ; } public static void main(String[] args) throws Exception { int count = 0 ; StringBuilder ans = new StringBuilder(); 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()) ; ar = new Integer [n]; st = new StringTokenizer(bf.readLine()) ; for(int i = 0 ; i < n ; i++) ar[i] = Integer.parseInt(st.nextToken()) ; Arrays.sort(ar); int c = 0 ; for(int i = 1 ; i <= 1000000000 ; i++) { if(binar(i)) continue ; if(m - i >= 0) { m -= i ; ans.append(i + " "); c++; } else break ; } System.out.println(c); System.out.println(ans); }}
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
93c15c8c9688946047626d15927c6f7d
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * @author Erasyl Abenov * * */ public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); try (PrintWriter out = new PrintWriter(outputStream)) { TaskB solver = new TaskB(); solver.solve(1, in, out); } } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException{ int n = in.nextInt(); int m = in.nextInt(); HashSet<Long> set = new HashSet<>(); ArrayList<Long> list = new ArrayList<>(); for(int i = 0; i < n; ++i) set.add(in.nextLong()); long sum = 0; long j = 0; while(true){ j++; if(sum + j > m) break; if(!set.contains(j)){ list.add(j); sum += j; } } out.println(list.size()); for(Long k : list){ out.print(k); out.print(" "); } } } class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(nextLine()); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public BigInteger nextBigInteger(){ return new BigInteger(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
0460f00781ebeb8a8de12d7103e1623a
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Codef{ public static void main(String[] args) throws IOException{ BufferedReader vod=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer s=new StringTokenizer(vod.readLine()); int n=Integer.parseInt(s.nextToken()); int m=Integer.parseInt(s.nextToken()); int[] ar=new int[n]; int[] an=new int[1000000]; s=new StringTokenizer(vod.readLine()); for (int i=0; i<n; i++){ ar[i]=Integer.parseInt(s.nextToken()); } Arrays.sort(ar); int x=1,y=0; for (int i=0; i<n; i++){ for (int j=x; j<ar[i]; j++){ if (m-j<0) break; an[y]=j; y++; m-=j; } //if (m<0) break; x=ar[i]+1; } x=ar[n-1]+1; while (m-x>=0){ m-=x; an[y]=x; y++; x++; } System.out.println(y); for (int i=0; i<y; i++){ System.out.print(an[i]+" "); } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
06c04593bae2ce267be8263a601b7a40
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.*; import java.io.*; public class R346_2_C { public static void main(String[] args) throws Exception{ Scan in = new Scan(); StringBuilder out = new StringBuilder(); int n = in.nextInt(); int m = in.nextInt(); Integer[] a = new Integer[n+1]; a[0] = 0; for (int i = 1; i <= n; i++) a[i] = in.nextInt(); Arrays.sort(a); int count = 0; ArrayList<Integer> list = new ArrayList<>(); for (int i = 1; i <= n; i++) { if (a[i] != a[i-1]+1) for (int j= a[i-1]+1; j<a[i] && j<=m; j++) { m-=j; count++; list.add(j); } if (a[i] >= m) break; } for (int j= a[n]+1; j<=m; j++) { m-=j; count++; list.add(j); } out.append(count + "\n"); for (Integer x : list) out.append(x + " "); out.deleteCharAt(out.length()-1); System.out.println(out); } } class Scan { BufferedReader br; StringTokenizer st; Scan() { // To read from the standard input 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
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
8b11ebda4ab3c3b3d9119508607cd18a
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); Set<Integer> set = new HashSet<Integer>(); int a = in.nextInt(); int b = in.nextInt(); for(int i =0; i<a; i++){ set.add(in.nextInt()); } StringBuilder sb = new StringBuilder(); int count =0; for(int i =1; i<1000000001; i++){ if(!set.contains(i)){ if(i>b){ break; } b-=i; count++; sb.append(i+" "); } } System.out.println(count); System.out.println(sb); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
7b55453f0ad06fc7542000512e406cbf
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class TanyaAndToys { public static void main(String[] args) { InputReader r = new InputReader(System.in); int n = r.nextInt(); int m = r.nextInt(); HashSet<Integer> set = new HashSet<Integer>(); for (int i = 0; i < n; i++) set.add(r.nextInt()); int[] res = new int[1000000]; int k = 0; for (int i = 1;; i++) { if (set.contains(i)) continue; if (m - i >= 0) { m -= i; res[k++] = i; } else { break; } } PrintWriter out = new PrintWriter(System.out); out.println(k); for (int i = 0; i < k; i++) out.println(res[i]); out.close(); } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public InputReader(FileReader stream) { reader = new BufferedReader(stream); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
8ddd3d09e8521c025bc453d21ec76514
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.*; public class c { static Scanner in=new Scanner(System.in); public static void main(String[] args) { int n=in.nextInt(),m=in.nextInt(),c=0; Set<Integer> set=new HashSet<Integer>(); for(int i=0;i<n;i++) { Integer temp=in.nextInt(); set.add(temp); } Integer po=0; StringBuilder sb=new StringBuilder(); while(m>0) { ++po; if(!set.contains((po))&& m>=po) { m -=po; sb.append(po+" "); ++c; } if(m<po) break; } System.out.println(c); System.out.println(sb); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
290a23cd25262ea9ca72c1828bfd0db4
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.TreeSet; public class C { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int m = nextInt(); TreeSet<Integer> tset = new TreeSet<>(); for (int i = 1; i <= n; i++) { tset.add(nextInt()); } ArrayList<Integer> ans = new ArrayList<>(); for (int i = 1; i <= 1e9; i++) { if (m < i) break; if (!tset.contains(i)) { ans.add(i); m -= i; } } pw.println(ans.size()); for (int i : ans) { pw.print(i+" "); } pw.close(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
5b700d48146b8b56f37d64928785f616
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.*; import java.io.*; public class C659 { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); int ans = 0; List<Integer> k1 = new ArrayList<Integer>(); int cur = 0; int curv = 1; while(ans < m) { if (cur < n && a[cur] == curv) { cur++; curv++; } else { ans += curv; k1.add(curv); curv++; } } if (ans > m) { k1.remove(k1.size()-1); } System.out.println(k1.size()); for (int i = 0; i < k1.size(); i++) { System.out.print(k1.get(i)+" "); } System.out.println(); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
92d43bacd92dba744ae51e889a4498f1
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.*; public class C { public static void main(String[] args) { Scanner qwe = new Scanner(System.in); int n = qwe.nextInt(); int m = qwe.nextInt(); boolean[] bought = new boolean[150000]; for(int i =0; i < n; i++){ int next = qwe.nextInt(); if(next < bought.length) bought[next] =true; } ArrayList<Integer> buying = new ArrayList<Integer>(); for (int i = 1; i < bought.length && m >= i; i++) { if(!bought[i]){ buying.add(i); m -= i; } } System.out.println(buying.size()); for (int toy : buying) { System.out.print(toy + " "); } System.out.println(); qwe.close(); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
cc7161bb81eaec50631bdbdd917cdaa3
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Test { public static void main(String args[] ) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); String[] str=line.split(" "); int n=Integer.parseInt(str[0]); long m=Long.parseLong(str[1]); line=br.readLine(); str=line.split(" "); long[] b=new long[n+2]; int k=1; for(int i=0;i<n;i++){ long tmp=Long.parseLong(str[i]); if(tmp<=m){ b[k]=tmp; k++; // System.out.println("tmp is "+tmp); } } int flag=0; if(b[k-1]!=m) { flag=1; b[k]=m; } else k--; long[] a=new long[k+1]; for(int i=0;i<k+1;i++){ a[i]=b[i]; // System.out.println("a[i] is "+a[i]); } // System.out.println(k); int cnt=0; ArrayList<Long> al=new ArrayList<Long>(); Arrays.sort(a); for(int i=0;i<k;i++){ // System.out.println("a[i+1] is "+a[i+1]+" a[i] is "+a[i]); // System.out.println(a[i+1]); if(i!=k-1&&sum(a[i+1])-sum(a[i])-a[i+1]<=m||(i==k-1&&flag==0&&sum(a[i+1])-sum(a[i])-a[i+1]<=m)||(flag==1&&i==k-1&&sum(a[i+1])-sum(a[i])<=m)){ // System.out.println("hrerbjhb"); // System.out.println(i); m-=(sum(a[i+1])-sum(a[i])-a[i+1]); if(flag==1&&i==k-1){ m+=a[i+1]; } // System.out.println("m is "+m); cnt+=a[i+1]-a[i]-1; if(flag==1&&i==k-1){ cnt++; al.add(a[i+1]); } for(long strt=a[i]+1;strt<a[i+1];strt++){ al.add(strt); // System.out.println((strt)+" added"); } } else{ long end=a[i]-1; // System.out.println("end is "+end); int j=1; while(m>=0){ m-=a[i]+j; j++; end++; } // System.out.println("end is "+end); // System.out.println(a[i]+1); // System.out.println(cnt); for(long strt=a[i]+1;strt<=end;strt++){ // System.out.println("strt is "+strt); al.add(strt); cnt++; // System.out.println("cnt is "+cnt); } break; // System.out.println("final cnt is "+cnt); } // System.out.println("here cnt is "+cnt); } System.out.println(cnt); for(int i=0;i<cnt;i++){ System.out.print(al.get(i)+" "); } // System.out.println(m); } public static long sum(long a){ return (a*(a+1))/2; } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
975106a74050767f36d184810187710a
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.*; import java.util.*; public class Main { void solve() throws Exception { int n = nextInt(); int m = nextInt(); Set<Integer> set = new TreeSet<>(); for (int i = 0; i < n; i++) set.add(nextInt()); int sum = 0; List<Integer> ans = new ArrayList<>(); for (int i = 1; i <= 1000000000; i++) { if (set.contains(i)) continue; sum += i; if (sum > m) break; ans.add(i); } out.println(ans.size()); for (int q : ans) out.print(q + " "); } public static void main(String[] args) { new Main().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { out.close(); } } BufferedReader in; PrintWriter out; StringTokenizer st; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
f6520b64f6d1ffb5a05c7b141a2649f7
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n, m; n = in.nextInt(); m = in.nextInt(); int[] has = new int[n+2]; for (int i = 0; i < n; i++) has[i] = in.nextInt(); has[n] = 0; has[n+1] = 1000000001; Arrays.sort(has); boolean stop = false; int count = 0; List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < n + 1; i++) if (!stop) { for (int j = has[i]+1; j <= has[i+1]-1; j++) if (m >= j) { count++; m -= j; list.add(j); } else { stop = true; break; } } System.out.println(count); for (Integer i: list) System.out.print(i + " "); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
9ec4dc6b631de03d15b47e6c735e5a83
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.Scanner; import java.util.Arrays; import java.util.List; import java.util.ArrayList; public class Main { public static void main(String[] args){ Scanner scan = new Scanner(System.in); int N = scan.nextInt(), M = scan.nextInt(); int[] A = new int[N]; for(int i = 0; i < N; i++){ A[i] = scan.nextInt(); } List< Integer > ans = new ArrayList< Integer >(); Arrays.sort(A); int s = 1; while(M > 0 && s <= M){ if(Arrays.binarySearch(A, s) < 0){ ans.add(s); M -= s; } ++s; } System.out.println(ans.size()); for(int i = 0; i < ans.size(); i++){ System.out.print(ans.get(i) + ((i == ans.size() - 1) ? "\n" : " ")); } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
6d5b69b326001374afa47ee3e5b3db40
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.*; import java.util.*; public class c659 { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); String[] asdf = f.readLine().split(" "); int n = Integer.parseInt(asdf[0]); int m = Integer.parseInt(asdf[1]); asdf = f.readLine().split(" "); int[] already = new int[n]; for (int i=0;i<n;i++) { already[i] = Integer.parseInt(asdf[i]); } Arrays.sort(already); int currIndex = 0; ArrayList<Integer> ans = new ArrayList<Integer>(); for (int i=1;i<Integer.MAX_VALUE;i++) { if (currIndex < already.length && already[currIndex] == i) { currIndex++; } else { m -= i; if (m >= 0) { ans.add(i); } else { break; } } } System.out.println(ans.size()); for (int i : ans) { System.out.print(i+" "); } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
34895774965260821da37e3cf31e5ffe
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
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.Arrays; public class Main { public static int arre[]; public static void main(String[] args) throws IOException{ BufferedReader cin=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String aux[]=cin.readLine().split(" "); int m=Integer.parseInt(aux[0]),ind=1; long a=Long.parseLong(aux[1]); arre=new int[m]; ArrayList<Integer>lis=new ArrayList(); aux=cin.readLine().split(" "); for(int i=0;i<m;i++) arre[i]=Integer.parseInt(aux[i]); Arrays.sort(arre); while(a>=ind) { if(!buscar(ind,m-1)) { lis.add(ind); a-=ind; } ind++; } out.write(lis.size()+"\n"); for (Integer li : lis) out.write(li+" "); out.println(); out.flush(); } private static boolean buscar(int ele,int fin) { int med=0,ini=0; while(ini<=fin) { med=(ini+fin)/2; if(arre[med]==ele) return true; if(ele<arre[med]) fin=med-1; else ini=med+1; } return false; } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
d37f5189314a82140b49fdf22c37cd13
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
/* Andy Rock * March 30, 2016 * * Codeforces Round #346 (Div. 2): C */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); st = new StringTokenizer(in.readLine()); boolean[] taken = new boolean[1000000]; for(int i=0;i<n;i++) { int a = Integer.parseInt(st.nextToken()); if(a < taken.length) taken[a] = true; } List<Integer> ans = new ArrayList<Integer>(); for(int i=1;m>0;i++) if(!taken[i]) { m -= i; if(m >= 0) ans.add(i); } System.out.println(ans.size()); for(int a : ans) System.out.print(a+" "); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
f0f0c67799ee0270fe2551a1374ef849
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int total=s.nextInt(); HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); for(int i=0;i<n;i++) { hm.put(s.nextInt(),1); } int ans=0; int j=1; ArrayList answer=new ArrayList<Integer>(); while(total>=j) { if(hm.get(j)==null) { ans++; answer.add(j); total-=j; } j++; } System.out.println(ans); for(int i=0;i<answer.size();i++) { System.out.print(answer.get(i)+" "); } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
c30296e556786af869d35bd18693de9b
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.List; public class P659C { InputStream is; PrintWriter out; // String INPUT = "3 7 1 3 4"; String INPUT = "4 14 4 6 12 8"; void solve() { int n = ni(); int m = ni(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } Arrays.sort(a); int index = 1; List<Integer> res = new ArrayList<Integer>(); while (m >= index) { int idx = Arrays.binarySearch(a, index); if (idx < 0) { res.add(index); m -= index; } index++; } System.out.println(res.size()); for (int num : res) { System.out.print(num + " " ); } } public static void main(String[] args) throws Exception { new P659C().run(); } 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"); } 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 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
e56e432f27bab0f55745bfd650c03acf
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.PrintStream; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { private static Scanner in = new Scanner(System.in); private static PrintStream out = System.out; public static void main(String[] args) { int n = in.nextInt(); int m = in.nextInt(); Set<Integer> seen = new HashSet<Integer>(); for (int i = 0; i < n; ++i) seen.add(in.nextInt()); ArrayList<Integer> ans = new ArrayList<Integer>(); for (int i = 1; m >= i; ++i) { if (!seen.contains(i)) { m -= i; ans.add(i); } } out.println(ans.size()); for (int curr : ans) out.print(curr + " "); out.println(); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
38ec8ef93ccefdf3480335059721c91c
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Palindrome { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] arr=new int[n]; int m=sc.nextInt(); Set<Integer> set=new HashSet<>(); Set<Integer> ans=new HashSet<>(); for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); set.add(arr[i]); } //System.out.println(set); for(int i=0;i<200000;i++) { if(set.contains(i+1)==false&&m>=i+1) { m=m-i-1; ans.add(i+1); } } System.out.println(ans.size()); for(int i:ans) { System.out.print(i+" "); } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
b0573430c36423e618b95ae2889d221b
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.util.*; public class Main { public static int arrLimit =31250000; public static void main(String[] args) { int[] status = new int[arrLimit]; ArrayList<Integer> ans = new ArrayList<Integer>(); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); for(int i =0 ;i<n;i++) { int x = scanner.nextInt() -1; //System.out.println("X " +x); int x1 = x/32; int x2 = x%32; status[x1] = status[x1] | (1<<x2); } boolean flag = false; for(int i =0;i<status.length ; i++) { for(int j =0;j<32;j++) { int d = status[i] & (1<<j); if( d == 0) { if(m-i*32-(j+1) >=0) { ans.add(i*32 + j+1); m = m-i*32-(j+1); } else { flag = true; break; } } } if(flag) break; } /* for(int i =1; i<status.length;i++) { if(status[i] == false ){ if(m-i >= 0 ) { ans.add(i); m = m-i; } else { break; } } } */ System.out.println(ans.size()); for(int i =0;i<ans.size() ; i++) { System.out.print(ans.get(i)); if(i != ans.size() - 1) { System.out.print(" "); } } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
fd336a69ac92f3d53c62752859dfb1d6
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.awt.Point; import java.awt.geom.Line2D; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.security.GuardedObject; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Scanner; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.io.InputStream; import java.math.BigInteger; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in; PrintWriter out; in=new FastScanner(System.in); out=new PrintWriter(System.out); //in=new FastScanner(new FileInputStream(new File("C://Users//KANDARP//Desktop//coding_contest_creation (1).txt"))); TaskC solver = new TaskC(); long var=System.currentTimeMillis(); solver.solve(1, in, out); /*if(System.getProperty("ONLINE_JUDGE")==null){ out.println("["+(double)(System.currentTimeMillis()-var)/1000+"]"); }*/ out.close(); } } class Pair { long x,y,index; long r1,r2; Pair(long x,long y,int index){ this.x=x; this.y=y; this.index=index; } public String toString(){ return this.x+" "+this.y+" "; } } class tupple{ long x,y,z; ArrayList<String> list=new ArrayList<>(); tupple(long x,long y,long z){ this.x=x; this.y=y; this.z=z; } tupple(tupple cl){ this.x=cl.x; this.y=cl.y; this.z=cl.z; this.list=cl.list; } } class Edge implements Comparable<Edge>{ int u; int v; int time; long cost; long wcost; public Edge(int u,int v,long cost,long wcost){ this.u=u; this.v=v; this.cost=cost; this.wcost=wcost; time=Integer.MAX_VALUE; } public int other(int x){ if(u==x)return v; return u; } @Override public int compareTo(Edge o) { // TODO Auto-generated method stub return Long.compare(cost, o.cost); } } class Ss{ Integer a[]=new Integer[3]; Ss(Integer a[]){ this.a=a; } public int hashCode(){ return a[0].hashCode()+a[1].hashCode()+a[2].hashCode(); } public boolean equals(Object o){ Ss x=(Ss)o; for(int i=0;i<3;i++){ if(x.a[i]!=this.a[i]){ return false; } } return true; } } class queary{ int type; int l; int r; int index; queary(int type,int l,int r){ this.type=type; this.l=l; this.r=r; } } class boat implements Comparable<boat>{ int capacity; int index; boat(int capacity,int index) { this.capacity=capacity; this.index=index; } @Override public int compareTo(boat o) { // TODO Auto-generated method stub return this.capacity-o.capacity; } } class angle{ double x,y,angle; int index; angle(int x,int y,double angle){ this.x=x; this.y=y; this.angle=angle; } } class TaskC { static long mod=1000000007; // SegTree tree; // int min[]; /* static int prime_len=1000010; static int prime[]=new int[prime_len]; static long n_prime[]=new long[prime_len]; static ArrayList<Integer> primes=new ArrayList<>(); static{ for(int i=2;i<=Math.sqrt(prime.length);i++){ for(int j=i*i;j<prime.length;j+=i){ prime[j]=i; } } for(int i=2;i<prime.length;i++){ n_prime[i]=n_prime[i-1]; if(prime[i]==0){ n_prime[i]++; } } // System.out.println("end"); // prime[0]=true; // prime[1]=1; } /* * long pp[]=new long[10000001]; pp[0]=0; pp[1]=1; for(int i=2;i<pp.length;i++){ if(prime[i]!=0){ int gcd=(int)greatestCommonDivisor(i/prime[i], prime[i]); pp[i]=(pp[i/prime[i]]*pp[prime[i]]*gcd)/pp[(int)gcd]; } else pp[i]=i-1; } } * */ class Rmq { int[] logTable; int[][] rmq; int[] a; public Rmq(int[] a) { this.a = a; int n = a.length; logTable = new int[n + 1]; for (int i = 2; i <= n; i++) logTable[i] = logTable[i >> 1] + 1; rmq = new int[logTable[n] + 1][n]; for (int i = 0; i < n; ++i) rmq[0][i] = i; for (int k = 1; (1 << k) < n; ++k) { for (int i = 0; i + (1 << k) <= n; i++) { int x = rmq[k - 1][i]; int y = rmq[k - 1][i + (1 << k - 1)]; rmq[k][i] = a[x] <= a[y] ? x : y; } } } public int minPos(int i, int j) { int k = logTable[j - i]; int x = rmq[k][i]; int y = rmq[k][j - (1 << k) + 1]; return a[x] <= a[y] ? a[x] : a[y]; } } /*int m,d; int dp[][][]; String a,b;*/ public int[] preprocess(int pat[],int M){ int lps[]=new int[M]; int len = 0; // length of the previous longest prefix suffix int i; lps[0] = 0; // lps[0] is always 0 i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { if (len != 0) { // This is tricky. Consider the example // AAACAAAA and i = 7. len = lps[len-1]; // Also, note that we do not increment i here } else // if (len == 0) { lps[i] = 0; i++; } } } return lps; } public int[] search(int txt[],int pat[],int N,int lps[],int M){ int i = 0; // index for txt[] int j=0; int index=0; int ans[]=new int[N]; Arrays.fill(ans, -1); while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { //printf("Found pattern at index %d \n", i-j); ans[index++]=i-j; j = lps[j-1]; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j-1]; else i = i+1; } } return ans; } class TrieNode{ int value; TrieNode children[]; public TrieNode(int value,TrieNode children[] ){ this.value=value; this.children=children; } } class Trie{ TrieNode root; int count; public Trie(TrieNode root,int count){ this.root=root; this.count=count; } } public void insert(Trie t,char key[]){ t.count++; int length=key.length; int level=0; TrieNode current=t.root; if(current==null){ t.root=new TrieNode(0, new TrieNode[26]); current=t.root; } for(level=0;level<length;level++){ int index=key[level]-'a'; if(current.children[index]==null){ current.children[index]=new TrieNode(0,new TrieNode[26]); } current=current.children[index]; } current.value=t.count; } public int search(Trie t,char key[]){ TrieNode current=t.root; if(current==null){ return 0; } int length=key.length; int level=0; for(level=0;level<length;level++){ int index=key[level]-'a'; if(current.children[index]==null){ return 0; } current=current.children[index]; } return current.value; } class team implements Comparable<team> { String name; int score; team(String name,int score){ this.name=name; this.score=score; } @Override public int compareTo(team o) { // TODO Auto-generated method stub return (this.score-o.score)*-1; } } public void solve(int testNumber, FastScanner in, PrintWriter out) throws IOException { int n=in.nextInt(); long m=in.nextInt(); long a[]=new long[n]; HashSet<Long> set=new HashSet<Long>(); for(int i=0;i<n;i++){ set.add(in.nextLong()); } long index=1; ArrayList<Long> ans=new ArrayList<Long>(); while(m>0){ if(set.contains(index)){ index++; continue; } if(m-index<0){ break; } else{ ans.add(index); m-=index; index++; } } out.println(ans.size()); for(long x:ans){ out.print(x+" ");; } out.println(); } public char[][] rotate90(char[][] mat){ int n=mat.length; int m=mat[0].length; char temp[][]=new char[m][n]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ temp[j][n-1-i]=mat[i][j]; } } return temp; } public char[][] flip(char mat[][]){ int n=mat.length; int m=mat[0].length; char tmp[][]=new char[n][m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ tmp[i][m-1-j]=mat[i][j]; } } return tmp; } public char[][] zoom(char[][] mat){ int n=mat.length; int m=mat[0].length; char temp[][]=new char[2*n][2*m]; int ii=0,jj=0; for(int i=0;i<n;i++){ jj=0; for(int j=0;j<m;j++){ // System.out.println(ii+" "+jj +" "+i+" "+j); temp[ii][jj]=mat[i][j]; temp[ii+1][jj]=mat[i][j]; temp[ii][jj+1]=mat[i][j]; temp[ii+1][jj+1]=mat[i][j]; jj+=2; } ii+=2; } return temp; } /*public long fun(int p,int i,int r,int q,int avy){ long ans=0; if(p==0){ if(i>=b.length() ){ if(r!=0 || avy==0) return 0; else return 1; } if(q==0){ if(avy==0) ans= dp[b.length()-i][(m-((int)(r*pow(10,b.length()-i,m))%m))%m][1]; else ans= (dp[b.length()-i][(m-((int)(r*pow(10,b.length()-i,m))%m))%m][0]+ dp[b.length()-i][(m-((int)(r*pow(10,b.length()-i,m))%m))%m][1])%m; System.out.println((b.length()-i)+" "+(m-((int)(r*pow(10,b.length()-i,m))%m))+" "+ans); return ans; } else{ for(int j=0;j<b.charAt(i)-'0';j++){ if(i%2==0 && j==d) continue; if(j==d) ans+=fun(p,i+1,(r*10+j)%m,0,1); else ans+=fun(p,i+1,(r*10+j)%m,0,avy); if(ans>=mod){ ans-=mod; } } if(b.charAt(i)-'0'==d) ans+=fun(p,i+1,(r*10+b.charAt(i)-'0')%m,1,1); else ans+=fun(p,i+1,(r*10+b.charAt(i)-'0')%m,1,avy); if(ans>=mod){ ans-=mod; } } } else{ if(i>=a.length() ){ if(r!=0 || avy==0) return 0; else return 1; } if(q==0){ // System.out.println(dp.length+" "+(b.length()-i)+" "+(m-((int)(r*pow(10,b.length()-i,m))%m))); if(avy==0) return dp[a.length()-i][(m-((int)(r*pow(10,a.length()-i,m))%m))%m][1]; else return (dp[a.length()-i][(m-((int)(r*pow(10,a.length()-i,m))%m))%m][0]+ dp[a.length()-i][(m-((int)(r*pow(10,a.length()-i,m))%m))%m][1])%m; } else{ for(int j=0;j<a.charAt(i)-'0';j++){ if(i%2==0 && j==d) continue; if(j==d) ans+=fun(p,i+1,(r*10+j)%m,0,1); else ans+=fun(p,i+1,(r*10+j)%m,0,avy); if(ans>=mod){ ans-=mod; } } if(a.charAt(i)-'0'==d) ans+=fun(p,i+1,(r*10+a.charAt(i)-'0')%m,1,1); else ans+=fun(p,i+1,(r*10+a.charAt(i)-'0')%m,1,avy); if(ans>=mod){ ans-=mod; } } } return ans; } */ public static long[][] matrixexpo(long m[][],String n,long mod){ if(n.equals("1")){ return m.clone(); } if(n.equals("10")){ return mulmatrix(m, m , mod); } else{ long temp [][]=matrixexpo(m,n.substring(0,n.length()-1),mod); temp=mulmatrix(temp, temp, mod); if(n.charAt(n.length()-1)=='0')return temp; else return mulmatrix(temp, m,mod); } } public static long[][] mulmatrix(long m1[][],long m2[][],long mod){ long ans[][]=new long[m1.length][m2[0].length]; for(int i=0;i<m1.length;i++){ for(int j=0;j<m2[0].length;j++){ for(int k=0;k<m1.length;k++){ ans[i][j]+=(m1[i][k]*m2[k][j]); ans[i][j]%=mod; } } } return ans; } long pow(long x,long y,long mod){ if(y<=0){ return 1; } if(y==1){ return x%mod; } long temp=pow(x,y/2,mod); if(y%2==0){ return (temp*temp)%mod; } else{ return (((temp*temp)%mod)*x)%mod; } } static long greatestCommonDivisor (long m, long n){ long x; long y; while(m%n != 0){ x = n; y = m%n; m = x; n = y; } return n; } } /* * long res[]=new long[m]; int cl=1; int cr=0; for(int i=0;i<m;i++){ int l=(int)q[i].x; int r=(int)q[i].y; while(cl>l){ cl--; ans+=add(cl); } while(cl<l){ ans-=remove(cl); cl++; } while(cr>r){ ans-=remove(cr); cr--; } while(cr<r){ cr++; ans+=add(cr); } res[(int)q[i].index]=ans; } for(int i=0;i<m;i++) out.println(res[i]); */ class SegmentTree2D { public long max(int[][] t, int x1, int y1, int x2, int y2) { int n = t.length >> 1; x1 += n; x2 += n; int m = t[0].length >> 1; y1 += m; y2 += m; long res = 0; for (int lx = x1, rx = x2; lx <= rx; lx = (lx + 1) >> 1, rx = (rx - 1) >> 1) for (int ly = y1, ry = y2; ly <= ry; ly = (ly + 1) >> 1, ry = (ry - 1) >> 1) { if ((lx & 1) != 0 && (ly & 1) != 0) res = (res+ t[lx][ly]); if ((lx & 1) != 0 && (ry & 1) == 0) res = (res+ t[lx][ry]); if ((rx & 1) == 0 && (ly & 1) != 0) res =(res+t[rx][ly]); if ((rx & 1) == 0 && (ry & 1) == 0) res = (res+ t[rx][ry]); } return res; } public void add(int[][] t, int x, int y, int value) { x += t.length >> 1; y += t[0].length >> 1; t[x][y] += value; for (int tx = x; tx > 0; tx >>= 1) for (int ty = y; ty > 0; ty >>= 1) { if (tx > 1) t[tx >> 1][ty] = (t[tx][ty]+t[tx ^ 1][ty]); if (ty > 1) t[tx][ty >> 1] = (t[tx][ty]+ t[tx][ty ^ 1]); } // for (int ty = y; ty > 1; ty >>= 1) // t[x][ty >> 1] = Math.max(t[x][ty], t[x][ty ^ 1]); // for (int tx = x; tx > 1; tx >>= 1) // for (int ty = y; ty > 0; ty >>= 1) // t[tx >> 1][ty] = Math.max(t[tx][ty], t[tx ^ 1][ty]); // for (int lx=x; lx> 0; lx >>= 1) { // if (lx > 1) // t[lx >> 1][y] = Math.max(t[lx][y], t[lx ^ 1][y]); // for (int ly = y; ly > 1; ly >>= 1) // t[lx][ly >> 1] = Math.max(t[lx][ly], t[lx][ly ^ 1]); // } } } class SegmentTree { // Modify the following 5 methods to implement your custom operations on the tree. // This example implements Add/Max operations. Operations like Add/Sum, Set/Max can also be implemented. long modifyOperation(long x, long y) { return y; } // query (or combine) operation long queryOperation(long leftValue, long rightValue) { return (leftValue| rightValue); } long deltaEffectOnSegment(long delta, long segmentLength) { // Here you must write a fast equivalent of following slow code: // int result = delta; // for (int i = 1; i < segmentLength; i++) result = queryOperation(result, delta); // return result; return delta; } int getNeutralDelta() { return 0; } int getInitValue() { return 0; } // generic code int n; long[] value; long[] delta; // delta[i] affects value[i], delta[2*i+1] and delta[2*i+2] long joinValueWithDelta(long value, long delta) { if (delta == getNeutralDelta()) return value; return modifyOperation(value, delta); } long joinDeltas(long delta1, long delta2) { if (delta1 == getNeutralDelta()) return delta2; if (delta2 == getNeutralDelta()) return delta1; return modifyOperation(delta1, delta2); } void pushDelta(int root, int left, int right) { value[root] = joinValueWithDelta(value[root], deltaEffectOnSegment(delta[root], right - left + 1)); delta[2 * root + 1] = joinDeltas(delta[2 * root + 1], delta[root]); delta[2 * root + 2] = joinDeltas(delta[2 * root + 2], delta[root]); delta[root] = getNeutralDelta(); } public SegmentTree(int n) { this.n = n; value = new long[4 * n]; delta = new long[4 * n]; init(0, 0, n - 1); } void init(int root, int left, int right) { if (left == right) { value[root] = getInitValue(); delta[root] = getNeutralDelta(); } else { int mid = (left + right) >> 1; init(2 * root + 1, left, mid); init(2 * root + 2, mid + 1, right); value[root] = queryOperation(value[2 * root + 1], value[2 * root + 2]); delta[root] = getNeutralDelta(); } } public long query(int from, int to) { return query(from, to, 0, 0, n - 1); } long query(int from, int to, int root, int left, int right) { if (from == left && to == right) return joinValueWithDelta(value[root], deltaEffectOnSegment(delta[root], right - left + 1)); pushDelta(root, left, right); int mid = (left + right) >> 1; if (from <= mid && to > mid) return queryOperation( query(from, Math.min(to, mid), root * 2 + 1, left, mid), query(Math.max(from, mid + 1), to, root * 2 + 2, mid + 1, right)); else if (from <= mid) return query(from, Math.min(to, mid), root * 2 + 1, left, mid); else if (to > mid) return query(Math.max(from, mid + 1), to, root * 2 + 2, mid + 1, right); else throw new RuntimeException("Incorrect query from " + from + " to " + to); } public void modify(int from, int to, long delta) { modify(from, to, delta, 0, 0, n - 1); } void modify(int from, int to, long delta, int root, int left, int right) { if (from == left && to == right) { this.delta[root] = joinDeltas(this.delta[root], delta); return; } pushDelta(root, left, right); int mid = (left + right) >> 1; if (from <= mid) modify(from, Math.min(to, mid), delta, 2 * root + 1, left, mid); if (to > mid) modify(Math.max(from, mid + 1), to, delta, 2 * root + 2, mid + 1, right); value[root] = queryOperation( joinValueWithDelta(value[2 * root + 1], deltaEffectOnSegment(this.delta[2 * root + 1], mid - left + 1)), joinValueWithDelta(value[2 * root + 2], deltaEffectOnSegment(this.delta[2 * root + 2], right - mid))); } } class LcaSparseTable { int len; int[][] up; int[][] max; int[] tin; int[] tout; int time; int []lvel; void dfs(List<Integer>[] tree, int u, int p) { tin[u] = time++; lvel[u]=lvel[p]+1; up[0][u] = p; if(u!=p) //max[0][u]=weight(u,p); for (int i = 1; i < len; i++) { up[i][u] = up[i - 1][up[i - 1][u]]; max[i][u]=Math.max(max[i-1][u],max[i-1][up[i-1][u]]); } for (int v : tree[u]) if (v != p) dfs(tree, v, u); tout[u] = time++; } public LcaSparseTable(List<Integer>[] tree, int root) { int n = tree.length; len = 1; while ((1 << len) <= n) ++len; up = new int[len][n]; max=new int[len][n]; tin = new int[n]; tout = new int[n]; lvel=new int[n]; lvel[root]=0; dfs(tree, root, root); } boolean isParent(int parent, int child) { return tin[parent] <= tin[child] && tout[child] <= tout[parent]; } public int lca(int a, int b) { if (isParent(a, b)) return a; if (isParent(b, a)) return b; for (int i = len - 1; i >= 0; i--) if (!isParent(up[i][a], b)) a = up[i][a]; return up[0][a]; } public long max(int a,int b){ int lca=lca(a,b); // System.out.println("LCA "+lca); long ans=0; int h=lvel[a]-lvel[lca]; // System.out.println("Height "+h); int index=0; while(h!=0){ if(h%2==1){ ans=Math.max(ans,max[index][a]); a=up[index][a]; } h/=2; index++; } h=lvel[b]-lvel[lca]; // System.out.println("Height "+h); index=0; while(h!=0){ if(h%2==1){ ans=Math.max(ans,max[index][b]); b=up[index][b]; } h/=2; index++; } return ans; } static void dfs(List<Integer>[] graph, boolean[] used, List<Integer> res, int u,int parent,List<Integer> collection) { used[u] = true; Integer uu=new Integer(u); collection.add(uu); for (int v : graph[u]){ if (!used[v]){ dfs(graph, used, res, v,u,collection); } else if(collection.contains(v)){ System.out.println("Impossible"); System.exit(0); } } collection.remove(uu); res.add(u); } public static List<Integer> topologicalSort(List<Integer>[] graph) { int n = graph.length; boolean[] used = new boolean[n]; List<Integer> res = new ArrayList<>(); for (int i = 0; i < n; i++) if (!used[i]) dfs(graph, used, res, i,-1,new ArrayList<Integer>()); Collections.reverse(res); return res; } static class pairs{ String company,color; String type; boolean visit=false; pairs(String company,String color,String type){ this.company=company; this.color=color; this.type=type; } } static void dfs1(List<Integer>[] graph, boolean[] used, List<Integer> res, int u) { used[u] = true; for (int v : graph[u]) if (!used[v]) dfs1(graph, used, res, v); res.add(u); } public static List<Integer> topologicalSort1(List<Integer>[] graph) { int n = graph.length; boolean[] used = new boolean[n]; List<Integer> res = new ArrayList<>(); for (int i = n-1; i >0; i--) if (!used[i]) dfs1(graph, used, res, i); Collections.reverse(res); return res; } int phi(int n) { int res = n; for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { while (n % i == 0) { n /= i; } res -= res / i; } } if (n != 1) { res -= res / n; } return res; } /* long DP(int id,int mask){ //System.out.println("hi"+dp[id][mask]+" "+id+" "+Integer.toBinaryString(mask)); if(id==0 && mask==0){ dp[0][mask]=1; return 1; } else if(id==0){ dp[0][mask]=0; return 0; } if(dp[id][mask]!=-1){ return dp[id][mask]; } long ans=0; for(int i=0;i<n;i++){ if((mask & (1<<i))!=0 && c[i][id]>=1){ ans+=DP(id-1,mask ^ (1 << i)); ans%=mod; } } ans+=DP(id-1,mask); ans%=mod; dp[id][mask]=ans; return ans; }*/ public static long[][] mulmatrix(long m1[][],long m2[][],long mod){ long ans[][]=new long[m1.length][m2[0].length]; for(int i=0;i<m1.length;i++){ for(int j=0;j<m2[0].length;j++){ for(int k=0;k<m1.length;k++){ ans[i][j]+=(m1[i][k]*m2[k][j]); ans[i][j]%=mod; } } } return ans; } public static long[][] matrixexpo(long m[][],String n,long mod){ if(n.equals("1")){ return m.clone(); } if(n.equals("10")){ return mulmatrix(m, m , mod); } else{ long temp [][]=matrixexpo(m,n.substring(0,n.length()-1),mod); temp=mulmatrix(temp, temp, mod); if(n.charAt(n.length()-1)=='0')return temp; else return mulmatrix(temp, m,mod); } } public static boolean isCompatible(long x[],long y[]){ for(int i=0;i<x.length-1;i++){ if(x[i]==y[i] && x[i+1]==y[i+1] && x[i]==x[i+1] && y[i]==y[i+1]){ return false; } } return true; } long pow(long x,long y,long mod){ if(y<=0){ return 1; } if(y==1){ return x%mod; } long temp=pow(x,y/2,mod); if(y%2==0){ return (temp*temp)%mod; } else{ return (((temp*temp)%mod)*x)%mod; } } long no_of_primes(long m,long n,long k){ long count=0,i,j; int primes []=new int[(int)(n-m+2)]; if(m==1) primes[0] = 1; for(i=2; i<=Math.sqrt(n); i++) { j = (m/i); j *= i; if(j<m) j+=i; for(; j<=n; j+=i) { if(j!=i) primes[(int)(j-m)] = 1; } } for(i=0; i<=n-m; i++) if(primes[(int)i]==0 && (i-1)%k==0) count++; return count; } } class SegTree { int n; long t[]; long mod=(long)(1000000007); SegTree(int n,long t[]){ this.n=n; this.t=t; build(); } void build() { // build the tree for (int i = n - 1; i > 0; --i) t[i]=(t[i<<1]|t[i<<1|1]); } void modify(int p, long value) { // set value at position p for (t[p += n]+=value; p > 1; p >>= 1) t[p>>1] = (t[p]|t[p^1]); } long query(int l, int r) { // sum on interval [l, r) long res=0; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l&1)!=0) res=Math.max(res,t[l++]); if ((r&1)!=0) res=Math.max(res,t[--r]); } return res; } // // // } class FastScanner { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int snumChars; private SpaceCharFilter filter; public FastScanner(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 String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class UF { private int[] parent; // parent[i] = parent of i private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31) private int count; // number of components public UF(int N) { if (N < 0) throw new IllegalArgumentException(); count = N; parent = new int[N]; rank = new byte[N]; for (int i = 0; i < N; i++) { parent[i] = i; rank[i] = 0; } } public int find(int p) { if (p < 0 || p >= parent.length) throw new IndexOutOfBoundsException(); while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } public int count() { return count; } public boolean connected(int p, int q) { return find(p) == find(q); } public boolean union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return false; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; return true; } } class MyArrayList { private int[] myStore; private int actSize = 0; public MyArrayList(){ myStore = new int[2]; } public int get(int index){ if(index < actSize) return myStore[index]; else throw new ArrayIndexOutOfBoundsException(); } public void add(int obj){ if(myStore.length-actSize <= 1) increaseListSize(); myStore[actSize++] = obj; } public int size(){ return actSize; } private void increaseListSize(){ myStore = Arrays.copyOf(myStore, myStore.length*2); } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
48c3c8783175dab451c1173e1ff206c2
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class TestAC { public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); int n = input.nextInt(); Set<Integer> set = new HashSet<>(); int k = input.nextInt(); long s = 0; int count=0; StringBuilder S=new StringBuilder(); for (int i = 0; i < n; i++) set.add(input.nextInt()); int ok = 0; while (true) { ok++; if(set.contains(ok)){ continue; } s+=ok; if (s > k) { System.out.println(count); System.out.println(S.toString()); break; } count++; S=S.append(ok+" "); } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
3318e36e75b4f2f3aee189a656b8b92a
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class TestAC { public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); int n = input.nextInt(); Set<Integer> set = new HashSet<>(); int k = input.nextInt(); long s = 0; int count=0; StringBuilder S=new StringBuilder(); for (int i = 0; i < n; i++) set.add(input.nextInt()); int ok = 0; while (true) { ok++; if(set.contains(ok)){ continue; } s+=ok; if (s > k) { System.out.println(count); System.out.println(S); break; } count++; S=S.append(ok).append(" "); } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
093e24e8848812fcd53f050ee5a96daa
train_002.jsonl
1459353900
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
256 megabytes
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; import java.util.StringTokenizer; public class TestAC { public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); int n = input.nextInt(); Set<Integer> set = new HashSet<>(); int k = input.nextInt(); long s = 0; int count=0; StringBuilder S=new StringBuilder(); for (int i = 0; i < n; i++) set.add(input.nextInt()); int ok = 0; while (true) { ok++; if(set.contains(ok)){ continue; } s+=ok; if (s > k) { System.out.println(count); System.out.println(S.toString()); break; } count++; S=S.append(ok+" "); } } }
Java
["3 7\n1 3 4", "4 14\n4 6 12 8"]
1 second
["2\n2 5", "4\n7 2 3 1"]
NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Java 7
standard input
[ "implementation", "greedy" ]
0318d4d5ea3425bf6506edeb1026f597
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.
1,200
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.
standard output
PASSED
ebb121c668de71626a4e534a3d867941
train_002.jsonl
1586529300
You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; import static java.lang.System.*; public class D { public static void main(String[]args){ InputReader sc = new InputReader(System.in); PrintWriter pw =new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int cases=sc.nextInt(); for(int z=0;z<cases;z++){ int len=sc.nextInt(); long begin=sc.nextLong(); long end=sc.nextLong(); begin-=2; end-=2; ArrayList<Integer>nodes=new ArrayList<Integer>(); if(begin==-1){ nodes.add(1); begin++; end++; } long[]cycle=new long[len-1]; long[]intecycle=new long[len-1]; for(int i=0;i<cycle.length;i++){ cycle[i]=(len-i-1)*2; } for(int i=0;i<intecycle.length;i++){ intecycle[i]+=cycle[i]; if(i!=0)intecycle[i]+=intecycle[i-1]; } int begincycle=0; while(begincycle<len&&begin>intecycle[begincycle])begincycle++; if(begincycle!=0){ begin-=intecycle[begincycle-1]; end-=intecycle[begincycle-1]; } long duration=end-begin+1; for(int a=begincycle;a<len&&nodes.size()<200005;a++){ if(a==len-2){ nodes.add(len); nodes.add(1); break; } for(int b=a+1;b<len;b++){ nodes.add(b+1); if(b!=len-1)nodes.add(a+1); else nodes.add(a+2); } } System.out.print(nodes.get((int)begin)); for(int a=(int)begin+1;a<begin+duration;a++){ System.out.print(" "+nodes.get(a)); } System.out.println(); } pw.flush(); } 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 double nextDouble() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } double res = 0; while(c<='9'&&c>='0'){ res*=10; res+=c-'0'; c=snext(); } if(c=='.'){ double decimal=0; long multiplier=1; c=snext(); do { if (c < '0' || c > '9') throw new InputMismatchException(); decimal *= 10; decimal += c - '0'; multiplier*=10; c = snext(); } while (!isSpaceChar(c)); return sgn*(res+decimal/multiplier); }else{ if(!isSpaceChar(c)){ throw new InputMismatchException(); } return sgn*res; } } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public String next(){return readString();} 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(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); if(isEndOfLine(res.charAt(res.length()-1))) return res.deleteCharAt(res.length()).toString(); return res.toString(); } public ArrayList<String> readAll(){ ArrayList<String>a=new ArrayList<String>(); try{ while(true){ a.add(nextLine()); } }catch(Exception e){ } return a; } public boolean hasNext(){ boolean hasnext=true; try{ hasnext= stream.available()!=0; }catch(IOException e){ } return hasnext||curChar<snumChars; } 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); } } }
Java
["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"]
2 seconds
["1 2 1 \n1 3 2 3 \n1"]
NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "graphs" ]
afb43928545743b497b1a9975768f8e5
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.
1,800
For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.
standard output
PASSED
7f23235937ede17c4f69ae1d72adae5d
train_002.jsonl
1586529300
You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; import java.util.logging.Logger; public class Main { public static void main(String[] args){ PrintWriter out = new PrintWriter(System.out); InputReader sc=new InputReader(System.in); int t=sc.nextInt(); for (int i = 0; i < t; i++) { long N=sc.nextInt(); long l=sc.nextLong(); long r=sc.nextLong(); long indexl=0; for (long k = 1; k <= N; k++) { if (k==N) { if (N*(N-1)+1>=l) { indexl=(int) k; } }else { if (2*k*N-k*(k+1)>=l) { indexl=(int) k; break; } } } long indexr=0; for (long k = 1; k <= N; k++) { if (k==N) { if (N*(N-1)+1>=r) { indexr=(int) k; } }else { if (2*k*N-k*(k+1)>=r) { indexr=(int) k; break; } } } ArrayList<Integer> arrayList=new ArrayList<>(); for (int j = (int) indexl; j <= (int)indexr; j++) { if (j==N) { arrayList.add(1); } for (int j2 = 1; j+j2 <= N; j2++) { arrayList.add(j); arrayList.add(j+j2); } } int start=(int) (l-((indexl-1)*2*N-(indexl-1)*(indexl)+1)); int end=(int) (r-((indexl-1)*2*N-(indexl-1)*(indexl)+1)); for (int j = start; j <= end; j++) { out.println(arrayList.get(j)); } } out.flush(); } static class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } }
Java
["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"]
2 seconds
["1 2 1 \n1 3 2 3 \n1"]
NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "graphs" ]
afb43928545743b497b1a9975768f8e5
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.
1,800
For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.
standard output
PASSED
29c7738eb8ea3b4bb80facbffc6ed64b
train_002.jsonl
1586529300
You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.List; public class CE85D { public static void main(String[] args) throws NumberFormatException, IOException { FastReader sc=new FastReader(); int t = sc.nextInt(); for(int x=0; x<t; x++) { long n = sc.nextLong(); long l = sc.nextLong(); long r = sc.nextLong(); long total = (n)*(n-1)+1; //System.out.println("totes" + total); // if(l == total && r==total) { // System.out.println(1); // continue; // } long first = 1; long second = 0; long sum = 0; while(true) { long next = 2*(n-first); //System.out.println(next); if(sum + next < l) { first += 1; sum += next; } else { break; } if(next == 2) { break; } } //System.out.println("sumdy" + sum); long diff = l - sum; second = first + 1 + ((diff-1)/2); //System.out.println("fgege" + first + " " + second); while(l <= r) { //System.out.println("ell"+ l); if(l == total) { System.out.print("1 "); } else { if(l%2 == 0) { //second System.out.print(second + " "); if(second < n) { second += 1; } else { first += 1; second = first + 1; } } else { System.out.print(first + " "); } } l++; } System.out.println(); } } 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;}} } /* int n = sc.nextInt(); for(int y=0; y<n; y++){ int x = sc.nextInt(); } int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int d = sc.nextInt(); int e = sc.nextInt(); */
Java
["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"]
2 seconds
["1 2 1 \n1 3 2 3 \n1"]
NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "graphs" ]
afb43928545743b497b1a9975768f8e5
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.
1,800
For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.
standard output
PASSED
69677cd151a5d79310ad59dacfa3e60d
train_002.jsonl
1586529300
You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.
256 megabytes
// Problem : D. Minimum Euler Cycle // Contest : Educational Codeforces Round 85 (Rated for Div. 2) // URL : https://codeforces.com/contest/1334/problem/D // Memory Limit : 256 MB // Time Limit : 2000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) import java.io.*; import java.util.*; public class a { public static void main(String[] args) throws Exception { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); //PrintWriter out = new PrintWriter("file.out"); Task solver = new Task(); int t = scan.nextInt(); //int t = 1; for(int i = 1; i <= t; i++) solver.solve(i, scan, out); out.close(); } static class Task { static final int inf = Integer.MAX_VALUE; public void solve(int testNumber, FastReader sc, PrintWriter pw) { int n = sc.nextInt(); long sum =1; long l = sc.nextLong(); long r = sc.nextLong(); long c = 2*n-2; int start = 1; while(sum+c<l){ sum+=c;c-=2; if(c==0)c++; start++; } //pw.println(sum); ArrayList<Long> arr= new ArrayList<Long>(); c= start; long curr = c+1; while(sum<=Math.min(1l*n*(n-1),r)){ if(curr == n+1){ c++; curr = c+1; } if(sum>=l&&sum<=r){ arr.add(c); } sum++; if(sum>=l&&sum<=r){ arr.add(curr); } curr++; //pw.println(curr); sum++; } if(r==1l*n*(n-1)+1)arr.add(1l); for(long x : arr){ pw.print(x+" "); } pw.println(); } } 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 class tup implements Comparable<tup>{ int a, b; tup(int a,int b){ this.a=a; this.b=b; } @Override public int compareTo(tup o){ return Integer.compare(o.b,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
["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"]
2 seconds
["1 2 1 \n1 3 2 3 \n1"]
NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "graphs" ]
afb43928545743b497b1a9975768f8e5
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.
1,800
For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.
standard output
PASSED
f00b6e5d0c25bb97a12fa4c6338b51c8
train_002.jsonl
1586529300
You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class Graph { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { Reader scan=new Reader(); int t=scan.nextInt(); while(t-->0) { long n=scan.nextLong(); long l=scan.nextLong(); long r=scan.nextLong(); D1334(n, l, r, 1, 1); System.out.println(); } } public static void D1334(long n, long l, long r, long seg, long cur) { if(cur>r) return; if(seg==n) { System.out.print(1); return; } long t= 2*(n-seg); long hi= cur+t-1; if(hi<l) { D1334(n, l, r, seg+1, hi+1); return; } long i= l-cur+1; if(i%2==0) { System.out.print((seg+i/2)+" "); i++; } for(;i+cur-1<=Math.min(r, hi);i++) { if(i%2!=0) System.out.print(seg+" "); else System.out.print((seg+i/2)+" "); } if(i==r+1) return; D1334(n, hi+1, r, seg+1, hi+1); } }
Java
["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"]
2 seconds
["1 2 1 \n1 3 2 3 \n1"]
NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "graphs" ]
afb43928545743b497b1a9975768f8e5
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.
1,800
For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.
standard output
PASSED
43173f84cc3096879f1c3ebd061793f4
train_002.jsonl
1586529300
You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.
256 megabytes
/* *created by Kraken on 02-05-2020 at 14:27 */ //package com.kraken.cf.practice; import java.util.*; import java.io.*; public class D1334 { public static void main(String[] args) { FastReader sc = new FastReader(); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); long l = sc.nextLong(), r = sc.nextLong(); long[] block = new long[n + 1]; block[0] = 0; for (int i = 1; i <= n; i++) block[i] = 2 * (n - i) + block[i - 1]; block[n] += 2; // System.out.println(Arrays.toString(block)); long left = findBlock(block, l); long right = findBlock(block, r); // System.out.printf("left: %d, right: %d\n", left, right); long curr = left; ArrayList<Long> path = new ArrayList<>(); while (curr <= right) { for (long i = curr + 1; i <= n; i++) { path.add(curr); path.add(i); } curr++; } if (right == n) path.add(1L); // System.out.println(path.toString()); StringBuilder sb = new StringBuilder(); long lidx = l - block[(int) (left - 1)] - 1; for (int i = 0; i < r - l + 1; i++) { sb.append(path.get((int) (lidx + i))).append(" "); } System.out.println(sb.toString()); } } private static int findBlock(long[] a, long key) { int l = 1, r = a.length - 1; while (l < r) { int mid = l + (r - l) / 2; if (a[mid] >= key) r = mid; else l = mid + 1; } return r; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"]
2 seconds
["1 2 1 \n1 3 2 3 \n1"]
NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "graphs" ]
afb43928545743b497b1a9975768f8e5
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.
1,800
For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.
standard output
PASSED
7bd3e6e0646487e948b48cbb53e720c7
train_002.jsonl
1586529300
You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.
256 megabytes
import java.util.*; import java.io.*; public class D1334 { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); long l = sc.nextLong(), r = sc.nextLong(); int i; long c = 0; for(i = 1; i < n; i++) { c += 2l * (n - i); if(l <= c) { c -= 2l * (n - i); break; } } if(i == n) { pw.println("1"); continue; } long max = c + 2l * (n - i); StringBuilder sb = new StringBuilder(""); for(long j = l; j <= r; j++) { if(j > max) { if(i == n - 1) { sb.append("1 "); break; } else { c += 2l * (n - i); i++; max += 2l * (n - i); } } if(j % 2 == 1) { sb.append(i + " "); } else { sb.append((i + (1l * (j - c) / 2)) + " "); } } pw.println(sb.substring(0, sb.length() - 1)); } pw.flush(); } public 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 int[] nextIntArray(int n) throws IOException { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = nextInt(); return array; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] array = new Integer[n]; for (int i = 0; i < n; i++) array[i] = new Integer(nextInt()); return array; } public long[] nextLongArray(int n) throws IOException { long[] array = new long[n]; for (int i = 0; i < n; i++) array[i] = nextLong(); return array; } public double[] nextDoubleArray(int n) throws IOException { double[] array = new double[n]; for (int i = 0; i < n; i++) array[i] = nextDouble(); return array; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"]
2 seconds
["1 2 1 \n1 3 2 3 \n1"]
NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "graphs" ]
afb43928545743b497b1a9975768f8e5
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.
1,800
For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.
standard output
PASSED
40ff4028d137ccb91ad679ffb9b19734
train_002.jsonl
1586529300
You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.
256 megabytes
/* D A R K L _ _ O R D D A K / | | \ L O R D A R _ / | | \ _ K L O R D A R K _ / | _ | \ _ L O R D D R K L _ / _ | _ | \\ | _ \ O R D D R K _ / _ | _ | \ \ | _ \ L O R D A R _ / _ / | / / \ \ | \ _ \ _ K L O D D _ / _ / | / / \ \ | \ _ \ _ A K _ / _ / | / / _ \ \ | \ _ \ _ L O R D A _ / _ / | / / _ \ \ | \ _ \ _ R K _ / _ / | | | | \ (O) / | | \ _ \ _ O D _ / _ / | | | | \ / | | \ _ \ _ D A / _ / | | | \ | \ _ \|/ / | | | \ _ \ K / _ / | | | \ | \ _ V / | | | \ _ \ L / / | | | \ _ / \ _ _ / | | | \ \ / / | | | | | | | \ \ / / | | | \ \ ROWECHEN / / | | | \ \ / / _ _ | | | \ \ ZHONG / / | | | _ _ \ \ / / _ / \ | | | | \ / \ \ / / \ / | | | | / \ _ \ \ / / _ / \ | | | | \ \ / / | | | | / \ _ \ \ / / / \ \ \ \ / / \ \ / / / / \ \ \ \ / / \ \ \ \ / / \ \ / / / / \ \ / \|/ \|/ | | | \|/ \|/ L O \|/ | | | | \|/ R D A R K L / _ | | | _ \ O R D D A R L O R / _ | | | _ \ D D A R L O R D / / / _ | _ | | \ _ \ D A R K O R D / / / _ | | _ | | \ _ \ D A R K L R D D A R | / / | | / | | \ / | | \ | K L O R D A R K | / / | | / | | \ / | | \ | L O R D A R / \ / | | | / | | / \ / K L O R D D A / \ / | | | / | | / \/ R K L O R D D / | / \ | \ / A R K L O R D A R K L / | / \ | \/ O R D D R K L O R D \ / | D A R K L O R D A R \/ | K L O R D D */ //TEMPLATE V2 import java.io.*; import java.util.*; import java.math.*; public class Main { //Solution goes below: ------------------------------------ public static void solution() throws IOException{ int T = nextInt(); for(int test=0;test<T;test++){ long n = nextLong(); long l = nextLong()-1; long r = nextLong(); boolean end = false; long total = n*n-n+1; if(r==total){ r--; end = true; } for(long level=1;level<n;level++){ long len = 2*(n-level); for(long i=l;i<Math.min(len,r);i++){ /*print(len); print(" "); print(i); print(" "); print(l); print(" "); print(r); print(" "); print(level); print(" ");*/ if(i%2==0){ print(level); }else{ print(i/2+1+level); } print(" ");//println(" "); } l = Math.max(l-len,0); r = Math.max(r-len,0); } if(end){ println("1 "); }else{ println(); } } } //Solution goes above: ------------------------------------ public static final String IN_FILE = ""; public static final String OUT_FILE = ""; //-------------------- ------------------------------------ //IO public static BufferedReader br; public static StringTokenizer st; public static BufferedWriter bw; public static void main(String[] args) throws IOException{ if(IN_FILE==""){ br = new BufferedReader(new InputStreamReader(System.in)); }else{ try { br = new BufferedReader(new FileReader(IN_FILE)); } catch (FileNotFoundException e) { br = new BufferedReader(new InputStreamReader(System.in)); } } if (OUT_FILE==""){ bw = new BufferedWriter(new OutputStreamWriter(System.out)); }else{ try { bw = new BufferedWriter (new FileWriter(OUT_FILE) ); } catch (FileNotFoundException e) { bw = new BufferedWriter(new OutputStreamWriter(System.out)); } } solution(); bw.close();//Flushes too. } public static String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public static String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public static int nextInt() { return Integer.parseInt(nextToken()); } public static long nextLong() { return Long.parseLong(nextToken()); } public static double nextDouble() { return Double.parseDouble(nextToken()); } public static void println(Object s) throws IOException{ bw.write(s.toString()+"\n"); } public static void println() throws IOException{ bw.newLine(); } public static void print(Object s) throws IOException{ bw.write(s.toString()); } public static void flush() throws IOException{//Useful for debug bw.flush(); } //Other public static class Arr<T> extends ArrayList<T> {} //I hate typing ArrayList }
Java
["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"]
2 seconds
["1 2 1 \n1 3 2 3 \n1"]
NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "graphs" ]
afb43928545743b497b1a9975768f8e5
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.
1,800
For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.
standard output
PASSED
397f59f149dd9c8c32b9efa054133e21
train_002.jsonl
1586529300
You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.
256 megabytes
import java.util.Scanner; public class ProblemD { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); int t = s.nextInt(); for(int a=0;a<t;a++) { int n = s.nextInt(); long l = s.nextLong(); long r = s.nextLong(); long[] arr = new long[n]; long sum = 0; long val = 2*(n-1); for(int i=0;i<n-1;i++) { sum += val; val -= 2; arr[i] = sum; } arr[n-1] = arr[n-2] + 1; // for(int i=0;i<n;i++) // System.out.println(arr[i]); int index = upperBound(arr, l); //System.out.println(index); print(arr, l, r, index); System.out.println(); } } public static void print(long[] arr, long l, long r, int index) { int n = arr.length; if(index == n-1) { System.out.print(1+" "); return; } long val1 = index + 1, val2 = 0; long end = arr[index]; if(l%2 == 0) { val2 = n - (end-l)/2; } else { val2 = n - (end-l-1)/2; } for(long i=l;l <= Math.min(end, r);l++) { if(l%2 == 1) System.out.print(val1+" "); else { System.out.print(val2+" "); val2++; } } if(end < r) print(arr, end + 1, r, index + 1); } public static int upperBound(long[] arr, long v) { if(v > arr[arr.length-1]) return -1; if(arr[0] > v) return 0; int low = 0, high = arr.length - 1; while(low < high) { if(low == high - 1) { if(arr[low] >= v) high = low; else low = high; break; } int mid = (low + high)/2; if(arr[mid] >= v) high = mid; else low = mid + 1; } return low; } }
Java
["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"]
2 seconds
["1 2 1 \n1 3 2 3 \n1"]
NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "graphs" ]
afb43928545743b497b1a9975768f8e5
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.
1,800
For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.
standard output
PASSED
0ad39a6ee50ca21d9aa279c30798eb6d
train_002.jsonl
1586529300
You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class ProblemD { public static void main(String[] args) { // TODO Auto-generated method stub FastReader s = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = s.nextInt(); for(int a=0;a<t;a++) { int n = s.nextInt(); long l = s.nextLong(); long r = s.nextLong(); long[] arr = new long[n]; long sum = 0; long val = 2*(n-1); for(int i=0;i<n-1;i++) { sum += val; val -= 2; arr[i] = sum; } arr[n-1] = arr[n-2] + 1; // for(int i=0;i<n;i++) // System.out.println(arr[i]); int index = upperBound(arr, l); //System.out.println(index); print(arr, l, r, index, out); out.println(); } out.flush(); } public static void print(long[] arr, long l, long r, int index, PrintWriter out) { int n = arr.length; if(index == n-1) { out.print(1+" "); return; } long val1 = index + 1, val2 = 0; long end = arr[index]; if(l%2 == 0) { val2 = n - (end-l)/2; } else { val2 = n - (end-l-1)/2; } for(long i=l;l <= Math.min(end, r);l++) { if(l%2 == 1) out.print(val1+" "); else { out.print(val2+" "); val2++; } } if(end < r) print(arr, end + 1, r, index + 1, out); } public static int upperBound(long[] arr, long v) { if(v > arr[arr.length-1]) return -1; if(arr[0] > v) return 0; int low = 0, high = arr.length - 1; while(low < high) { if(low == high - 1) { if(arr[low] >= v) high = low; else low = high; break; } int mid = (low + high)/2; if(arr[mid] >= v) high = mid; else low = mid + 1; } return low; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"]
2 seconds
["1 2 1 \n1 3 2 3 \n1"]
NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "graphs" ]
afb43928545743b497b1a9975768f8e5
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.
1,800
For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.
standard output
PASSED
bc6a964da99972378878c08fd9367f52
train_002.jsonl
1586529300
You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); DMinimumEulerCycle solver = new DMinimumEulerCycle(); solver.solve(1, in, out); out.close(); } static class DMinimumEulerCycle { public void solve(int testNumber, Scanner sc, PrintWriter pw) { int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); long a = sc.nextLong(); long b = sc.nextLong(); long[] arr = new long[n]; arr[0] = 2 * n - 2; for (int i = 1; i < n - 1; i++) arr[i] = arr[i - 1] + 2 * (n - i - 1); arr[n - 1] = arr[n - 2] + 1; int in = 0; int la = 0; int l = 0; int h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= a) { in = mid; h = mid - 1; } else { l = mid + 1; } } l = 0; h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= b) { la = mid; h = mid - 1; } else { l = mid + 1; } } for (int i = in; i <= la; i++) { int[] tmp = new int[2 * (n - i) - 2]; int idx = 0; if (i == n - 1) pw.print(1); else { for (int j = i + 2; j <= n; j++) { tmp[idx] = i + 1; if (idx + 1 < tmp.length) tmp[idx + 1] = j; idx += 2; } if (i == in) { if (i == la) { int s = (int) (a - (i == 0 ? 0 : arr[i - 1]) - 1); int e = (int) (b - (i == 0 ? 0 : arr[i - 1])); for (int j = s; j < e; j++) pw.print(tmp[j] + " "); } else { int s = (int) (a - (i == 0 ? 0 : arr[i - 1]) - 1); for (int j = s; j < tmp.length; j++) pw.print(tmp[j] + " "); } } else if (i == la) { int e = (int) (b - (i == 0 ? 0 : arr[i - 1])); for (int j = 0; j < e; j++) pw.print(tmp[j] + " "); } else { for (int j = 0; j < tmp.length; j++) pw.print(tmp[j] + " "); } } } pw.println(); } pw.flush(); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"]
2 seconds
["1 2 1 \n1 3 2 3 \n1"]
NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "graphs" ]
afb43928545743b497b1a9975768f8e5
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.
1,800
For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.
standard output
PASSED
ecce6e58d229fd3c1bc4ca0174586e3c
train_002.jsonl
1586529300
You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; /** * Built using CHelper plug-in * Actual solution is at the top */ public class MinimumEulerCycle { public static void main(String[] args) throws IOException { 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.nextInt(), in, out); out.close(); } static class TaskA { long mod = (long)(1000000007); public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException { String s = "1213231"; while(testNumber-->0){ long n = in.nextLong(); long l = in.nextLong(); long r = in.nextLong(); if(l == n*(n-1)+1){ out.println(1); continue; } long x = findX(n , l); long prev = 2*n*(x-1) - x*(x-1); for(long i = l;i<=r;i++){ if(i == n*(n-1) + 1){ out.print(1 + " "); continue; } if((i - prev)%2 == 1) out.print(x + " "); else{ out.print((i - prev)/2 + x + " "); if((i-prev)/2 + x == n){ x++; prev = i; } } } out.println(); } } public long findX(long n , long l){ long x = 0; long count = 0; while(count<l){ x++; count += 1 + 2*(n-1-x) + 1; } return x; } public void mapAdd(HashMap<Long , ArrayList<Long>> m , long x , long y){ if(!m.containsKey(x)) m.put(x , new ArrayList<>()); m.get(x).add(y); } public void update(long a[] , int index , long value){ for(int i=index;i<a.length;i += i&(-i)) a[i] += value; } public long get(long a[] , int index){ long res = 0; for(int i=index;i>0;i-=i&(-i)) res += a[i]; return res; } public int[] nextGreater(int a[] , int n){ int ng[] = new int[n+1]; Deque<Combine> s = new LinkedList<>(); for(int i=n;i>0;i--){ int k = i; Combine c = new Combine(a[k] , k); while(s.size()>0 && s.peekLast().value <= c.value){ Combine d = s.pollLast(); ng[d.delete] = c.delete; } s.addLast(c); } return ng; } public void sieve(int a[]){ a[0] = a[1] = 1; int i; for(i=2;i*i<=a.length;i++){ if(a[i] != 0) continue; a[i] = i; for(int k = (i)*(i);k<a.length;k+=i){ if(a[k] != 0) continue; a[k] = i; } } } public int [][] matrixExpo(int c[][] , int n){ int a[][] = new int[c.length][c[0].length]; int b[][] = new int[a.length][a[0].length]; for(int i=0;i<c.length;i++) for(int j=0;j<c[0].length;j++) a[i][j] = c[i][j]; for(int i=0;i<a.length;i++) b[i][i] = 1; while(n!=1){ if(n%2 == 1){ b = matrixMultiply(a , a); n--; } a = matrixMultiply(a , a); n/=2; } return matrixMultiply(a , b); } public int [][] matrixMultiply(int a[][] , int b[][]){ int r1 = a.length; int c1 = a[0].length; int c2 = b[0].length; int c[][] = new int[r1][c2]; for(int i=0;i<r1;i++){ for(int j=0;j<c2;j++){ for(int k=0;k<c1;k++) c[i][j] += a[i][k]*b[k][j]; } } return c; } public long nCrPFermet(int n , int r , long p){ if(r==0) return 1l; long fact[] = new long[n+1]; fact[0] = 1; for(int i=1;i<=n;i++) fact[i] = (i*fact[i-1])%p; long modInverseR = pow(fact[r] , p-2 , 1l , p); long modInverseNR = pow(fact[n-r] , p-2 , 1l , p); long w = (((fact[n]*modInverseR)%p)*modInverseNR)%p; return w; } public long pow(long a , long b , long res , long mod){ if(b==0) return res; if(b==1) return (res*a)%mod; if(b%2==1){ res *= a; res %= mod; b--; } // System.out.println(a + " " + b + " " + res); return pow((a*a)%mod , b/2 , res , mod); } public long pow(long a , long b , long res){ if(b == 0) return res; if(b==1) return res*a; if(b%2==1){ res *= a; b--; } return pow(a*a , b/2 , res); } public void swap(int a[] , int p1 , int p2){ int x = a[p1]; a[p1] = a[p2]; a[p2] = x; } public void sortedArrayToBST(TreeSet<Integer> a , int start, int end) { if (start > end) { return; } int mid = (start + end) / 2; a.add(mid); sortedArrayToBST(a, start, mid - 1); sortedArrayToBST(a, mid + 1, end); } class Combine{ int value; int delete; Combine(int val , int delete){ this.value = val; this.delete = delete; } } class Sort2 implements Comparator<Combine>{ public int compare(Combine a , Combine b){ if(a.value > b.value) return 1; else if(a.value == b.value && a.delete>b.delete) return 1; else if(a.value == b.value && a.delete == b.delete) return 0; return -1; } } public int lowerLastBound(ArrayList<Integer> a , int x){ int l = 0; int r = a.size()-1; if(a.get(l)>=x) return -1; if(a.get(r)<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid-1)<x) return mid-1; else if(a.get(mid)>=x) r = mid-1; else if(a.get(mid)<x && a.get(mid+1)>=x) return mid; else if(a.get(mid)<x && a.get(mid+1)<x) l = mid+1; } return mid; } public int upperFirstBound(ArrayList<Integer> a , Integer x){ int l = 0; int r = a.size()-1; if(a.get(l)>x) return l; if(a.get(r)<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid+1)>x) return mid+1; else if(a.get(mid)<=x) l = mid+1; else if(a.get(mid)>x && a.get(mid-1)<=x) return mid; else if(a.get(mid)>x && a.get(mid-1)>x) r = mid-1; } return mid; } public int lowerLastBound(int a[] , int x){ int l = 0; int r = a.length-1; if(a[l]>=x) return -1; if(a[r]<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid-1]<x) return mid-1; else if(a[mid]>=x) r = mid-1; else if(a[mid]<x && a[mid+1]>=x) return mid; else if(a[mid]<x && a[mid+1]<x) l = mid+1; } return mid; } public int upperFirstBound(long a[] , long x){ int l = 0; int r = a.length-1; if(a[l]>x) return l; if(a[r]<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid+1]>x) return mid+1; else if(a[mid]<=x) l = mid+1; else if(a[mid]>x && a[mid-1]<=x) return mid; else if(a[mid]>x && a[mid-1]>x) r = mid-1; } return mid; } public long log(float number , int base){ return (long) Math.floor((Math.log(number) / Math.log(base))); } public long gcd(long a , long b){ if(a<b){ long c = b; b = a; a = c; } if(b == 0) return a; return gcd(b , a%b); } public void print2d(long a[][] , PrintWriter out){ for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++) out.print(a[i][j] + " "); out.println(); } out.println(); } public void print1d(int a[] , PrintWriter out){ for(int i=0;i<a.length;i++) out.print(a[i] + " "); out.println(); out.println(); } class Node{ int index; Node right; Node left; public Node(int index){ this.index = index; right = null; left = null; } } class AVLTree{ Node root; public AVLTree(){ this.root = null; } public int height(Node n){ return (n == null ? 0 : n.height); } public int getBalance(Node n){ return (n == null ? 0 : height(n.left) - height(n.right)); } public Node rotateRight(Node a){ Node b = a.left; Node br = b.right; a.lSum -= b.lSum; a.lCount -= b.lCount; b.rSum += a.rSum; b.rCount += a.rCount; b.right = a; a.left = br; a.height = 1 + Math.max(height(a.left) , height(a.right)); b.height = 1 + Math.max(height(b.left) , height(b.right)); return b; } public Node rotateLeft(Node a){ Node b = a.right; Node bl = b.left; a.rSum -= b.rSum; a.rCount -= b.rCount; b.lSum += a.lSum; b.lCount += a.lCount; b.left = a; a.right = bl; a.height = 1 + Math.max(height(a.left) , height(a.right)); b.height = 1 + Math.max(height(b.left) , height(b.right)); return b; } public Node insert(Node root , long value){ if(root == null){ return new Node(value); } if(value<=root.value){ root.lCount++; root.lSum += value; root.left = insert(root.left , value); } if(value>root.value){ root.rCount++; root.rSum += value; root.right = insert(root.right , value); } // updating the height of the root root.height = 1 + Math.max(height(root.left) , height(root.right)); int balance = getBalance(root); //ll if(balance>1 && value<=root.left.value) return rotateRight(root); //rr if(balance<-1 && value>root.right.value) return rotateLeft(root); //lr if(balance>1 && value>root.left.value){ root.left = rotateLeft(root.left); return rotateRight(root); } //rl if(balance<-1 && value<=root.right.value){ root.right = rotateRight(root.right); return rotateLeft(root); } return root; } public void insertElement(long value){ this.root = insert(root , value); } public int getElementLessThanK(long k){ int count = 0; Node temp = root; while(temp!=null){ if(temp.value == k){ if(temp.left == null || temp.left.value<k){ count += temp.lCount; return count-1; } else temp = temp.left; } else if(temp.value>k){ temp = temp.left; } else{ count += temp.lCount; temp = temp.right; } } return count; } public void inorder(Node root , PrintWriter out){ Node temp = root; if(temp!=null){ inorder(temp.left , out); out.println(temp.value + " " + temp.lCount + " " + temp.rCount); inorder(temp.right , out); } } class Node{ long value; long lCount , rCount; long lSum , rSum; Node left , right; int height; public Node(long value){ this.value = value; left = null; right = null; lCount = 1; rCount = 1; lSum = value; rSum = value; height = 1; } } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2 1 3\n3 3 6\n99995 9998900031 9998900031"]
2 seconds
["1 2 1 \n1 3 2 3 \n1"]
NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "graphs" ]
afb43928545743b497b1a9975768f8e5
The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.
1,800
For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.
standard output
PASSED
04ab892e568189c6edc6a10a7d1e012f
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.util.Scanner; /* * 输入n个字符串 * 记将字符串的第一个字符移到字符串的最后为一步操作 * 输出最少的步数使得n个字符串相同,无解输出-1 * */ public class MikeAndStrings { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int min = 1000000; int flag = 0; String str[] = new String[n]; for (int i = 0; i < n; i++) { str[i] = scanner.next(); } for (int j = 0; j < n; j++) { int count = 0; String x = str[j]; flag = 0; for (int k = 0; k < n; k++) { String y = str[k]; flag = 0; for (int m = 0; m < str[k].length(); m++) { if (str[k].equals(x)) { flag = 1; break; } else { count++; str[k] = str[k].substring(1) + str[k].substring(0, 1); } } if (flag == 0) break; str[k] = y; } if (flag == 0) break; min = min >= count ? count : min; } if (flag == 0) { System.out.println("-1"); } else { System.out.println(min); } } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
ee4dc89699e18c4ea21f556f8a045dc9
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.util.Scanner; /* * 输入n个字符串 * 记将字符串的第一个字符移到字符串的最后为一步操作 * 输出最少的步数使得n个字符串相同,无解输出-1 * */ public class MikeAndStrings { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int min = 1000000; boolean flag = false; String str[] = new String[n]; for (int i = 0; i < n; i++) { str[i] = scanner.next(); } for (int j = 0; j < n; j++) { int count = 0; String x = str[j]; flag = false; for (int k = 0; k < n; k++) { String y = str[k]; flag = false; for (int m = 0; m < str[k].length(); m++) { if (str[k].equals(x)) { flag = true; break; } else { count++; str[k] = str[k].substring(1) + str[k].substring(0, 1); } } if (flag == false) break; str[k] = y; } if (flag == false) break; min = min >= count ? count : min; } if (flag == false) { System.out.println("-1"); } else { System.out.println(min); } } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
782fb2fb7d467d716cff3c02de84b064
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.util.*; import java.util.stream.*; import java.io.*; import java.math.*; import java.awt.geom.*; public class Main { public static final BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); public static final PrintWriter outWriter = new PrintWriter(System.out); public static int hackLen = Integer.MAX_VALUE; public static int normalizeIndex(String init) { String min = init, s = init; int minNdx = 0; for (int i = 1; i < s.length(); i++) { s = s.substring(1) + s.substring(0,1); if (s.equals(init)) { hackLen = i; break; } else if (min.compareTo(s) > 0) { min = s; minNdx = i; } } return minNdx; } public static String normalize(String s) { int ndx = normalizeIndex(s); return s.substring(ndx)+s.substring(0,ndx); } public static int cost(int b, int a, int len) { return a >= b ? a-b : a+len-b; } public static int cost(int[] ndxes, int a, int len) { int out = 0; for (int b : ndxes) { out += cost(a, b, len); } return out; } public static int minCost(int[] ndxes, int len) { int out = cost(ndxes, 0, len); for (int i = 1; i < len; i++) { out = Math.min(out, cost(ndxes, i, len)); } return out; } public static void main() { int n = nextInt(); String init = next(); int[] ndxes = new int[n]; String normalized = normalize(init); ndxes[0] = normalizeIndex(init); for (int i = 1; i < n; i++) { String tmp = next(); if (!normalize(tmp).equals(normalized)) { outWriter.println(-1); return; } ndxes[i] = normalizeIndex(tmp); } outWriter.println(minCost(ndxes, Math.min(hackLen, normalized.length()))); } public static void main(String[] args) { main(); outWriter.flush(); } public static StringTokenizer tokenizer = null; public static String nextLine() { try { return buffer.readLine(); } catch (IOException e) { throw new UncheckedIOException(e); } } public static String next() { while (tokenizer == null || !tokenizer.hasMoreElements()) { tokenizer = new StringTokenizer(nextLine()); } return tokenizer.nextToken(); } public static int nextInt() { return Integer.parseInt(next()); } public static long nextLong() { return Long.parseLong(next()); } public static double nextDouble() { return Double.parseDouble(next()); } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
80d18fde32e63c19e5826ce008bc1720
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
//package ap; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class one { //static HashMap<Integer,Integer> po[]=new HashMap[25000]; //static int mod= 1000000007; //static int val[]=new int[12501]; public static void main(String[] args) { InputReader scnr = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n=scnr.nextInt(); String s[]=new String[n]; for(int i=0;i<n;i++){ s[i]=scnr.readString(); } int min=Integer.MAX_VALUE; for(int i=0;i<n;i++){ String y=s[i]; int sum=0; for(int x=0;x<n;x++){ int val=compare(y,s[x]); if(val==-1){ break; } sum+=val; } min=Math.min(sum, min); } if(min>=100000){ System.out.println(-1); }else System.out.println(min); } static int compare(String s1,String s2){ if(s1.equals(s2)){ return 0; } else{ for(int i=0;i<s1.length();i++){ s2=s2.substring(1)+s2.charAt(0); if(s1.equals(s2)){ return i+1; } } return (int)Math.pow(10, 5); } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
349de69e53621c9e0aedbdb684d0b974
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; public class Main { public static InputReader in; public static PrintWriter pw; public static void main(String args[]) { new Thread(null, new Runnable() { public void run() { try{ solve(); } catch(Exception e){ e.printStackTrace(); } } }, "1", 1 << 26).start(); } static ArrayList<Integer> g[]; static ArrayList<Integer> h[]; static boolean visited[]; static boolean parent[]; static int par[]; static int degree[]; static int edjes=0; static int start=-1; static int end=-1; static int Total=0; static int time1[]; static int time2[]; static int glob=0; static long ans[]=new long[1000000]; static boolean vis2[][]; //static long sum1=0; //static long val[]; static ArrayList<Integer> levels[]; static int max=0; static int lev=1; static ArrayList<Integer> nodes[]; static ArrayList<Integer> values[]; static int depth[]; static boolean found=false; // static long sm[]; static int sum1=0; static int pre[][]; static int subtree[]; static int cnt=0; static HashMap<String,Integer> hm; static int sm[]; static int prime[]; static long mul[]; static long d[]=new long[1000000]; static int tot=0; static long highest=(long)1e9; static boolean bit=false; static Stack<Integer> tt=new Stack(); static HashSet<String> set=new HashSet<String>(); public static void solve(){ in = new InputReader(System.in); pw = new PrintWriter(System.out); int n=in.nextInt(); String s[]=new String[n]; int fr[][]=new int[26][n]; for(int i=0;i<n;i++) { s[i]=in.readString(); for(int j=0;j<s[i].length();j++) { fr[s[i].charAt(j)-'a'][i]++; } } for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { for(int k=0;k<26;k++) { if(fr[k][i]!=fr[k][j]) { System.out.println(-1); System.exit(0); } } } } int minp=Integer.MAX_VALUE; for(int i=0;i<n;i++) { int sm=0; for(int j=0;j<n;j++) { if(s[i].equals(s[j])) continue; int min=100000000; for(int k=1;k<s[j].length();k++) { String p=s[j].substring(0,k); String q=s[j].substring(k,s[j].length()); StringBuilder sb=new StringBuilder(q); sb.append(p); //System.out.println(sb.toString()); if(sb.toString().equals(s[i])) { min=k; break; } } sm+=min; } minp=Math.min(minp, sm); } if(minp>10000000) minp=-1; System.out.println(minp); } static class Pair implements Comparable<Pair>{ int now; int aft; //int index; Pair(int ver,int weight){ this.now=ver; this.aft=weight; //this.index=index; } @Override public int compareTo(Pair o) { return (int)(o.now-now); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
05e4dacd9260fe24c98e0efa9b5d0a21
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /* * 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 msagimbekov */ public class Codeforces798B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String s = br.readLine(); int m = s.length(); char[][] c = new char[n][m]; c[0] = s.toCharArray(); for (int i = 1; i < n; i++) { c[i] = br.readLine().toCharArray(); } int min = Integer.MAX_VALUE; int res; for (int i = 0; i < n; i++) { res = 0; for (int j = 0; j < n; j++) { if (i != j) { int dist = dist(c[i], c[j], m); if (dist == -1) { System.out.println("-1"); return; } res += dist; } } if (min > res) { min = res; } } System.out.println(min); br.close(); } private static int dist(char[] a, char[] b, int m) { int res = 0; boolean found = false; int start = 0; int cnt = 0; while (start < m) { for (int i = 0; i < m; i++) { int ind = start + i; if (ind >= m) { ind %= m; } if (b[ind] != a[i]) { cnt = 0; break; } else { cnt++; } } if (cnt == m) { found = true; res = start; break; } start++; } return found ? res : -1; } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
8150976a405a91dcf5f83bd73b9d0bd9
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author toshif */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyReader in = new MyReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, MyReader in, PrintWriter out) { int n = in.nextInt(); String[] s = new String[n]; for (int i = 0; i < n; i++) { s[i] = in.next(); } int m = s[0].length(); List<Integer>[] offset = new List[n]; for (int i = 0; i < n; i++) { offset[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { for (int a = 0; a < m; a++) { String s1 = s[i].substring(a) + s[i].substring(0, a); if (s[0].equals(s1)) { offset[i].add(a); } } if (offset[i].isEmpty()) { out.println(-1); return; } } int mi = 1000_000; for (int off = 0; off < m; off++) { int cnt = 0; for (int i = 0; i < n; i++) { int best = 1000_000; for (Integer of : offset[i]) { int c1 = 0; if (off <= of) { c1 += of - off; } else { c1 += of + (m - off); } best = Math.min(best, c1); } cnt += best; } mi = Math.min(mi, cnt); } out.println(mi); } } static class MyReader { public BufferedReader reader; public StringTokenizer tokenizer; public MyReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
1510426db33f8c6d3f60b74f05155c4b
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.util.*; public class MikeAndStrings { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt();scan.nextLine(); String[] s=new String[n]; for(int i=0;i<n;i++) s[i]=scan.nextLine(); int res=0, min=(int)1e9; for(int i=0;i<n;i++) { res=-1; for(int j=0;j<n;j++) { int c=0; String or=s[j]; while(c<50&&!s[i].equals(s[j])) { s[j]=shift(s[j]); c++; } s[j]=or; if(c==50)break; if(res==-1)res++; res+=c; } min=Math.min(min, res); } System.out.println(min); } public static String shift(String s) { return s.substring(1)+s.charAt(0); } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
14cfd254d0f67e1056cb8cceaabe9c79
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import javafx.util.Pair; 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 iint() { return Integer.parseInt(next()); } long ilong() { return Long.parseLong(next()); } double idouble() { return Double.parseDouble(next()); } String readline() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int makeequal(StringBuffer sb1,StringBuffer sb2) { int count=-1; char[] ch1=sb1.toString().toCharArray(); char[] ch2=sb2.toString().toCharArray(); Arrays.sort(ch1); Arrays.sort(ch2); String st1=new String(ch1); String st2=new String(ch2); if(st1.equals(st2)) count=0; else return count; boolean notpossible=true; for(int i=0;i<sb1.length();i++) { if(sb1.toString().equals(sb2.toString())){ notpossible=false; break; } else { char[] ch=new char[1]; ch[0]=sb2.charAt(0); sb2.deleteCharAt(0); sb2.append(new String(ch)); count++; } } if(notpossible==false) return count; else return -1; } } public static void main(String[] args) { FastReader s=new FastReader(); // System.out.println(s.makeequal(new StringBuffer("zwoxz"),new StringBuffer("xzzwo"))); //System.out.println(s.makeequal(new StringBuffer("zwoxz"),new StringBuffer("zzwox"))); //System.out.println(s.makeequal(new StringBuffer("zwoxz"),new StringBuffer("xzzwo"))); // /* int n=s.iint(); String[] arrayst=new String[n]; for (int i=0;i<n ;i++ ) { arrayst[i]=s.next(); } boolean ans=false; int sum=0; int minmove=10000000; int len=arrayst[0].length(); //int[] sumarray=new int[n]; for (int i=0;i<n ;i++ ) { StringBuffer sb=new StringBuffer(arrayst[i]); for (int j=0;j<len ;j++ ) { char c=sb.charAt(0); sb.deleteCharAt(0); sb.append(c); sum=0; for (int k=0;k<n ;k++ ) { if(i!=k) { if(s.makeequal(sb,new StringBuffer(arrayst[k]))<0) { ans=true; break; } else sum+=s.makeequal(sb,new StringBuffer(arrayst[k])); } } //System.out.println(sum); if(j!=len-1) sum=sum+j+1; if(sum<minmove) minmove=sum; } } if(ans==false){ System.out.println(minmove); } else System.out.println("-1"); } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
6ec942a8dab82f9065e0a12c17cd56b7
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.io.*; import java.util.*; public class MikeAndStrings { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // int test = Integer.parseInt(br.readLine().trim()); // while(test --> 0) { int n = Integer.parseInt(br.readLine().trim()); String s[] = new String[n]; for(int i=0;i<n;i++) { s[i] = br.readLine().trim(); } int l = s[0].length(), res=0, c=100000, pdt=1, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; // int a[] = new int[n]; // int b[] = new int[n]; long sum = 0; boolean f = true; // StringBuffer s1 = new StringBuffer(); // StringBuffer s2 = new StringBuffer(); for(int i=0;i<l;i++) { String s1 = s[0].substring(i, l) + new StringBuffer(s[0].substring(0,i)).toString(); c = i; for(int j=1;j<n;j++) { boolean makeEqual = false; for( int k=0;k<l;k++) { String s2 = s[j].substring(k, l) + new StringBuffer(s[j].substring(0, k)).toString(); // System.out.println(j+1 + " " + s1 + " " + s2); if(s1.equals(s2)) { c += k; makeEqual = true; break; // System.out.println("true"); } } if(!makeEqual) f = false; } if(!f) break; min = Math.min(min, c); } if(f) { System.out.println(min); } else { System.out.println(-1); } // } } private static void solve() { } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
d973ed5e03d5d96f5684efaf58d26362
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.util.*; public class MikeAndStrings { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String[] strings = new String[n]; for (int i = 0; i < n; i++) { strings[i] = in.next(); } int k = strings[0].length(); int[][] dp = new int[n][k]; for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) { dp[i][j] = Integer.MAX_VALUE - k; } } for (int i = 0; i < n; i++) { strings[i] = strings[i] + strings[i]; } for (int i = 0; i < k; i++) { dp[0][i] = i; } for (int i = 1; i < n; i++) { for (int j = 0; j < k; j++) { for (int prev = 0; prev < k; prev++) { if (strings[i].substring(j, j + k).equals(strings[i - 1].substring(prev, prev + k))) { dp[i][j] = Math.min(dp[i][j], dp[i - 1][prev] + j); } } } } int ans = Integer.MAX_VALUE - k; for (int i = 0; i < k; i++) { ans = Math.min(ans, dp[n - 1][i]); } if (ans == Integer.MAX_VALUE - k) { System.out.println(-1); } else { System.out.println(ans); } } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
106df38f234b0751e7fdc51908703dcc
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
/* / フフ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ム / )\⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ Y (⠀⠀| ( ͡° ͜ʖ ͡°)⠀⌒(⠀ ノ (⠀ ノ⌒ Y ⌒ヽ-く __/ | _⠀。ノ| ノ。 |/ (⠀ー '_人`ー ノ ⠀|\  ̄ _人'彡ノ ⠀ )\⠀⠀ 。⠀⠀ / ⠀⠀(\⠀ #⠀ / ⠀/⠀⠀⠀/ὣ====================D- /⠀⠀⠀/⠀ \ \⠀⠀\ ( (⠀)⠀⠀⠀⠀ ) ).⠀) (⠀⠀)⠀⠀⠀⠀⠀( | / |⠀ /⠀⠀⠀⠀⠀⠀ | / [_] ⠀⠀⠀⠀⠀[___] */ // Main Code at the Bottom import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; public class Main { //Fast IO class static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { boolean env=System.getProperty("ONLINE_JUDGE") != null; if(!env) { try { br=new BufferedReader(new FileReader("src\\input.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } } else br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long MOD=1000000000+7; //Euclidean Algorithm static long gcd(long A,long B){ return (B==0)?A:gcd(B,A%B); } //Modular Exponentiation static long fastExpo(long x,long n){ if(n==0) return 1; if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD; return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD; } //Modular Inverse static long inverse(long x) { return fastExpo(x,MOD-2); } //Prime Number Algorithm static boolean isPrime(long n){ if(n<=1) return false; if(n<=3) return true; if(n%2==0 || n%3==0) return false; for(int i=5;i*i<=n;i+=6) if(n%i==0 || n%(i+2)==0) return false; return true; } //Reverse an array static void reverse(int arr[],int l,int r){ while(l<r) { int tmp=arr[l]; arr[l++]=arr[r]; arr[r--]=tmp; } } //Print array static void print1d(int arr[]) { out.println(Arrays.toString(arr)); } static void print2d(long arr[][]) { for(long a[]: arr) out.println(Arrays.toString(a)); } // Pair static class pair{ int x,y; pair(int a,int b){ this.x=a; this.y=b; } public boolean equals(Object obj) { if(obj == null || obj.getClass()!= this.getClass()) return false; pair p = (pair) obj; return (this.x==p.x && this.y==p.y); } public int hashCode() { return Objects.hash(x,y); } } static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); //Main function(The main code starts from here public static void main (String[] args) throws java.lang.Exception { int test; test=1; //test=sc.nextInt(); while(test-->0){ int n=sc.nextInt(); String a[]=new String[n]; for(int i=0;i<n;i++) a[i]=sc.nextLine(); int ans=Integer.MAX_VALUE,flag=0; StringBuilder sb=new StringBuilder(a[0]); int N=a[0].length(); for(int pos=0;pos<N;pos++) { int cnt=0; for(int i=0;i<n;i++) { String tmp=new String(sb+""+sb); if(!tmp.contains(a[i])) { flag=1; break; } int idx=0,val=Integer.MAX_VALUE,len=tmp.length(); for(;idx<len;idx++) { int f=1; if(tmp.charAt(idx)==a[i].charAt(0) && idx+N-1<len) { f=0; for(int j=0;j<N;j++) if(a[i].charAt(j)!=tmp.charAt(idx+j)) { f=1; break; } } if(f==0) val=Math.min(val, N-idx); } if(val==N) val=0; cnt+=val; } if(flag==1) break; char c=sb.charAt(0); sb.replace(0, 1, ""); sb.append(c); ans=Math.min(ans, cnt); } if(flag==1) out.println(-1); else out.println(ans); } out.flush(); out.close(); } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
f8ebd2d9cedd544c5cc538478970e75f
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.io.*; import java.lang.Math; import java.util.*; public class stt { public static int norot(String str1,String str2) {int ans=0; boolean flag=true; for(int q=0;q<str1.length();q++) for(int r=0;r<str1.length();r++) { if(str1.charAt(r)!=str2.charAt((q+r)%str1.length())) {r=0; break; } if(r==str1.length()-1) return q; } return Integer.MAX_VALUE; } public static void main(String[] args) { //int sz = 1 << 15; // Scanner in = new Scanner(new BufferedInputStream(System.in, sz)); // PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out, sz)); Scanner s= new Scanner(System.in); int n=s.nextInt(); s.nextLine(); String arr[]= new String[n]; for(int i=0;i<n;i++) arr[i]=s.nextLine().trim(); int rot = 0; int min=Integer.MAX_VALUE; for(int i=0;i<n;i++) { rot=0; for(int j=0;j<n;j++) {if(j!=i) { int t=norot(arr[i],arr[j]); if(t==Integer.MAX_VALUE) {System.out.println("-1"); return; } else {rot+=t; // System.out.println("rot"+j+"="+rot); } } } min=Math.min(min,rot); // System.out.println("min"+i+"="+min); } // for(int i=0;i<n;i++) // System.out.println(arr[i]); System.out.println(min); /*System.out.println(norot("xzzwo","zwoxz")); System.out.println(norot("zwoxz","zzwox"));*/ } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
2ff49b721c8e5e715ee39dbb5f5fd8fb
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.util.Scanner; public class Sub { public static void main(String[] args) { int count1=50*50; Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); String[] s = new String[n]; for (int i = 0; i < n; i++) { s[i] = scanner.next(); } int count = 0; for (int i = 0; i < n; i++) { count =0; for (int j = 0; j < n; j++) { String mark = s[j]; Integer length = mark.length(); for (int k = 0; k < length; k++) { if (s[i].equals(mark)) { count = count + k; break; } else { mark = mark.substring(1, length) + mark.substring(0, 1); } if (k == length - 1 && !s[i].equals(mark)) { System.out.println(-1); System.exit(0); } } } if(count<count1) count1=count; } System.out.println(count1); } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
f1c5ee24347731885e8aae97dbc7821a
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class MikeAndStrings { public static FastScanner in = new FastScanner(System.in); public static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner(InputStream i) { reader = new BufferedReader(new InputStreamReader(i)); tokenizer = new StringTokenizer(""); } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) { try { int n = in.nextInt(); String[] text = new String[n]; for (int i = 0; i < n; i++) text[i] = in.next(); int minSum = Integer.MAX_VALUE; for (int j = 0; j < text[0].length(); j++) { String currentText = text[0].substring(j) + text[0].substring(0, j); int sum = 0; for (int i = 0; i < n; i++) { int k = 0; while (k < text[0].length() && !currentText.equals(text[i].substring(k) + text[i].substring(0, k))) k++; if (k == text[0].length()) { System.out.println("-1"); return; } sum += k; } minSum = Math.min(minSum, sum); } System.out.println(minSum); in.close(); } catch (Exception e) { e.printStackTrace(); } } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
70b922a4136dec4d17828b5482fc92fd
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.io.*; import java.util.*; /** * * @author akashvermaofskt * Coding is love <3! */ public class MikeAndStrings { public static void main(String args[]) { try { int n=nextInt(); String A[]=new String[n]; for (int i = 0; i < n; i++) { A[i]=next(); } long ans=Long.MAX_VALUE; for (int i = 0; i < n; i++) { long lans=0; for (int j = 0; j < n; j++) { String full=A[j]+""+A[j]; int index=full.indexOf(A[i]); if(index<0){ bw.write("-1\n"); bw.flush(); return; } lans+=index; } ans=Math.min(lans, ans); } bw.write(ans+"\n"); bw.flush(); } catch (Exception e) { e.printStackTrace(); } } //TEMPLATE //****************************************************************************** // Fast I/O static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static StringTokenizer st = null; static int mod=1000000007; static String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static int b_search(int l,int r,int A[],int key){ int ans=0; l=0;r=1000000000; while(l<r){ //System.out.println(ans); ans=(l+r)/2; long temp=0; for (int i = 0; i < A.length; i++) { temp+=(long)Math.ceil((double)A[i]/(double)ans); } if(temp<=key){ r=ans; } else{ l=ans+1; ans=r; } } return ans; } //****************************************************************************** //Modulo and FastExpo static long modInverse(long a) { return power(a, mod - 2,mod); } // To compute x^y under modulo m static long power(long x, long y, int p) { // Initialize result long res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if((y & 1)==1) res = (res * x) % p; // y must be even now // y = y / 2 y = y >> 1; x = (x * x) % p; } return res; } //****************************************************************************** //GCD static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } //****************************************************************************** // Useful user datatype static class Pair{ public long x; public long y; public Pair(long first, long second){ this.x = first; this.y = second; } @Override public String toString() { return "(" + x + "," + y + ")"; } } static Comparator csort=new Comparator<Pair>(){ public int compare(Pair a, Pair b) { if(a.x < b.x) return -1; else if (a.x > b.x) return 1; else if(a.y < b.y) return -1; else if (a.y > b.y) return 1; else return 0; } }; //****************************************************************************** //N choose K public static long choose(long total, long choose){ if(total < choose) return 0; if(choose == 0 || choose == total) return 1; return choose(total-1,choose-1)+choose(total-1,choose); } //****************************************************************************** //Permutations // simply prints all permutation - to see how it works private static void printPermutations( Comparable[] c ) { System.out.println( Arrays.toString( c ) ); while ( ( c = nextPermutation( c ) ) != null ) { System.out.println( Arrays.toString( c ) ); } } // modifies c to next permutation or returns null if such permutation does not exist private static Comparable[] nextPermutation( final Comparable[] c ) { // 1. finds the largest k, that c[k] < c[k+1] int first = getFirst( c ); if ( first == -1 ) return null; // no greater permutation // 2. find last index toSwap, that c[k] < c[toSwap] int toSwap = c.length - 1; while ( c[ first ].compareTo( c[ toSwap ] ) >= 0 ) --toSwap; // 3. swap elements with indexes first and last swap( c, first++, toSwap ); // 4. reverse sequence from k+1 to n (inclusive) toSwap = c.length - 1; while ( first < toSwap ) swap( c, first++, toSwap-- ); return c; } // finds the largest k, that c[k] < c[k+1] // if no such k exists (there is not greater permutation), return -1 private static int getFirst( final Comparable[] c ) { for ( int i = c.length - 2; i >= 0; --i ) if ( c[ i ].compareTo( c[ i + 1 ] ) < 0 ) return i; return -1; } // swaps two elements (with indexes i and j) in array private static void swap( final Comparable[] c, final int i, final int j ) { final Comparable tmp = c[ i ]; c[ i ] = c[ j ]; c[ j ] = tmp; } //****************************************************************************** // DSU //Maintain an Array A with N elements and Array size for size of each set, intialize A[i]=i and size[i]=1 static int root(int A[],int i){ while(A[i]!=i){ A[i]=A[A[i]]; i=A[i]; } return i; } static boolean find(int A[],int a,int b){ if(root(A,a)==root(A,b))return true; else return false; } static void union(int A[],int size[],int a,int b){ int ra=root(A,a); int rb=root(A,b); if(ra==rb)return; if(size[ra]<size[rb]){ A[ra]=A[rb]; size[rb]+=size[ra]; }else{ A[rb]=A[ra]; size[ra]+=size[rb]; } } //************************************************************************** //BinarySearch /* binary search for 5: v-- lower bound 1 2 3 4 5 5 5 6 7 9 ^-- upper bound binary search for 8 v-- lower bound 1 2 3 4 5 5 5 6 7 9 ^-- upper bound */ //For finding greater than static int upper_bound(int A[],int key){ int first = 0; int last = A.length; int mid; while (first < last) { mid =first+(last - first)/2; if (A[mid] <= key) first = mid + 1; else last = mid; } return first; } //For finding greater than equal to static int lower_bound(int A[],int key){ int first = 0; int last = A.length; int mid=0; while (first < last) { mid = first + ((last - first) >> 1); if (A[mid] < key) first = mid + 1; else last = mid; } return first; } //************************************************************************** }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
8892e46013630fbb2dad127019e19e8d
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class MikeAndStrings implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); private final long INF = (long) 1e9; public void solve() { int n = in.ni(); String[] x = new String[n]; for (int i = 0; i < n; i++) x[i] = in.next(); long min = INF; for (int i = 0; i < n; i++) { long local = 0; for (int j = 0; j < n; j++) { if (i != j) { local += f(x[i], x[j]); } } min = Math.min(min, local); } if (min >= INF) { out.println(-1); } else { out.println(min); } } private long f(String x, String y) { int index = (y + y).indexOf(x); return (index < 0) ? INF : index; } @Override public void close() throws IOException { in.close(); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (MikeAndStrings instance = new MikeAndStrings()) { instance.solve(); } } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
be83864f9b085fe0df509d4e7c72d35b
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.util.*; import java.io.*; public class Mikeandstrings { /************************ SOLUTION STARTS HERE ************************/ static HashSet<String> getCyclicRotation(String str) { HashSet<String> set = new HashSet<>(); for(int i=str.length() - 1;i >= 0;i--) { String shift = str.substring(i) + str.substring(0, i); ArrayList<Integer> arl = disp.getOrDefault(shift, new ArrayList<>()); arl.add(i); disp.put(shift, arl); set.add(shift); } // System.out.println("set " + set); return set; } static HashMap<String , ArrayList<Integer>> disp = new HashMap<>(); private static void solve() { int N = nextInt(); String arr[] = new String[N]; for(int i=0;i<N;i++) arr[i] = nextLine(); int len = arr[0].length(); HashSet<String> set = getCyclicRotation(arr[0]); for(String s : arr) if(!set.contains(s)) { println(-1); return; } HashMap<String , Integer> freq = new HashMap<>(); for(String s : arr) freq.put(s, freq.getOrDefault(s, 0) + 1); int min = Integer.MAX_VALUE; // println("disp " + disp); for(Map.Entry<String, Integer> e : freq.entrySet()) { int cost = 0; for(Map.Entry<String, Integer> f : freq.entrySet()) { int minShift = Integer.MAX_VALUE; for(int d1 : disp.get(e.getKey())) for(int d2 : disp.get(f.getKey())) minShift = Math.min(minShift,(d1 - d2 + len) % len); cost += f.getValue() * minShift; } min = Math.min(min,cost); } println(min); } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE **********************/ public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); st = null; solve(); reader.close(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer st; static 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();} static String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} static int nextInt() {return Integer.parseInt(next());} static long nextLong() {return Long.parseLong(next());} static double nextDouble(){return Double.parseDouble(next());} static char nextChar() {return next().charAt(0);} static int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;} static long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;} static int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;} static long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;} static void print(Object o) { writer.print(o); } static void println(Object o){ writer.println(o);} /************************ TEMPLATE ENDS HERE ************************/ }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output
PASSED
adae8448591812b37ffd6468efe18cfc
train_002.jsonl
1492785300
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); String s = in.nextLine(); String[] a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = in.nextLine(); } int N = a[0].length(); int min = Integer.MAX_VALUE; int max = 0; for (int i = 0; i < n; ++i) { String temp = a[i]; int sum = 0; for (int j = 0; j < n; ++j) { if (a[j].equals(temp)) continue; boolean flag = false; for (int di = 0; di < N; ++di) { if (rotate(a[j], di).equals(temp)) { flag = true; sum += di; break; } } if (!flag) { out.println(-1); return; } } min = Math.min(min, sum); } out.println(min); } public String rotate(String s, int n) { char[] temp = new char[s.length()]; int N = s.length(); for (int i = 0; i < N; ++i) { temp[(i + (N - n)) % N] = s.charAt(i); } return new String(temp); } } }
Java
["4\nxzzwo\nzwoxz\nzzwox\nxzzwo", "2\nmolzv\nlzvmo", "3\nkc\nkc\nkc", "3\naa\naa\nab"]
2 seconds
["5", "2", "0", "-1"]
NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
Java 8
standard input
[ "dp", "brute force", "strings" ]
a3a7515219ebb0154218ee3520e20d75
The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
1,300
Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.
standard output