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
sequencelengths
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
74faa990424767d756d0b7ffade6f100
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.*; public class arr{ static void func(int n){ if(n%2==0){ System.out.println(n/2); for(int i=1;i<=n/2;i++){ System.out.print(2+" "); } }else{ int notwos=(n/2)-1; System.out.println(n/2); for(int i=1;i<=notwos;i++){ System.out.print(2+" "); } System.out.print(3); } } public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n=scn.nextInt(); func(n); } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
0aaf7e1d6e9d51dd4bcb3c350b635dab
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.util.*; import static java.lang.System.out; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.StringTokenizer; public class Main { static final long mod = (int)1e9+7; static final long M = (int)1e9+7; 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 next() 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; } int[] readArray(int n) throws IOException { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } 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 int digitSum(int n) { int sum =0; while(n > 0) { int last = n%10; sum+=last; n/=10; } return sum; } public static boolean isPrime(int n) { for(int i = 2;i*i<=n;i++) { if(n%i == 0) { return false; } } return true; } public static int gcd(int a, int b) { if(b == 0) return a; else return gcd(b,a%b); } public static int[] computePrefix(int arr[], int n) { int[] prefix = new int[n]; prefix[0] = arr[0]; for(int i = 1;i<n;i++) { prefix[i] = prefix[i-1]+arr[i]; } return prefix; } public static int[] nextPermutation(int[] nums) { int i = nums.length - 2; while (i >= 0 && nums[i + 1] <= nums[i]) { i--; } if (i >= 0) { int j = nums.length - 1; while (j >= 0 && nums[j] <= nums[i]) { j--; } swap(nums, i, j); } reverse(nums, i + 1); return nums; } public static void reverse(int[] nums, int start) { int i = start, j = nums.length - 1; while (i < j) { swap(nums, i, j); i++; j--; } } public static void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } public static ArrayList<Integer> loopy(int[] arr) { ArrayList<Integer> temp = new ArrayList<>(); int n = arr.length; for(int i = 0;i<n;i++) { for(int j = 0;j<n;j++) { temp.add(arr[i]+arr[j]); i++; } } return temp; } public static void main(String[] args) throws IOException { Reader sc=new Reader(); int n = sc.nextInt(); System.out.println(n/2); if(n%2 == 0) { for(int i = 0;i<n/2;i++) { System.out.print(2+" "); } } else { for(int i = 0;i<n/2-1;i++) { System.out.print(2+" "); } System.out.print(3+" "); } System.out.println(); } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
afdefd3574ba76566ed25ffc28143fe0
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader in = new FastReader(); // PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int num = in.nextInt(); if (num % 2 == 0) { System.out.println(num / 2); for (int i = 0; i < num / 2; i++) { System.out.print(2 + " "); } } else { System.out.println(num / 2); for (int i = 0; i < (num / 2) - 1; i++) { System.out.print(2 + " "); } System.out.println(3); } } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
4c46ab8c832af475f9e769723447c6a0
train_000.jsonl
1482165300
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.
256 megabytes
import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(in.readLine()); out.println(n / 2); out.print((n % 2 == 0) ? '2' : '3'); for (int i = 0; i < n / 2 - 1; i++) { out.print(" 2"); } out.println(); out.close(); } }
Java
["5", "6"]
1 second
["2\n2 3", "3\n2 2 2"]
null
Java 11
standard input
[ "implementation", "number theory", "greedy", "math" ]
98fd00d3c83d4b3f0511d8afa6fdb27b
The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).
800
The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
standard output
PASSED
ae2961a5955dd4df747511c7d788a841
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { FastReader reader = new FastReader(); PrintWriter writer = new PrintWriter(System.out); int n = reader.nextInt(); int[] count = new int[n]; boolean ans = true; for (int i=1; i<n; i++) { int x = reader.nextInt(); int y = reader.nextInt(); if (y<n) ans = false; count[x]++; } int cur=0; for (int i=0; i<n; i++) { cur += count[i]; if (cur > i) ans = false; } if (!ans) writer.print("NO"); else { writer.println("YES"); TreeSet<Integer> set = new TreeSet<Integer>(); int last = -1; for (int i=1; i<n; i++) set.add(i); for (int i=1; i<n; i++) { if (count[i] > 0) { set.remove(i); if (last != -1) writer.println(last + " " + i); last = i; count[i]--; } while (count[i] > 0) { int got = set.first(); writer.println(got + " " + last); set.remove(got); last = got; count[i]--; } } writer.println(n + " " + last); } writer.close(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
57479d047a49e9f119d9ff305c0091ab
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.*; import java.util.*; /** * Copyright © 2018 Chris. All rights reserved. * * @author Chris * 2018/7/9 15:33 * @see format */ public class E { private static BufferedReader br; private static StreamTokenizer st; private static PrintWriter pw; private static void solve() throws IOException { int n = nextInt(); int cnt[] = new int[1001]; for (int i = 1; i < n; i++) { int a = nextInt(); int b = nextInt(); if (a < b) { a ^= b; b ^= a; a ^= b; } if (a != n || a == b) { pw.print("NO"); return; } cnt[b]++; } Set<Integer> set = new HashSet<>(); Set<int[]> pair = new HashSet<>(); for (int i = 1; i < n; i++) { if (cnt[i] == 0) { set.add(i); continue; } if (cnt[i] - 1 > set.size()) { pw.print("NO"); return; } int pre = i; Iterator<Integer> it = null; for (int j = 1; j < cnt[i]; j++) { if (null == it) { it = set.iterator(); } int next = it.next(); it.remove(); pair.add(new int[]{pre, next}); pre = next; } pair.add(new int[]{pre, n}); } if (set.size() > 0) { pw.print("NO"); return; } pw.println("YES"); Iterator<int[]> it = pair.iterator(); while (it.hasNext()) { int p[] = it.next(); pw.println(p[0] + " " + p[1]); } } public static void main(String args[]) throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if (!oj) { System.setIn(new FileInputStream("in.txt")); // System.setOut(new PrintStream("out.txt")); } br = new BufferedReader(new InputStreamReader(System.in)); st = new StreamTokenizer(br); pw = new PrintWriter(new OutputStreamWriter(System.out)); st.ordinaryChar('\''); //指定单引号、双引号和注释符号是普通字符 st.ordinaryChar('\"'); st.ordinaryChar('/'); long t = System.currentTimeMillis(); solve(); if (!oj) { pw.println("[" + (System.currentTimeMillis() - t) + "ms]"); } pw.flush(); } private static int nextInt() throws IOException { st.nextToken(); return (int) st.nval; } private static long nextLong() throws IOException { st.nextToken(); return (long) st.nval; } private static double nextDouble() throws IOException { st.nextToken(); return st.nval; } private static String[] nextSS(String reg) throws IOException { return br.readLine().split(reg); } private static String nextLine() throws IOException { return br.readLine(); } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
c18d70b117e287be1000ea1bbfddd43e
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
//package sept; import java.io.*; import java.util.*; public class CodeAgon { InputStream is; PrintWriter out; String INPUT = ""; //boolean debug=true; boolean debug=false; void solve() { int n=ni(); int[] a=new int[n-1]; for(int i=0;i<n-1;i++) { int u=ni(),v=ni(); if(v!=n) { out.println("NO"); return; } a[i]=u; } Arrays.sort(a); int l=0; int[] vis=new int[n+1]; int curr=1; ArrayList<Pair> ans=new ArrayList<>(); while(l<n-1) { int r=l+1; while(r<n-1 && a[l]==a[r])r++; int next=n; while(l<r-1) { while(vis[curr]==1)curr++; ans.add(new Pair(curr,next)); next=curr; vis[curr]=1; l++; } if(vis[a[l]]==1) { out.println("NO"); return; } ans.add(new Pair(next,a[l])); vis[a[l]]=1; l++; } out.println("YES"); for(Pair p:ans) { out.println(p.a+" "+p.b); } out.println(); } static int[][] packD(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) p[f]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) { g[from[i]][--p[from[i]]] = to[i]; } return g; } static class Pair { int a,b; public Pair(int a,int b) { this.a=a; this.b=b; } } static long lcm(int a,int b) { long val=a; val*=b; return (val/gcd(a,b)); } static long gcd(long a,long b) { if(a==0)return b; return gcd(b%a,a); } static int pow(int a, int b, int p) { long ans = 1, base = a; while (b!=0) { if ((b & 1)!=0) { ans *= base; ans%= p; } base *= base; base%= p; b >>= 1; } return (int)ans; } static int inv(int x, int p) { return pow(x, p - 2, p); } void run() throws Exception { if(!debug)oj=true; is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception {new CodeAgon().run();} private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
c08e419454a9cc0c55b223da0b58360b
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
/* Author: Ronak Agarwal, reader part not written by me*/ import java.io.* ; import java.util.* ; import static java.lang.Math.min ; import static java.lang.Math.max ; import static java.lang.Math.abs ; import static java.lang.Math.log ; import static java.lang.Math.pow ; import static java.lang.Math.sqrt ; /* Thread is created here to increase the stack size of the java code so that recursive dfs can be performed */ public class Codeshefcode{ public static void main(String[] args) throws IOException{ new Thread(null,new Runnable(){ public void run(){ exec_Code() ;} },"Solver",1l<<27).start() ; } static void exec_Code(){ try{ Solver Machine = new Solver() ; Machine.Solve() ; Machine.Finish() ;} catch(Exception e){ e.printStackTrace() ; print_and_exit() ;} catch(Error e){ e.printStackTrace() ; print_and_exit() ; } } static void print_and_exit(){ System.out.flush() ; System.exit(-1) ;} } /* Implementation of the Reader class */ class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar,numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is;} public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();} if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine(){ int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString() ; } public String s(){ 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 l(){ 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 i(){ 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 void readL(long arr[],int l,int r){ for(int i=l ; i<=r ; i++) arr[i] = l(); } public void readI(int arr[],int l,int r){ for(int i=l ; i<=r ; i++) arr[i] = i(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } /* All the useful functions,constants,renamings are here*/ class Template{ /* Constants Section */ final int INT_MIN = Integer.MIN_VALUE ; final int INT_MAX = Integer.MAX_VALUE ; final long LONG_MIN = Long.MIN_VALUE ; final long LONG_MAX = Long.MAX_VALUE ; static long MOD = 1000000007 ; static Reader ip = new Reader() ; static PrintWriter op = new PrintWriter(System.out) ; /* Methods for writing */ static void p(Object o){ op.print(o) ; } static void pln(Object o){ op.println(o) ;} static void Finish(){ op.flush(); op.close(); } /* Implementation of operations modulo MOD */ static long inv(long a){ return powM(a,MOD-2) ; } static long m(long a,long b){ return (a*b)%MOD ; } static long d(long a,long b){ return (a*inv(b))%MOD ; } static long powM(long x,long n){ if(n<0) return powM(inv(x),-n) ; long y=1 ; for( ; n!=0 ; x=(x*x)%MOD , n/=2) if((n&1)==1) y = (y*x)%MOD ; return y ; } /* Renaming of some generic utility classes */ final static class mylist extends ArrayList<pair>{} final static class myset extends TreeSet<pair>{} final static class mystack extends Stack<Integer>{} final static class mymap extends TreeMap<Long,Integer>{} } /* Implementation of the pair class, useful for every other problem */ class pair implements Comparable<pair>{ int x ; int y ; pair(int _x,int _y){ x=_x ; y=_y ;} public int compareTo(pair p){ return (this.x<p.x ? -1 : (this.x>p.x ? 1 : (this.y<p.y ? -1 : (this.y>p.y ? 1 : 0)))) ; } } /* Main code starts here */ class Solver extends Template{ long gcd(long a,long b){ if(b==0) return a; return gcd(b,a%b); } public void Solve() throws IOException{ int n = ip.i(); pair arr[] = new pair[n]; for(int i=1 ; i<n ; i++) arr[i] = new pair(ip.i(),ip.i()); Arrays.sort(arr,1,n); for(int i=1 ; i<n ; i++) if(arr[i].y!=n){ pln("NO"); return; } mylist ls = new mylist(); int frq[] = new int[n+1]; for(int i=1 ; i<n ; i++) frq[arr[i].x]++; int ptr=(n-1); while(ptr!=0 && frq[ptr]!=0) ptr--; for(int i=(n-1) ; i>=1 ; i--){ if(frq[i]!=0){ if(ptr>i){ pln("NO"); return; } int u = n; for(int j=1 ; j<frq[i] ; j++){ if(ptr==0){ pln("NO"); return; } int v = ptr; ls.add(new pair(u,v)); ptr--; while(ptr!=0 && frq[ptr]!=0) ptr--; u = v; } ls.add(new pair(u,i)); } } pln("YES"); for(pair p : ls) pln(p.x+" "+p.y); } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
4710d6cbdbb5c3ab4d8e82963c480ffb
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws FileNotFoundException { ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out)); // String fileName = "C-small-attempt0"; // ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".in"), new PrintWriter(new File("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".out"))); new Main(io).solve(); // new Main(io).solveLocal(); io.close(); } ConsoleIO io; Main(ConsoleIO io) { this.io = io; } ConsoleIO opt; Main(ConsoleIO io, ConsoleIO opt) { this.io = io; this.opt = opt; } List<List<Integer>> gr = new ArrayList<>(); long MOD = 1_000_000_007; public void solve() { int n = io.ri(); int[] count = new int[n+1]; for(int i = 1;i<n;i++){ int x = io.ri(); int y = io.ri(); if(y!=n){ io.writeLine("NO"); return; } count[x]++; } Stack<Integer> stack = new Stack<>(); for(int i = 1;i<n;i++)if(count[i]== 0){ stack.add(i); } int prev = n; StringBuilder sb = new StringBuilder(); sb.append("YES"); for(int i = n-1;i>0;i--)if(count[i]>0){ int t = count[i]; while(t>1){ if(stack.size()==0 || stack.peek() > i){ io.writeLine("NO"); return; } int v = stack.pop(); sb.append(System.lineSeparator()); sb.append(prev + " " + v); prev = v; t--; } sb.append(System.lineSeparator()); sb.append(prev + " " + i); prev = i; } io.writeLine(sb.toString()); } } class ConsoleIO { BufferedReader br; PrintWriter out; public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;} public void flush(){this.out.flush();} public void close(){this.out.close();} public void writeLine(String s) {this.out.println(s);} public void writeInt(int a) {this.out.print(a);this.out.print(' ');} public void writeWord(String s){ this.out.print(s); } public void writeIntArray(int[] a, int k, String separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k; i++) { if (i > 0) sb.append(separator); sb.append(a[i]); } this.writeLine(sb.toString()); } public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }} public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}} public long[] readLongArray() { String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length]; for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]); return r; } public int[] readIntArray() { String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length]; for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]); return r; } public int[] readIntArray(int n) { int[] res = new int[n]; char[] all = this.readLine().toCharArray(); int cur = 0;boolean have = false; int k = 0; boolean neg = false; for(int i = 0;i<all.length;i++){ if(all[i]>='0' && all[i]<='9'){ cur = cur*10+all[i]-'0'; have = true; }else if(all[i]=='-') { neg = true; } else if(have){ res[k++] = neg?-cur:cur; cur = 0; have = false; neg = false; } } if(have)res[k++] = neg?-cur:cur; return res; } public int ri() { try { int r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public long readLong() { try { long r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public String readWord() { try { boolean start = false; StringBuilder sb = new StringBuilder(); while (true) { int c = br.read(); if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') { sb.append((char)c); start = true; } else if (start || c == -1) return sb.toString(); } } catch (Exception ex) { return ""; } } public char readSymbol() { try { while (true) { int c = br.read(); if (c != ' ' && c != '\r' && c != '\n' && c != '\t') { return (char) c; } } } catch (Exception ex) { return 0; } } //public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }} } class Pair { public Pair(int a, int b) {this.a = a;this.b = b;} public int a; public int b; } class PairLL { public PairLL(long a, long b) {this.a = a;this.b = b;} public long a; public long b; } class Triple { public Triple(int a, int b, int c) {this.a = a;this.b = b;this.c = c;} public int a; public int b; public int c; }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
359b8527199d2677fd60c29ec474e265
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.*; import java.util.*; public class tr1 { static PrintWriter out; static StringBuilder sb; static int inf = (int) 1e9; static long mod = (long) 998244353; static int[] si; static ArrayList<Integer> primes; static HashSet<Integer> pr; static int n, k, m; static int[] in; static HashMap<Integer, Integer> factors; static HashSet<Integer> f; static int[] fac, a, b; static int[] l, r; static int[][] memo; static int[] numc; static ArrayList<Integer>[] ad; static HashMap<Integer, Integer> hm; static pair[] ed; static TreeSet<Integer>[] np; static TreeMap<pair, Integer> tm; static int[] le, re; static char[] h; static pair[] mm; static boolean[] vis; static int y; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int n = sc.nextInt(); boolean f = true; TreeSet<Integer> ts = new TreeSet<>(); for (int i = 1; i < n - 1; i++) ts.add(i); pair[] a = new pair[n]; int c = 0; int[] cnt = new int[n]; for (int i = 0; i < n - 1; i++) { a[i] = new pair(sc.nextInt(), sc.nextInt()); if (a[i].node == n && a[i].level == n - 1) c++; else if (a[i].node != n) f = false; else { if (ts.contains(a[i].level)) ts.remove(a[i].level); } cnt[a[i].level-1]++; } if (!f || (f && c == 0)) { out.print("NO"); out.flush(); return; } f = true; Queue<pair> q = new LinkedList(); for (int i = n-2; i >=0; i--) { if(cnt[i]==0) continue; int l=i+1; if(cnt[i]>i+1) f=false; while(cnt[i]>1) { if(ts.isEmpty()) break; if(ts.floor(l)==null) break; int x=ts.floor(l); ts.remove(x); q.add(new pair(l, x)); if(x>i+1) f=false; l=x; cnt[i]--; } cnt[i]--; q.add(new pair(n, l)); if(cnt[i]!=0) f=false; } if(!f) { System.out.println("NO"); return; } out.println("YES"); while (!q.isEmpty()) out.println(q.poll()); out.flush(); } static class pair implements Comparable<pair> { int node; int level; pair(int f, int t) { node = t; level = f; } public String toString() { return node + " " + level; } @Override public int compareTo(pair o) { return level - o.level; } } static class pair1 implements Comparable<pair1> { int x; int y; int z; pair1(int f, int t, int u) { x = f; y = t; z = u; // num = n; } public String toString() { return x + " " + y; } @Override public int compareTo(pair1 o) { if (x == o.x) return y - o.y; return x - o.x; } } static public class FenwickTree { // one-based DS int n; int[] ft; FenwickTree(int size) { n = size; ft = new int[n + 1]; // for(int i=1;i<=n;i++) // ft[i]=i; } int rsq(int b) // O(log n) { int sum = 0; while (b > 0) { sum += ft[b]; b -= b & -b; } // min? return sum; } int rsq(int a, int b) { return rsq(b) - rsq(a - 1); } void point_update(int k, int val) // O(log n), update = increment { while (k <= n) { // System.out.println(k+" "+val); ft[k] += val; k += k & -k; } // min? } int point_query(int idx) // c * O(log n), c < 1 { int sum = ft[idx]; if (idx > 0) { int z = idx ^ (idx & -idx); --idx; while (idx != z) { // System.out.println("oo"); sum -= ft[idx]; idx ^= idx & -idx; } } return sum; } void scale(int c) { for (int i = 1; i <= n; ++i) ft[i] *= c; } int findIndex(int cumFreq) { int msk = n; while ((msk & (msk - 1)) != 0) msk ^= msk & -msk; // msk will contain the MSB of n int idx = 0; while (msk != 0) { int tIdx = idx + msk; if (tIdx <= n && cumFreq >= ft[tIdx]) { idx = tIdx; cumFreq -= ft[tIdx]; } msk >>= 1; } if (cumFreq != 0) return -1; return idx; } } static public class SegmentTree { // 1-based DS, OOP int N; // the number of elements in the array as a power of 2 (i.e. after padding) long[] array, sTree, lazy; SegmentTree(long[] in) { array = in; N = in.length - 1; sTree = new long[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new long[N << 1]; build(1, 1, N); } void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] += val; while (index > 1) { index >>= 1; sTree[index] = sTree[index << 1] + sTree[index << 1 | 1]; } } void update_range(int i, int j, long val) // O(log n) { update_range(1, 1, N, i, j, val); } void update_range(int node, int b, int e, int i, int j, long val) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] += (e - b + 1) * val; lazy[node] += val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node << 1, b, mid, i, j, val); update_range(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void propagate(int node, int b, int mid, int e) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; sTree[node << 1] += (mid - b + 1) * lazy[node]; sTree[node << 1 | 1] += (e - mid) * lazy[node]; lazy[node] = 0; } long query(int i, int j) { return query(1, 1, N, i, j); } long query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return 0; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; propagate(node, b, mid, e); long q1 = query(node << 1, b, mid, i, j); long q2 = query(node << 1 | 1, mid + 1, e, i, j); return q1 + q2; } } static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public int[] merge(int[] d, int st, int e) { if (st > e) return null; if (e == st) { int[] ans = { d[e] }; return ans; } int mid = (st + e) / 2; int[] ans = new int[e - st + 1]; int[] ll = merge(d, st, mid); int[] rr = merge(d, mid + 1, e); if (ll == null) return rr; if (rr == null) return ll; int iver = 0; int idxl = 0; int idxr = 0; for (int i = st; i <= e; i++) { if (ll[idxl] < rr[idxr]) { } } return ans; } public static class pair2 implements Comparable<pair2> { int a; int idx; pair2(int a, int i) { this.a = a; idx = i; } public String toString() { return a + " " + idx; } @Override public int compareTo(pair2 o) { // TODO Auto-generated method stub return idx - o.idx; } } static long inver(long x) { int a = (int) x; long e = (mod - 2); long res = 1; while (e > 0) { if ((e & 1) == 1) { // System.out.println(res*a); res = (int) ((1l * res * a) % mod); } a = (int) ((1l * a * a) % mod); e >>= 1; } // out.println(res+" "+x); return res % mod; } static int atMostSum(int arr[], int n, int k) { int sum = 0; int cnt = 0, maxcnt = 0; for (int i = 0; i < n; i++) { // If adding current element doesn't // cross limit add it to current window if ((sum + arr[i]) <= k) { sum += arr[i]; cnt++; } // Else, remove first element of current // window and add the current element else if (sum != 0) { sum = sum - arr[i - cnt] + arr[i]; } // keep track of max length. maxcnt = Math.max(cnt, maxcnt); } return maxcnt; } public static int[] longestSubarray(int[] inp) { // array containing prefix sums up to a certain index i int[] p = new int[inp.length]; p[0] = inp[0]; for (int i = 1; i < inp.length; i++) { p[i] = p[i - 1] + inp[i]; } // array Q from the description below int[] q = new int[inp.length]; q[inp.length - 1] = p[inp.length - 1]; for (int i = inp.length - 2; i >= 0; i--) { q[i] = Math.max(q[i + 1], p[i]); } int a = 0; int b = 0; int maxLen = 0; int curr; int[] res = new int[] { -1, -1 }; while (b < inp.length) { curr = a > 0 ? q[b] - p[a - 1] : q[b]; if (curr >= 0) { if (b - a > maxLen) { maxLen = b - a; res = new int[] { a, b }; } b++; } else { a++; } } return res; } static void factor(int n) { if (si[n] == n) { f.add(n); return; } f.add(si[n]); factor(n / si[n]); } static void seive() { si = new int[100001]; primes = new ArrayList<>(); int N = 100001; si[1] = 1; for (int i = 2; i < N; i++) { if (si[i] == 0) { si[i] = i; primes.add(i); } for (int j = 0; j < primes.size() && primes.get(j) <= si[i] && (i * primes.get(j)) < N; j++) si[primes.get(j) * i] = primes.get(j); } } static class unionfind { int[] p; int[] size; int jum; unionfind(int n) { p = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { p[i] = i; } jum = n; Arrays.fill(size, 1); } int findSet(int v) { if (v == p[v]) return v; return p[v] = findSet(p[v]); } boolean sameSet(int a, int b) { a = findSet(a); b = findSet(b); if (a == b) return true; return false; } int max() { int max = 0; for (int i = 0; i < size.length; i++) if (size[i] > max) max = size[i]; return max; } void combine(int a, int b) { a = findSet(a); b = findSet(b); if (a == b) return; jum--; if (size[a] > size[b]) { p[b] = a; size[a] += size[b]; } else { p[a] = b; size[b] += size[a]; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
9e049ee67b483604387f9bc1ff0ff8a4
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
//package com.company; import java.io.*; import java.util.*; public class Main { static long TIME_START, TIME_END; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileInputStream("Test.in")); PrintWriter pw = new PrintWriter(System.out); // PrintWriter pw = new PrintWriter(new FileOutputStream("Test.in")); // PrintWriter pw = new PrintWriter(new FileOutputStream("Test.out")); Runtime runtime = Runtime.getRuntime(); long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory(); TIME_START = System.currentTimeMillis(); Task t = new Task(); t.solve(sc, pw); TIME_END = System.currentTimeMillis(); long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory(); pw.close(); System.out.println("Memory increased:" + (usedMemoryAfter - usedMemoryBefore) / 1000000); System.out.println("Time used: " + (TIME_END - TIME_START) + "."); } public static class Task { public void solve(Scanner sc, PrintWriter pw) throws IOException { int n = sc.nextInt(); int[] deg = new int[n]; for (int i = 0; i < n - 1; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt(); if (b != n) { pw.println("NO"); return; } deg[a]++; } List<Integer>[] attached = new List[n]; for (int i = 0; i < n; i++) { attached[i] = new ArrayList<>(); } boolean[] use = new boolean[n]; for (int i = 0; i < n; i++) { if (deg[i] > 0) { deg[i]--; use[i] = true; } } int innerIdx = n - 2; for (int i = n - 2; i >= 0; i--) { if (deg[i] > 0) { while (innerIdx >= 0 && deg[i] > 0) { if (!use[innerIdx]) { deg[i] -= 1; if (innerIdx > i) { pw.println("NO"); return; } attached[i].add(innerIdx); } innerIdx--; } } } pw.println("YES"); for (int i = 0; i < n; i++) { if (use[i]) { int[] list = new int[attached[i].size() + 2]; list[0] = n; for (int j = 0; j < attached[i].size(); j++) { list[j + 1] = attached[i].get(j) + 1; } list[attached[i].size() + 1] = i + 1; for (int j = 0; j < list.length - 1; j++) { pw.println(list[j] + " " + list[j + 1]); } } } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(s); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
16b652edd52beb708332c389d85c1797
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ static ArrayList[] a = new ArrayList[200001]; public void solve () throws IOException { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(); int cnt[] = new int [n + 1]; for(int i = 0 ; i < n - 1 ; i ++) { int x = in.nextInt(); int y = in.nextInt(); cnt[x] ++; cnt[y] ++; } if(cnt[n] != n - 1) { pw.print("NO"); pw.flush(); pw.close(); return ; } boolean visited[] = new boolean [n + 1]; int root = n; visited[n] = true; Vector<pair>ans = new Vector<>(); for(int i = n - 1 ; i > 0 ; i--) { if(cnt[i] != 0) { visited[i] = true; Vector<Integer>v = new Vector<>(); for(int j = n ; j > 0 && v.size() < cnt[i] - 1 ; j--) { if(cnt[j] == 0 && !visited[j]) { v.add(j); } } v.add(i); if(v.get(0) > i || v.size() != cnt[i] ) { pw.print("NO"); pw.flush(); pw.close(); return ; } for(int j = 0 ; j < v.size() ; j++) { ans.add(new pair(root , v.get(j))); visited[v.get(j)] = true; root = v.get(j); } } } for(int i = 1 ; i <= n ; i++) { if(!visited[i]) { pw.print("NO"); pw.flush(); pw.close(); return ; } } pw.println("YES"); for(int i = 0 ; i < ans.size() ; i++) { pw.println(ans.get(i)); } pw.flush(); pw.close(); } public static void main(String[] args) throws Exception { new Thread(null,new Runnable() { public void run() { try { new Main().solve(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } },"1",1<<26).start(); } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public void extended(int a,int b) { if(b==0) { d=a; p=1; q=0; } else { extended(b,a%b); int temp=p; p=q; q=temp-(a/b)*q; } } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long[] shuffle(long[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; long temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static HashSet<Integer> primeFactorization(int n) { HashSet<Integer> a =new HashSet<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static long GCD(long n,long m) { if(m==0) return n; else return GCD(m,n%m); } public static long LCM (long a,long b) { return ((a*b)/(GCD(a,b))); } static class pair implements Comparable<pair> { Integer y , x ; pair(int l,Integer y) { this.x=l; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*3 + new Long(y).hashCode(); } } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x%M*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result%M * x%M)%M; x=(x%M * x%M)%M; n=n/2; } return result; } public static long modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } static class Segment{ int seg[]; int a[]; int lazy[]; Segment (int n,int b[]){ seg=new int[4*n]; lazy=new int[4*n]; a=new int[b.length]; a=b.clone(); } public void build(int node,int start,int end) { if(start==end) { seg[node]=a[start]; return ; } int mid=(start+end)/2; build(2*node+1,start,mid); build(2*node+2,mid+1,end); seg[node]=seg[2*node+1]+seg[2*node+2]; } public void update(int node,int start,int end,int id,int val) { if(start==end) { seg[node]=a[start]=val; return; } int mid=(start+end)/2; if(id>=start && id<=mid) { update(2*node+1,start,mid,id,val); } else update(2*node+2,mid+1,end,id,val); seg[node]=seg[2*node+1]+seg[2*node+2]; } public int query(int node,int start,int end,int l,int r) { if(l>end || r<start) return 0; if(start>=l && end<=r) return seg[node]; int mid=(start+end)/2; return (query(2*node+1,start,mid,l,r)+query(2*node+2,mid+1,end,l,r)); } public void updateRange(int node,int start,int end,int l,int r,int val) { if(lazy[node]!=0) { seg[node] += lazy[node]; if(start!=end) { lazy[2*node+1]+=lazy[node]; lazy[2*node+2]+=lazy[node]; } lazy[node]=0; } if(l>end || r<start) return ; if(start>=l && end<=r) { seg[node] += val; if(start!=end) { lazy[2*node+1]+=val; lazy[2*node+2]+=val; } lazy[node]=0; return ; } int mid=(start+end)/2; updateRange(2*node+1,start,mid,l,r,val); updateRange(2*node+2,mid+1,end,l,r,val); seg[node]=seg[2*node+1]+seg[2*node+2]; } public int queryRange(int node,int start,int end,int l,int r) { if(l>end || r<start) return 0; if(lazy[node]!=0) { seg[node] += lazy[node]; if(start!=end) { lazy[2*node+1]+=lazy[node]; lazy[2*node+2]+=lazy[node]; } lazy[node]=0; } if(start>=l && end<=r) return seg[node]; int mid=(start+end)/2; return (queryRange(2*node+1,start,mid,l,r)+queryRange(2*node+2,mid+1,end,l,r)); } } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
1af410b6f0cdb0f374a7fd161bb31637
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.*; import java.util.*; import java.util.LinkedList; import java.math.*; import java.lang.*; import java.util.PriorityQueue; import static java.lang.Math.*; @SuppressWarnings("unchecked") public class Solution implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long min(long a,long b) { if(a>b) { return b; } return a; } public static int min(int a,int b) { if(a>b) { return b; } return a; } public static long max(long a,long b) { if(a>b) { return a; } return b; } public static int max(int a,int b) { if(a>b) { return a; } return b; } static class pair implements Comparable<pair> { int x; int y; pair(int x,int y) { this.x = x; this.y = y; } public int compareTo(pair p) { if(this.x>p.x) { return -1; } else if(this.x<p.x) { return 1; } else { return 0; } } } public static long gcd(long a,long b) { if(a==0) return b; if(b==0) return a; while((a%=b)!=0&&(b%=a)!=0); return a^b; } public static int mod(int a) { if(a>0) return a; return -a; } static int mod = (int)1e9+7; public static long expo(long exp,long pow) { long ans = 1; while(pow!=0) { if((pow&1)==1) { ans = (ans*exp)%mod; } exp = (exp*exp)%mod; pow = pow>>1; } return ans; } static int[] a; static int max = (int)1e6; public static long fact(int num) { if(num==0) { return 1; } return (fact(num-1)*num)%mod; } static boolean[] sieve; static ArrayList<Integer> prime; public static void sieve() { sieve = new boolean[max+1]; prime = new ArrayList<>(); for(int i=2;i<=max;i++) { if(!sieve[i]) { for(int j=i*2;j<=max;j+=i) { sieve[j] = true; } } } for(int i=2;i<=max;i++) { if(!sieve[i]) { prime.add(i); } } } public static long lcm(long a,long b) { return a*b/gcd(a,b); } public static int bsearch(long[] a,int l,int r,int h,long sub) { while(r>l){ int mid = (r+l+1)/2; if(a[mid]-sub<=h) { l = mid; } else { r = mid-1; } } if(a[l]-sub<=h) { return l; } return -1; } public static void main(String args[]) throws Exception { new Thread(null, new Solution(),"Main",1<<26).start(); } public void run() { InputReader sc = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t1 = 1; while(t1-->0) { int n = sc.nextInt(); int[] mat = new int[n+1]; boolean[] visit = new boolean[n+1]; boolean[][] ans = new boolean[n+1][n+1]; boolean flag = true; for(int i=0;i<n-1;i++) { int a = sc.nextInt(); int b = sc.nextInt(); if(a!=n&&b!=n) { out.println("NO"); out.close(); return; } if(a==n) { mat[b]++; } else { mat[a]++; } } for(int i=1;i<n;i++) { if(mat[i]!=0) { ans[i][n] = true; visit[i] = true; mat[i]--; } } visit[n] = true; for(int i=1;i<n;i++) { if(mat[i]!=0) { int pre = i; for(int j=1;j<i;j++) { if(!visit[j]) { ans[pre][n] = false; ans[pre][j] = true; ans[j][n] = true; visit[j] = true; pre = j; mat[i]--; if(mat[i]==0) { break; } } } } if(mat[i]!=0) { flag = false; break; } } if(flag) { out.println("YES"); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(ans[i][j]) { out.println(i+" "+j); } } } } else { out.println("NO"); } } out.close(); } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
2bf736e5e2ca3623b584cfe60a90ca05
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; /** * Created by timur on 28.03.15. */ public class TaskE { boolean eof; BufferedReader br; StringTokenizer st; PrintWriter out; public static void main(String[] args) throws IOException { new TaskE().run(); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "-1"; } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { return br.readLine(); } void run() throws IOException { InputStream input = System.in; PrintStream output = System.out; try { File f = new File("a.in"); if (f.exists() && f.canRead()) { input = new FileInputStream(f); output = new PrintStream("a.out"); } } catch (Throwable e) { } br = new BufferedReader(new InputStreamReader(input)); out = new PrintWriter(output); solve(); br.close(); out.close(); } void solve() { int n = nextInt(); int[] a = new int[n], b = new int[n], cnt = new int[n]; int x, y, u , v; for (int i = 0; i < n - 1; i++) { x = nextInt() - 1; y = nextInt() - 1; a[i] = x; b[i] = y; cnt[x]++; cnt[y]++; if (x == y) { out.print("NO"); return; } } if (cnt[n - 1] < n - 1) { out.print("NO"); return; } for (int i = 0; i < n; i++) { if (cnt[i] > i + 1) { out.print("NO"); return; } } int cur = n - 2, ds = 0; int[] dist = new int[n]; int[][] paths = new int[n][]; Queue<Integer> pi = new ArrayDeque<>(); Queue<Integer> ipi = new ArrayDeque<>(); try { while (cur >= 0) { if (cnt[cur] == 0) { if (ds == 0) { out.print("NO"); return; } else { ds--; paths[pi.poll()][ipi.poll()] = cur; } } else { dist[cur] = cnt[cur]; ds += cnt[cur]; paths[cur] = new int[dist[cur]]; paths[cur][dist[cur] - 1] = cur + 1; for (int i = 0; i < dist[cur] - 1; i++) { pi.add(cur); ipi.add(i); } } cur--; } } catch (Exception e) { out.print("NO"); return; } out.println("YES"); for (int i = 0; i < n; i++) { if (paths[i] != null) { int l = i + 1; for (int j = 0; j < paths[i].length; j++) { out.println(l + " " + (paths[i][j] + 1)); l = paths[i][j] + 1; } } } } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
391caf07d686c55f11b98f16c165c58c
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.PriorityQueue; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author real */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int count[] = new int[n + 1]; for (int i = 0; i < n - 1; i++) { int a = in.nextInt(); int b = in.nextInt(); if (Math.max(a, b) != n || Math.min(a, b) == n) { out.print("NO"); return; } count[Math.min(a, b)]++; } int parent[] = new int[n + 1]; PriorityQueue<Integer> list = new PriorityQueue<>(); for (int i = 1; i < n; i++) { if (count[i] == 0) { list.add(i); } else { int par = n; while (count[i] != 1) { if (list.size() == 0) { out.print("NO"); return; } int temp = list.poll(); count[i]--; parent[temp] = par; par = temp; } parent[i] = par; } } if (list.size() != 0) { out.print("NO"); return; } out.println("YES"); for (int i = 1; i <= n - 1; i++) { out.println(i + " " + parent[i]); } } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar; private int snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { //*-*------clare------ //remeber while comparing 2 non primitive data type not to use == //remember Arrays.sort for primitive data has worst time case complexity of 0(n^2) bcoz it uses quick sort //again silly mistakes ,yr kb tk krta rhega ye mistakes //try to write simple codes ,break it into simple things // for test cases make sure println(); ;) //knowledge>rating /* public class Main implements Runnable{ public static void main(String[] args) { new Thread(null,new Main(),"Main",1<<26).start(); } public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC();//chenge the name of task solver.solve(1, in, out); out.close(); } */ 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
d7e56acf2907c533850da3321b8b4494
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
/** * BaZ :D */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static Reader scan; static PrintWriter pw; public static void main(String[] args) { new Thread(null,null,"BaZ",1<<25) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws IOException { scan = new Reader(); pw = new PrintWriter(System.out,true); StringBuilder sb = new StringBuilder(); int n = ni(); int freq[] = new int[n+1]; boolean maraya = false; for(int i=1;i<n;++i) { int a = ni(),b = ni(); if(a==n || b==n) { if(a==n && b==n) { maraya = true; } else if(a==n) { ++freq[b]; } else { ++freq[a]; } } else maraya = true; } if(maraya) { pl("NO"); } else { ArrayList<Integer> list = new ArrayList<>(); TreeSet<Integer> free = new TreeSet<>(); for(int i=1;i<n;++i) { if(freq[i]==0) { free.add(i); } else list.add(i); } ArrayList<Integer> yayy = new ArrayList<>(); for(int e:list) { yayy.add(e); int need = freq[e] - 1; for (int j = 0; j < need; ++j) { Integer x = free.pollFirst(); if (x == null || x > e) { maraya = true; break; } else yayy.add(x); } if (maraya) break; } yayy.add(n); if(maraya) { pl("NO"); } else { pl("YES"); for(int i=0;i<yayy.size()-1;++i) { pl(yayy.get(i)+" "+yayy.get(i+1)); } } } pw.flush(); pw.close(); } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String listName, List list) { pl(listName+" : "); for(Object o : list) p(o); pl(); } static void pa(String arrayName, Object[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(Object o : arr[i]) p(o); pl(); } } static void pa(String arrayName, int[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(int o : arr[i]) p(o); pl(); } } static void pa(String arrayName, long[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(long o : arr[i]) p(o); pl(); } } static void pa(String arrayName, char[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(char o : arr[i]) p(o); pl(); } } static void pa(String arrayName, double[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(double o : arr[i]) p(o); pl(); } } 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]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
bff3f1afbeb104194df0a564e3a62049
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.Set; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.util.ArrayList; import java.util.HashSet; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author prakharjain */ 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] u = new int[n - 1]; int[] v = new int[n - 1]; edge[] edges = new edge[n - 1]; for (int i = 0; i < n - 1; i++) { int a = in.nextInt(); int b = in.nextInt(); u[i] = a; v[i] = b; edges[i] = new edge(a, b); //c if (b != n) { out.println("NO"); return; } } Set<Integer> s = new HashSet<>(); for (int i = 0; i < n - 1; i++) { s.add(u[i]); s.add(v[i]); } if (!s.contains(n) || !s.contains(n - 1)) { out.println("NO"); return; } Arrays.sort(edges, (e1, e2) -> e2.u - e1.u); TreeSet<Integer> ds = new TreeSet<>((x, y) -> y - x); for (int i = 1; i <= n; i++) { ds.add(i); } for (int num : s) { ds.remove(num); } int dss = ds.size(); int ad = 0; for (int i = 1; i < n - 1; i++) { if (edges[i].u == edges[i - 1].u) { ad++; } } //conf if (ad != dss) { out.println("NO"); return; } ArrayList<edge> ans = new ArrayList<>(); int ll = n; int st = 0; for (int i = 1; i < n - 1; i++) { if (edges[i].u != edges[i - 1].u) { int tc = i - st - 1; int fu = edges[i - 1].u; int tv = ll; int p = fu; for (int j = 0; j < tc; j++) { int num = ds.first(); if (num > fu || num > tv) { out.println("NO"); return; } ds.remove(num); ans.add(new edge(p, num)); p = num; } ans.add(new edge(p, tv)); st = i; ll = fu; } } int tc = n - 1 - st - 1; int fu = edges[n - 2].u; int tv = ll; int p = fu; for (int j = 0; j < tc; j++) { int num = ds.first(); ds.remove(num); ans.add(new edge(p, num)); p = num; } ans.add(new edge(p, tv)); out.println("YES"); for (int i = 0; i < ans.size(); i++) { edge edge = ans.get(i); out.println(edge.u + " " + edge.v); } } class edge { int u; int v; public edge(int u, int v) { this.u = u; this.v = v; } } } 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 println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
7e95252d1892ae5775148416992a9809
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; //Solution Credits: Taranpreet Singh public class Main{ //SOLUTION BEGIN void solve(int TC) throws Exception{ int n = ni(); int[][] e = new int[n-1][]; boolean valid = true; for(int i = 0; i< n-1; i++){ e[i] = new int[]{ni(), ni()}; if(Math.max(e[i][0], e[i][1])!=n)valid = false; if(e[i][0]==e[i][1])valid = false; } Arrays.sort(e, (int[] i1, int[] i2) -> Integer.compare(Math.min(i1[0], i1[1]), Math.min(i2[0], i2[1]))); for(int i = 0; i< n-1; i++){ if(Math.min(e[i][0], e[i][1])<=i)valid = false; } if(valid){ pn("YES"); int prev = Math.min(e[0][0], e[0][1]); TreeSet<Integer> set = new TreeSet<>(); for(int i = 1; i<= n-1; i++)set.add(i); boolean[] used = new boolean[n+1]; used[prev] = true; for(int i = 1; i< n-1; i++){ int m = Math.min(e[i][0], e[i][1]); if(used[m]){ do{ m = set.pollFirst(); }while(used[m]); }used[m] = true; pn(prev+" " + m); prev = m; } pn(prev+" " + n); }else pn("NO"); } //SOLUTION ENDS long mod = (int)1e9+7, IINF = (long)3e18; final int MAX = (int)1e5+1, INF = (int)1e9, root = 3; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.141592653589793238462643383279502884197169399375105820974944, eps = 1e-8; static boolean multipleTC = false, memory = true; FastReader in;PrintWriter out; void run() throws Exception{ in = new FastReader(); out = new PrintWriter(System.out); int T = (multipleTC)?ni():1; // long ct = System.currentTimeMillis(); //Solution Credits: Taranpreet Singh for(int i = 1; i<= T; i++)solve(i); // pn(System.currentTimeMillis()-ct); out.flush(); out.close(); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n(){return in.next();} String nln(){return in.nextLine();} int ni(){return Integer.parseInt(in.next());} long nl(){return Long.parseLong(in.next());} double nd(){return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
4209583b679e29a9c63720eb3f02919e
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.*; public class A3 { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } static String reverse(String s){ return (new StringBuilder(s)).reverse().toString(); } static void sort(int ar[]){ int n=ar.length; ArrayList<Integer> a=new ArrayList<>(); for(int i=0;i<n;i++) a.add(ar[i]); Collections.sort(a); for(int i=0;i<n;i++) ar[i]=a.get(i); } public static void solve(InputReader sc, PrintWriter pw) { int i,j=0; int t=1; // int t=sc.nextInt(); u:while(t-->0){ int n=sc.nextInt(); int v[]=new int[n-1]; int f=0; for(i=0;i<n-1;i++){ int a=sc.nextInt(); int b=sc.nextInt(); if(a==n){ if(b==n) f=1; v[i]=b; } else if(b==n){ if(a==n) f=1; v[i]=a; } else f=1; } sort(v); if(f==1) pw.println("NO"); else{ int u[]=new int[n-1]; int h[]=new int[n+1]; u[0]=v[0]; h[v[0]]=1; int y=1; for(i=1;i<n-1;i++){ if(v[i]==v[i-1]){ for(;y<n;y++){ if(h[y]==0){ u[i]=y; if(y>=v[i]){ f=1; } h[y]=1; break; } } if(u[i]==0) f=1; } else{ u[i]=v[i]; h[u[i]]=1; } } if(f==1){ pw.println("NO"); // for(i=0;i<n-1;i++){ // pw.println(u[i]+" "+n); // } } else{ pw.println("YES"); for(i=0;i<n-1;i++){ pw.println(u[i]+" "+((i==n-2)?n:u[i+1])); } } } } } static class Pair implements Comparable<Pair>{ int a; int b; // int i; Pair(int a,int b){ this.a=a; this.b=b; // this.i=i; } public int compareTo(Pair p){ if(a!=p.a) return (a-p.a); return (b-p.b); } } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long fast_pow(long base,long n,long M){ if(n==0) return 1; if(n==1) return base%M; long halfn=fast_pow(base,n/2,M); if(n%2==0) return ( halfn * halfn ) % M; else return ( ( ( halfn * halfn ) % M ) * base ) % M; } static long modInverse(long n,long M){ return fast_pow(n,M-2,M); } 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
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
3878056eb12d9810f33a3107af6f9e26
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; /* spar5h */ //hm.get((long)0) != hm.get(0) public class cf5 implements Runnable{ static class pair { int i, j; pair(int i, int j) { this.i = i; this.j = j; } } static class comp implements Comparator<pair> { public int compare(pair x, pair y) { if(x.i < y.i) return -1; if(x.i > y.i) return 1; return 0; } } public void run() { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int t = 1; while(t-- > 0) { int n = s.nextInt(); ArrayList<pair> list = new ArrayList<pair>(); for(int i = 0; i < n - 1; i++) { int u = s.nextInt(), v = s.nextInt(); list.add(new pair(min(u, v), max(u, v))); } boolean res = true; for(int i = 0; i < n - 1; i++) if(list.get(i).j != n) res = false; if(!res) { w.println("NO"); continue; } Collections.sort(list, new comp()); int i = 0; int[] dead = new int[n + 1]; ArrayList<pair> edge = new ArrayList<pair>(); while(i < n - 1) { int key = list.get(i).i, count = 0; while(i < n - 1 && key == list.get(i).i) { count++; i++; } int prev = key; count--; dead[prev] = 1; for(int j = 1; j < key; j++) { if(count == 0) break; if(dead[j] == 0) { edge.add(new pair(prev, j)); dead[j] = 1; prev = j; count--; } } if(count > 0) { res = false; break; } edge.add(new pair(prev, n)); } if(res) { w.println("YES"); for(int j = 0; j < edge.size(); j++) w.println(edge.get(j).i + " " + edge.get(j).j); } else w.println("NO"); } w.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new cf5(),"cf5",1<<26).start(); } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
aab320efa7dd130548bb3caf551dc23e
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.*; import java.util.*; public class Task { public static void main(String[] args) throws Exception { new Task().go(); } PrintWriter out; Reader in; BufferedReader br; Task() throws IOException { try { //br = new BufferedReader( new FileReader("input.txt") ); //in = new Reader("input.txt"); in = new Reader("input.txt"); out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); } catch (Exception e) { //br = new BufferedReader( new InputStreamReader( System.in ) ); in = new Reader(); out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); } } void go() throws Exception { //int t = in.nextInt(); int t = 1; while (t > 0) { solve(); t--; } out.flush(); out.close(); } int inf = 2000000000; int mod = 1000000007; double eps = 0.000000001; int n; int m; ArrayList<Integer>[] g; int[] a; void solve() throws IOException { int n = in.nextInt(); int[] cnt = new int[n + 1]; for (int i = 0; i < n - 1; i++) { int x = in.nextInt(); int y = in.nextInt(); cnt[x]++; cnt[y]++; } boolean ok = cnt[n] == n - 1; int sum = 0; for (int i = 1; i < n; i++) { ok &= cnt[i] <= i - sum; sum += cnt[i]; } if (!ok) { out.println("NO"); return; } LinkedList<Integer> notUsed = new LinkedList<>(); ArrayList<Integer> ans = new ArrayList<>(); for (int i = 1; i < n; i++) { if (cnt[i] == 0) notUsed.add(i); else { ans.add(i); while (cnt[i] > 1) { ans.add(notUsed.poll()); cnt[i]--; } } } ans.add(n); out.println("YES"); for (int i = 0; i < n - 1; i++) { out.println(ans.get(i) + " " + ans.get(i + 1)); } } class Pair implements Comparable<Pair>{ int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (a != p.a) return Integer.compare(a, p.a); else return Integer.compare(b, p.b); } } class Item { int a; int b; int c; Item(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } } static class InputReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public InputReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public InputReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
3a13f6fd3c1b8aa40e615d128a0f39da
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static int MOD = 1000000007; // After writing solution, quick scan for: // array out of bounds // special cases e.g. n=1? // // Big numbers arithmetic bugs: // int overflow // sorting, or taking max, after MOD void solve() throws IOException { int n = ri(); int[][] ab = new int[n][]; int[] counts = new int[n]; for (int i = 0; i < n-1; i++) { ab[i] = ril(2); ab[i][0]--; ab[i][1]--; if (ab[i][0] > ab[i][1]) { int temp = ab[i][0]; ab[i][0] = ab[i][1]; ab[i][1] = temp; } counts[ab[i][0]]++; counts[ab[i][1]]++; } if (counts[n-1] != n-1) { pw.println("NO"); return; } List<int[]> ans = new ArrayList<>(); boolean[] ok = new boolean[n]; for (int i = n-2; i >= 0; i--) { if (counts[i] == 0) { if (!ok[i]) { pw.println("NO"); return; } } else { int extra = counts[i]-1; List<Integer> chain = new ArrayList<>(); for (int j = i-1; extra > 0 && j >= 0; j--) { if (ok[j] || counts[j] > 0) continue; ok[j] = true; extra--; chain.add(j); } chain.add(i); ans.add(new int[]{n-1, chain.get(0)}); for (int j = 0; j < chain.size()-1; j++) ans.add(new int[]{chain.get(j), chain.get(j+1)}); } } pw.println("YES"); for (int[] e : ans) pw.println((e[0]+1) + " " + (e[1]+1)); } // Template code below BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException { Main m = new Main(); m.solve(); m.close(); } void close() throws IOException { pw.flush(); pw.close(); br.close(); } int ri() throws IOException { return Integer.parseInt(br.readLine().trim()); } long rl() throws IOException { return Long.parseLong(br.readLine().trim()); } int[] ril(int n) throws IOException { int[] nums = new int[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } long[] rll(int n) throws IOException { long[] nums = new long[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); long x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } int[] rkil() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return ril(x); } long[] rkll() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return rll(x); } char[] rs() throws IOException { return br.readLine().toCharArray(); } void sort(int[] A) { Random r = new Random(); for (int i = A.length-1; i > 0; i--) { int j = r.nextInt(i+1); int temp = A[i]; A[i] = A[j]; A[j] = temp; } Arrays.sort(A); } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
a93025bff045b686dcee1555a92cd155
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.util.TreeSet; import java.util.ArrayList; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); ETreeReconstruction solver = new ETreeReconstruction(); solver.solve(1, in, out); out.close(); } static class ETreeReconstruction { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int[] from = new int[n - 1]; int[] to = new int[n - 1]; boolean flag = true; int[] cc = new int[n + 1]; for (int i = 0; i < n - 1; i++) { from[i] = in.scanInt(); to[i] = in.scanInt(); if (to[i] != n) flag = false; cc[from[i]]++; } TreeSet<Integer> set = new TreeSet<>(); for (int i = 1; i < n; i++) if (cc[i] == 0) set.add(i); ArrayList<pair> arrayList = new ArrayList<pair>(); for (int i = n - 1; i >= 1; i--) { if (cc[i] > 0) { int last = i; while (cc[i] > 1 && set.size() > 0) { int highest = set.last(); if (highest > last) flag = false; set.remove(highest); arrayList.add(new pair(last, highest)); last = highest; cc[i]--; } if (cc[i] != 1) flag = false; cc[i]--; arrayList.add(new pair(last, n)); } } if (!flag) { out.println("NO"); return; } if (arrayList.size() != n - 1) throw new RuntimeException("NO"); out.println("YES"); for (pair p : arrayList) out.println(p.x + " " + p.y); } class pair { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
d5008e3a3b05ee31681241abe4f050fd
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.Map.Entry; public class Main { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private PrintWriter pw; private long mod = 1000000000 + 7; private StringBuilder ans_sb; private void soln() { // int n = nextInt(); // long m = nextLong(); // long d = nextLong(); // Pair[] a = new Pair[n]; // for(int i=0;i<n;i++) { // a[i] = new Pair(nextLong(), i); // } // Arrays.parallelSort(a); // boolean[] v = new boolean[n]; // int day = 0; // int[] ans1 = new int[n]; // for(int i=0;i<n;i++) { // if(!v[i]) { // day++; // v[i] = true; // ans1[a[i].b] = day; // } // int l = i+1; // int r = n-1; // int ans = -1; // // while(l<=r) { // int mid = ((l+r)>>1); // if(a[mid].a - a[i].a >= d+1) { // r = mid - 1; // ans = mid; // }else { // l = mid + 1; // } // } // if(ans != -1) { // v[ans] = true; // ans1[a[ans].b] = ans1[a[i].b]; // } // } // pw.println(day); // for(int i=0;i<n;i++) { // pw.print(ans1[i]+" "); // } int n = nextInt(); int[] freq = new int[n]; // TreeSet<Integer> ts = new TreeSet<>(); for (int i = 0; i < n - 1; i++) { int a = nextInt() - 1; int b = nextInt() - 1; freq[a]++; freq[b]++; } // debug(freq); boolean f = true; if (freq[n - 1] != n - 1) f = false; boolean[] v = new boolean[n]; ArrayList<Integer> l = new ArrayList<>(); v[n - 1] = true; l.add(n - 1); for (int i = n - 2; i >= 0; i--) { if (!v[i]) { v[i] = true; int ff = freq[i] - 1; if (ff != 0) { for (int j = i; j >= 0; j--) { if (!v[j] && freq[j] == 0) { l.add(j); v[j] = true; ff--; if (ff == 0) break; } } } // debug(ff); // debug(i); if (ff != 0) { f = false; } l.add(i); } } if (l.size() != n) f = false; if (f) { pw.println( "YES"); for (int i = 0; i < n - 1; i++) { pw.println( (l.get(i) + 1) + " " + (l.get( i + 1) + 1)); } } else pw.println( "NO"); } private class Pair implements Comparable<Pair> { long a; int b; public Pair( long x, int y) { a = x; b = y; } @Override public int compareTo( Pair arg0) { return Long .compare( this.a, arg0.a); } } private String solveEqn( long a, long b) { long x = 0, y = 1, lastx = 1, lasty = 0, temp; while (b != 0) { long q = a / b; long r = a % b; a = b; b = r; temp = x; x = lastx - q * x; lastx = temp; temp = y; y = lasty - q * y; lasty = temp; } return lastx + " " + lasty; } private void debug( Object... o) { System.out .println( Arrays.deepToString( o)); } private long pow( long a, long b, long c) { if (b == 0) return 1; long p = pow( a, b / 2, c); p = (p * p) % c; return (b % 2 == 0) ? p : (a * p) % c; } private long gcd( long n, long l) { if (l == 0) return n; return gcd( l, n % l); } public static void main( String[] args) throws Exception { new Thread( null, new Runnable() { @Override public void run() { new Main() .solve(); } }, "1", 1 << 26).start(); // new Main().solve(); } public StringBuilder solve() { InputReader( System.in); /* * try { InputReader(new FileInputStream("C:\\Users\\hardik\\Desktop\\in.txt")); * } catch(FileNotFoundException e) {} */ pw = new PrintWriter( System.out); // ans_sb = new StringBuilder(); soln(); pw.close(); // System.out.println(ans_sb); return ans_sb; } public void InputReader( InputStream stream1) { stream = stream1; } private boolean isWhitespace( int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine( int c) { return c == '\n' || c == '\r' || c == -1; } private 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 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 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 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 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 int[] nextIntArray( int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } private long[] nextLongArray( int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private void pArray( int[] arr) { for (int i = 0; i < arr.length; i++) { System.out .print(arr[i] + " "); } System.out .println(); return; } private void pArray( long[] arr) { for (int i = 0; i < arr.length; i++) { System.out .print(arr[i] + " "); } System.out .println(); return; } private boolean isSpaceChar( int c) { if (filter != null) return filter .isSpaceChar( c); return isWhitespace( c); } private char nextChar() { int c = read(); while (isSpaceChar( c)) c = read(); char c1 = (char) c; while (!isSpaceChar( c)) c = read(); return c1; } private interface SpaceCharFilter { public boolean isSpaceChar( int ch); } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
2512bc5a97994155131789b5b2b648da
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class E { FastScanner in; PrintWriter out; boolean systemIO = true; public class Pair { int v; int place; public Pair(int v, int place) { this.v = v; this.place = place; } } public void solve() { int n = in.nextInt(); int[] v = new int[n]; for (int i = 0; i < n - 1; i++) { int x = in.nextInt() - 1; v[x]++; if (in.nextInt() != n) { out.println("NO"); return; } } int[][] path = new int[n][]; path[n - 1] = new int[0]; Queue<Pair> q = new ArrayDeque<>(); for (int i = n - 2; i >= 0; i--) { if (v[i] == 0) { if (q.isEmpty()) { out.println("NO"); return; } Pair p = q.poll(); path[p.v][p.place] = i; path[i] = new int[0]; } else { path[i] = new int[v[i]]; path[i][v[i] - 1] = i; for (int j = 0; j < path[i].length - 1; j++) { q.add(new Pair(i, j)); } } } if (!q.isEmpty()) { out.println("NO"); return; } out.println("YES"); for (int i = 0; i < path.length; i++) { int th = n - 1; for (int j = 0; j < path[i].length; j++) { out.println(th + 1 + " " + (path[i][j] + 1)); th = path[i][j]; } } } public void run() { try { if (systemIO) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("segments.in")); out = new PrintWriter(new File("segments.out")); } solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA public static void main(String[] arg) { new E().run(); } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
b2324c6fb60f387d3cb56a18d750bf9a
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=998244353L; int ret=99999999; void work() { int n=in.nextInt(); int[] count=new int[n]; for(int i=0;i<n-1;i++){ int s=in.nextInt(); int e=in.nextInt(); if(s>e){ int t=s; s=e; e=t; } if(e!=n||s==e){ out.println("NO"); return; } count[s]++; if(count[s]>s){ out.println("NO"); return; } } for(int i=1,cur=0;i<n;i++){ cur+=count[i]; if(cur>i){ out.println("NO"); return; } } int[] ret=new int[n]; ret[n-1]=n; for(int i=0,j=0;i<n&&j<n;){ while(j<n&&count[j]==0){ j++; } ret[i]=j; if(j<n)i+=count[j++]; } for(int i=0,j=1;i<n-1;i++){ if(ret[i]!=0)continue; while(count[j]!=0){ j++; } ret[i]=j++; } out.println("YES"); for(int i=1;i<n;i++){ out.println(ret[i-1]+" "+ret[i]); } } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
b0d09e9c9a5534a8d8552f7db1ffc296
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.awt.Point; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.Scanner; public class E1041 { static int N; public static void main(String args[]) throws Exception { Scanner in = new Scanner(new BufferedInputStream(System.in)); PrintStream out = new PrintStream(new BufferedOutputStream(System.out)); N = in.nextInt(); int[] counts = new int[N - 1]; for (int i = 0; i < 2 * (N - 1); i++) { int curr = in.nextInt() - 1; if (curr != N - 1) counts[curr]++; } PriorityQueue<Integer> valid = new PriorityQueue<>(); PriorityQueue<Point> todo = new PriorityQueue<>((a, b) -> a.x - b.x); for (int i = 0; i < counts.length; i++) { if (counts[i] == 0) valid.add(i); else todo.add(new Point(i, counts[i])); } if (solve(valid, todo)) { out.println("YES"); for (Point edge : edges) { out.println((edge.x + 1) + " " + (edge.y + 1)); } } else { out.println("NO"); } out.flush(); } static ArrayList<Point> edges = new ArrayList<>(); public static boolean solve(PriorityQueue<Integer> valid, PriorityQueue<Point> todo) { while (todo.size() > 0) { Point curr = todo.poll(); int prev = N - 1; for (int i = 1; i < curr.y; i++) { if (valid.isEmpty() || valid.peek() > curr.x) return false; int next = valid.poll(); edges.add(new Point(prev, next)); prev = next; } edges.add(new Point(prev, curr.x)); } return true; } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
20544c7b724a8433774ddf5f11ff0564
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
//package que_a; import java.io.*; import java.util.*; import java.math.*; public class utkarsh { InputStream is; PrintWriter out; long mod = (long) (1e9 + 7), inf = (long) (3e15); boolean SHOW_TIME, debug; class pair { int F, S; pair(int f, int s) { F = f; S = s; } } void solve() { //Enter code here utkarsh //SHOW_TIME = true; //debug = true; int n = ni(); int a[] = new int[n-1]; boolean b[] = new boolean[n]; for(int i = 0; i < n-1; i++) { int u = ni(), v = ni(); if(u == n && v == n) { out.println("NO"); return; } else if(u == n) { a[i] = v; b[v] = true; } else if(v == n) { a[i] = u; b[u] = true; } else { out.println("NO"); return; } } Arrays.sort(a); int x = n-1, j = n-1, k; pair d[] = new pair[n-1]; for(int i = n-2; i >= 0; i = k) { if(a[i] < x) { out.println("NO"); return; } k = i; int y = n; while(k > 0 && a[k-1] == a[i]) { while(b[j]) j--; d[k] = new pair(y, j); y = j; j--; k--; } d[k] = new pair(y, a[i]); k--; x -= (i - k); } out.println("YES"); for(pair p : d) out.println(p.F +" "+ p.S); } long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a%b); } //---------- I/O Template ---------- public static void main(String[] args) { new utkarsh().run(); } void run() { is = System.in; out = new PrintWriter(System.out); long start = System.currentTimeMillis(); solve(); long end = System.currentTimeMillis(); if(SHOW_TIME) out.println("\n" + (end - start) + " ms"); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
f3f0a4af4ea6bb344674454e51d170b6
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.*; import java.math.*; import java.text.*; import java.util.*; import java.util.regex.*; public class Solution { 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; } } public static void main(String[] args) throws IOException { InputReader in=new InputReader(System.in); PrintWriter w=new PrintWriter(System.out); int n=in.nextInt(); int[] a=new int[n-1]; int[] b=new int[n-1]; boolean lb=false; for(int i=0;i<n-1;i++) { a[i]=in.nextInt(); b[i]=in.nextInt(); if(b[i]<n) lb=true; } if(lb) { w.println("NO"); } else { Arrays.sort(a); int cur=a[0]; int min=1; boolean[] vis=new boolean[n+1]; int[] ax=new int[n-1]; int[] ay=new int[n-1]; int index=0; vis[n]=true; boolean exist=false; int i=1; int cur_root=a[0]; boolean np=false; for(i=1;i<n-1;i++) { //w.println("hello"+" "+i+" "+cur+" "+min); if(a[i]>cur) { //w.println("heyy "+i); ax[index]=cur_root; ay[index]=n; index++; vis[cur]=true; cur_root=a[i]; } else { exist=false; for(int j=cur_root-1;j>=1;j--) { if(!vis[j]) { min=j; exist=true; break; } } if(!exist) { np=true; break; } ax[index]=min; ay[index]=cur_root; index++; vis[min]=true; vis[a[i]]=true; cur_root=min; } cur=a[i]; } ax[index]=cur_root; ay[index]=n; index++; //w.println(i); if(np) { w.println("NO"); } else { w.println("YES"); for(int q=0;q<=n-2;q++) { w.println(ax[q]+" "+ay[q]); } } } w.close(); } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
b758ab22b3a1ad4cb358c78b6bbb3575
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.io.*; import java.util.*; public class Main { private void solve() throws IOException { int n = readInt(); int[] a = new int[n]; int[] cnt = new int[n]; for (int i = 0; i < n - 1; i++) { int x = readInt() - 1; int y = readInt() - 1; a[i] = Math.min(x, y); if (Math.max(x, y) != n - 1) { out.println("NO"); return; } cnt[a[i]]++; } List<Integer> missing = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { if (cnt[i] == 0) { missing.add(i); } } List<Integer>[] g = new List[n]; for (int i = 0; i < n; i++) { g[i] = new ArrayList<>(); } for (int i = n - 1; i >= 0; i--) { if (cnt[i] == 0) { continue; } for (int j = 0; j < cnt[i] - 1; j++) { int v = missing.get(missing.size() - 1); missing.remove(missing.size() - 1); if (v > i) { out.println("NO"); return; } g[i].add(v); } } out.println("YES"); for (int i = 0; i < n - 1; i++) { if (cnt[i] == 0) { continue; } int from = n - 1; for (int v : g[i]) { out.println((from + 1) + " " + (v + 1)); from = v; } out.println((from + 1) + " " + (i + 1)); } } /////////////////////////////////////////////////////////////////////////////////////////////////// BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) throws IOException { new Main().run(); } private void run() { try { long t1 = System.nanoTime(); if (new File("input.txt").exists()) { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } else { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } solve(); in.close(); out.close(); long t2 = System.nanoTime(); System.err.println("Time = " + (t2 - t1) / 1e9 + " sec"); } catch (Throwable e) { throw new RuntimeException(e); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } @SuppressWarnings("unused") int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") long readLong() throws IOException { return Long.parseLong(readString()); } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
6890ed4ae060b9c2cfba59c760dae99e
train_000.jsonl
1537094100
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
256 megabytes
import java.lang.*; import java.math.*; import java.util.*; import java.io.*; public class Main { void solve(){ int n=ni(); int cnt[]=new int[n+1]; for(int i=1;i<n;i++){ int a=ni(),b=ni(); if(b!=n) { pw.println("NO"); return; } cnt[a]++; } int a[]=new int[n+1]; int i=1,j=1; a[1]=n; for(int k=n-1;k>=1;k--){ if(cnt[k]==0){ while(j<=i && a[j]!=0) j++; if(j>i) { pw.println("NO"); return; } a[j]=k; }else { if(i+cnt[k]<=n) { a[i+cnt[k]]=k; i+=cnt[k]; }else { pw.println("NO"); return; } } } pw.println("YES"); for(i=1;i<n;i++){ pw.println(a[i]+" "+a[i+1]); } } long M=(long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); Thread t = new Thread(null, null, "~", Runtime.getRuntime().maxMemory()){ @Override public void run() { long s = System.currentTimeMillis(); solve(); pw.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } }; t.start(); t.join(); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); } }
Java
["4\n3 4\n1 4\n3 4", "3\n1 3\n1 3", "3\n1 2\n2 3"]
1 second
["YES\n1 3\n3 2\n2 4", "NO", "NO"]
NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Java 8
standard input
[ "data structures", "constructive algorithms", "greedy", "graphs" ]
531746ba8d93a76d5bdf4bab67d9ba19
The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i &lt; b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.
1,900
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
standard output
PASSED
f248b8628ed30153673d8e46ba67e803
train_000.jsonl
1331280000
Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters — color ci and size si. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in the tower must alternate (colors of adjacent cubes must differ). The Zebra Tower should have at least two cubes. There are no other limitations. The figure below shows an example of a Zebra Tower. A Zebra Tower's height is the sum of sizes of all cubes that form the tower. Help little Janet build the Zebra Tower of the maximum possible height, using the available cubes.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; import java.util.TreeMap; public class cf159e { public static void main(String[] args) { FastIO in = new FastIO(), out = in; int n = in.nextInt(); Map<Long,Cluster<Pair<Long,Long>>> map = new HashMap<Long,Cluster<Pair<Long,Long>>>(); long[] c = new long[n], s = new long[n]; for(int i=0; i<n; i++) { c[i] = in.nextInt(); s[i] = in.nextInt(); if(!map.containsKey(c[i])) map.put(c[i],new Cluster<Pair<Long,Long>>()); map.get(c[i]).add(new Pair<Long,Long>(-s[i],(long)i)); } Map<Long,Pair<Long,Long>> sizes = new HashMap<Long,Pair<Long,Long>>(); long ans = 0; long c1 = 0, c2 = 0; for(Cluster<Pair<Long,Long>> cl : map.values()) { long sum = 0; long count = 0; for(Pair<Long,Long> p : cl) { sum += -p.first; count++; if(sizes.containsKey(count-1)) { long tsum = sum + sizes.get(count-1).first; if(tsum > ans) { c1 = c[p.second.intValue()]; c2 = sizes.get(count-1).second; ans = tsum; } } if(sizes.containsKey(count)) { long tsum = sum + sizes.get(count).first; if(tsum > ans) { c1 = c[p.second.intValue()]; c2 = sizes.get(count).second; ans = tsum; } } if(sizes.containsKey(count+1)) { long tsum = sum + sizes.get(count+1).first; if(tsum > ans) { c2 = c[p.second.intValue()]; c1 = sizes.get(count+1).second; ans = tsum; } } } sum = 0; count = 0; for(Pair<Long,Long> p : cl) { sum += -p.first; count++; if(!sizes.containsKey(count) || sum > sizes.get(count).first) { sizes.put(count, new Pair<Long,Long>(sum,c[p.second.intValue()])); } } } out.println(ans); Iterator<Pair<Long,Long>> i1 = map.get(c1).iterator(); Iterator<Pair<Long,Long>> i2 = map.get(c2).iterator(); int count = 0, total = 0; StringBuilder sb = new StringBuilder(); while(true) { if(count % 2 == 0) { if(!i1.hasNext()) break; total++; sb.append((i1.next().second+1)+" "); } else { if(!i2.hasNext()) break; total++; sb.append((i2.next().second+1)+" "); } count++; } out.println(total); out.println(sb.toString().trim()); out.close(); } static class Pair<T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>> implements Comparable<Pair<T1,T2>>{ T1 first; T2 second; Pair(T1 _first, T2 _second) { first = _first; second = _second; } @Override public int compareTo(Pair<T1,T2> p) { int z = first.compareTo(p.first); if(z != 0) return z; return second.compareTo(p.second); } @Override public boolean equals(Object o) { if(!(o instanceof Pair<?,?>)) return false; @SuppressWarnings("unchecked") Pair<T1,T2> p = (Pair<T1,T2>)o; return first.equals(p.first) && second.equals(p.second); } public String toString() { return first+":"+second; } } static class Cluster<T extends Comparable<? super T>> implements Iterable<T> { TreeMap<T,Long> map = new TreeMap<T,Long>(); Cluster() {} void add(T t) { if(map.containsKey(t)) map.put(t, map.get(t)+1); else map.put(t, 1L); } @Override public Iterator<T> iterator() { return new ClusterIterator<T>(map); } public String toString() { return "["+map+"]"; } } static class ClusterIterator<T extends Comparable<? super T>> implements Iterator<T> { Iterator<Entry<T,Long>> baseIterator; T element; long count = 0; public ClusterIterator(TreeMap<T, Long> map) { baseIterator = map.entrySet().iterator(); } @Override public boolean hasNext() { if(count > 0) return true; return baseIterator.hasNext(); } @Override public T next() { if(count == 0) { Entry<T,Long> curEntry = baseIterator.next(); element = curEntry.getKey(); count = curEntry.getValue(); return next(); } count--; return element; } @Override public void remove() { throw new UnsupportedOperationException(); } } static class FastIO extends PrintWriter { BufferedReader br; StringTokenizer st; public FastIO() { this(System.in,System.out); } public FastIO(InputStream in, OutputStream out) { super(new BufferedWriter(new OutputStreamWriter(out))); br = new BufferedReader(new InputStreamReader(in)); scanLine(); } public void scanLine() { try { st = new StringTokenizer(br.readLine().trim()); } catch(Exception e) { throw new RuntimeException(e.getMessage()); } } public int numTokens() { if(!st.hasMoreTokens()) { scanLine(); return numTokens(); } return st.countTokens(); } public String next() { if(!st.hasMoreTokens()) { scanLine(); return next(); } return st.nextToken(); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n1 2\n1 3\n2 4\n3 3", "2\n1 1\n2 1"]
1.5 seconds
["9\n3\n2 3 1", "2\n2\n2 1"]
null
Java 7
standard input
[ "data structures", "sortings", "*special", "greedy" ]
fa867bb7df94cc0edc03bcbf975de001
The first line contains an integer n (2 ≤ n ≤ 105) — the number of cubes. Next n lines contain the descriptions of the cubes, one description per line. A cube description consists of two space-separated integers ci and si (1 ≤ ci, si ≤ 109) — the i-th cube's color and size, correspondingly. It is guaranteed that there are at least two cubes of different colors.
1,700
Print the description of the Zebra Tower of the maximum height in the following form. In the first line print the tower's height, in the second line print the number of cubes that form the tower, and in the third line print the space-separated indices of cubes in the order in which they follow in the tower from the bottom to the top. Assume that the cubes are numbered from 1 to n in the order in which they were given in the input. If there are several existing Zebra Towers with maximum heights, it is allowed to print any of them. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
standard output
PASSED
ca6becd515afe5558c4bed21419bfaa4
train_000.jsonl
1331280000
Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters — color ci and size si. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in the tower must alternate (colors of adjacent cubes must differ). The Zebra Tower should have at least two cubes. There are no other limitations. The figure below shows an example of a Zebra Tower. A Zebra Tower's height is the sum of sizes of all cubes that form the tower. Help little Janet build the Zebra Tower of the maximum possible height, using the available cubes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; public class Main { static class Assert { static void check(boolean e) { if (!e) { throw new Error(); } } } class Stack { int len; int[] val; Stack() { int[] val = new int[100001]; len = 0; } int pop() { return val[len--]; } int add(int v) { return val[++len] = v; } } class Scanner { StreamTokenizer in; Scanner(InputStream is) { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(is))); in.resetSyntax(); in.whitespaceChars(0, 32); in.wordChars(33, 255); } String next() { try { in.nextToken(); Assert.check(in.ttype == in.TT_WORD); return in.sval; } catch (IOException e) { throw new Error(e); } } int nextInt() { return Integer.parseInt(next()); } } public static void main(String[] argv) { new Main().run(); } void run() { in = new Scanner(System.in); out = new PrintWriter(System.out); try { solve(); } finally { out.close(); } } PrintWriter out; Scanner in; class Box { int color; int cost; Box() { color = in.nextInt(); cost = in.nextInt(); } @Override public String toString() { return color + " " + cost; } @Override public int hashCode() { return cost + 31 * color; } @Override public boolean equals(Object o) { Box b = (Box) o; return b.cost == cost && b.color == color; } } class Pack { long cost; int len; int color; Pack(long cost, int len, int color) { this.color = color; this.cost = cost; this.len = len; } @Override public String toString() { return color + " " + cost + " " + len; } } class PackList extends ArrayList<Pack> { PackList() { super(); } PackList(PackList a) { super(a); } } class BoxList extends ArrayList<Box> { BoxList(BoxList a) { super(a); } BoxList() { super(); } } void outAnswer(Pack p1, Pack p2, Box[] a, Box[] sort) { int col1 = p1.color; int col2 = p2.color; int len1 = p1.len; int len2 = p2.len; HashMap<Box, Integer> map = new HashMap<Box, Integer>(); for (int i = 0; i < sort.length; i++) { if (sort[i].color == col1 && len1 > 0) { if (!map.containsKey(sort[i])) { map.put(sort[i], 1); } else { map.put(sort[i], map.get(sort[i]) + 1); } len1--; } if (sort[i].color == col2 && len2 > 0) { if (!map.containsKey(sort[i])) { map.put(sort[i], 1); } else { map.put(sort[i], map.get(sort[i]) + 1); } len2--; } } out.println(p1.cost + p2.cost); out.println(p1.len + p2.len); ArrayList<Integer> index1 = new ArrayList<Integer>(); ArrayList<Integer> index2 = new ArrayList<Integer>(); for (int i = 0; i < a.length; i++) { if (map.containsKey(a[i])) { if (col1 == a[i].color) { index1.add(i + 1); } else { index2.add(i + 1); } int cnt = map.get(a[i]) - 1; if (cnt == 0) { map.remove(a[i]); } else { map.put(a[i], cnt); } } } int min = Math.min(index1.size(), index2.size()); for (int i = 0; i < min; i++) { out.print(index1.get(i) + " " + index2.get(i) + " "); } if (index1.size() > min) { out.print(index1.get(index1.size() - 1)); } if (index2.size() > min) { out.print(index2.get(index2.size() - 1)); } } void solve() { int n = in.nextInt(); Box[] a = new Box[n]; for (int i = 0; i < n; i++) { a[i] = new Box(); } Box[] b = a.clone(); Arrays.sort(a, new Comparator<Box>() { @Override public int compare(Box b1, Box b2) { if (b1.color == b2.color) { return b2.cost - b1.cost; } return b1.color - b2.color; } }); int color = a[0].color; long curSum = a[0].cost; Pack[] packs = new Pack[n]; int len = 1; packs[0] = new Pack(curSum, len, color); for (int i = 1; i < n; i++) { if (color == a[i].color) { curSum += a[i].cost; len++; packs[i] = new Pack(curSum, len, color); } else { color = a[i].color; curSum = a[i].cost; len = 1; packs[i] = new Pack(curSum, len, color); } } Arrays.sort(packs, new Comparator<Pack>() { @Override public int compare(Pack p1, Pack p2) { if (p1.len == p2.len) { if (p2.cost == p1.cost) { return 0; } return p2.cost - p1.cost > 0 ? 1 : -1; } return p1.len - p2.len; } }); ArrayList<Pack> res = new ArrayList<Pack>(); HashMap<Integer, PackList> map = new HashMap<Integer, PackList>(); // for (int i = 0; i < n; i++) { // out.println(packs[i]); // } int lastLen = 1; int count = 1; res.add(packs[0]); for (int i = 1; i < n; i++) { // out.println(lastLen == packs[i].len); if (lastLen == packs[i].len && count > 0) { res.add(packs[i]); count--; } else if (lastLen != packs[i].len) { lastLen = packs[i].len; count = 1; res.add(packs[i]); } } // out.println("-----------------------------"); // for (int i = 0; i < res.size(); i++) { // out.println(res.get(i)); // } PackList buf = new PackList(); for (int i = 0; i < res.size();) { buf.clear(); if (i < res.size() - 1 && res.get(i).len == res.get(i + 1).len) { // out.println("x2 add"); buf.add(res.get(i)); buf.add(res.get(i + 1)); map.put(res.get(i).len, new PackList(buf)); i += 2; } else { buf.add(res.get(i)); map.put(res.get(i).len, new PackList(buf)); i++; } } // now we have array of blocks in map with key as len // for-each 1->max len; find max size len = res.get(res.size() - 1).len; long max = Long.MIN_VALUE; Pack part1 = null; Pack part2 = null; if (map.get(1).size() == 2) { max = map.get(1).get(0).cost + map.get(1).get(1).cost; part1 = map.get(1).get(0); part2 = map.get(1).get(1); } // for (Integer i : map.keySet()) { // out.println(map.get(i)); // } for (int l = 2; l <= len; l++) { if (map.get(l).size() == 2) { Pack f = map.get(l).get(0); Pack s = map.get(l).get(1); if (max < f.cost + s.cost) { max = f.cost + s.cost; // out.println("update"); part1 = f; part2 = s; } } for (Pack p1 : map.get(l)) { for (Pack p2 : map.get(l - 1)) { if (p1.color != p2.color && max < p1.cost + p2.cost) { max = p1.cost + p2.cost; part1 = p1; part2 = p2; } } } } outAnswer(part1, part2, b, a); } }
Java
["4\n1 2\n1 3\n2 4\n3 3", "2\n1 1\n2 1"]
1.5 seconds
["9\n3\n2 3 1", "2\n2\n2 1"]
null
Java 7
standard input
[ "data structures", "sortings", "*special", "greedy" ]
fa867bb7df94cc0edc03bcbf975de001
The first line contains an integer n (2 ≤ n ≤ 105) — the number of cubes. Next n lines contain the descriptions of the cubes, one description per line. A cube description consists of two space-separated integers ci and si (1 ≤ ci, si ≤ 109) — the i-th cube's color and size, correspondingly. It is guaranteed that there are at least two cubes of different colors.
1,700
Print the description of the Zebra Tower of the maximum height in the following form. In the first line print the tower's height, in the second line print the number of cubes that form the tower, and in the third line print the space-separated indices of cubes in the order in which they follow in the tower from the bottom to the top. Assume that the cubes are numbered from 1 to n in the order in which they were given in the input. If there are several existing Zebra Towers with maximum heights, it is allowed to print any of them. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
standard output
PASSED
86951739be377540b4136ee6bc72b5f0
train_000.jsonl
1331280000
Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters — color ci and size si. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in the tower must alternate (colors of adjacent cubes must differ). The Zebra Tower should have at least two cubes. There are no other limitations. The figure below shows an example of a Zebra Tower. A Zebra Tower's height is the sum of sizes of all cubes that form the tower. Help little Janet build the Zebra Tower of the maximum possible height, using the available cubes.
256 megabytes
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] argv) { new Main().run(); } void run() { in = new Scanner(System.in); out = new PrintWriter(System.out); try { solve(); } finally { out.close(); } } PrintWriter out; Scanner in; class Box { int color; int cost; Box() { color = in.nextInt(); cost = in.nextInt(); } @Override public int hashCode() { return cost + 31 * color; } @Override public boolean equals(Object o) { Box b = (Box) o; return b.cost == cost && b.color == color; } } class Pack { long cost; int len; int color; Pack(long cost, int len, int color) { this.color = color; this.cost = cost; this.len = len; } } class PackList extends ArrayList<Pack> { PackList() { super(); } PackList(PackList a) { super(a); } } class BoxList extends ArrayList<Box> { BoxList(BoxList a) { super(a); } BoxList() { super(); } } void outAnswer(Pack p1, Pack p2, Box[] a, Box[] sort) { int col1 = p1.color; int col2 = p2.color; int len1 = p1.len; int len2 = p2.len; HashMap<Box, Integer> map = new HashMap<Box, Integer>(); for (int i = 0; i < sort.length; i++) { if (sort[i].color == col1 && len1 > 0) { if (!map.containsKey(sort[i])) { map.put(sort[i], 1); } else { map.put(sort[i], map.get(sort[i]) + 1); } len1--; } if (sort[i].color == col2 && len2 > 0) { if (!map.containsKey(sort[i])) { map.put(sort[i], 1); } else { map.put(sort[i], map.get(sort[i]) + 1); } len2--; } } out.println(p1.cost + p2.cost); out.println(p1.len + p2.len); ArrayList<Integer> index1 = new ArrayList<Integer>(); ArrayList<Integer> index2 = new ArrayList<Integer>(); for (int i = 0; i < a.length; i++) { if (map.containsKey(a[i])) { if (col1 == a[i].color) { index1.add(i + 1); } else { index2.add(i + 1); } int cnt = map.get(a[i]) - 1; if (cnt == 0) { map.remove(a[i]); } else { map.put(a[i], cnt); } } } int min = Math.min(index1.size(), index2.size()); for (int i = 0; i < min; i++) { out.print(index1.get(i) + " " + index2.get(i) + " "); } if (index1.size() > min) { out.print(index1.get(index1.size() - 1)); } if (index2.size() > min) { out.print(index2.get(index2.size() - 1)); } } void solve() { int n = in.nextInt(); Box[] a = new Box[n]; for (int i = 0; i < n; i++) { a[i] = new Box(); } Box[] b = a.clone(); Arrays.sort(a, new Comparator<Box>() { @Override public int compare(Box b1, Box b2) { if (b1.color == b2.color) { return b2.cost - b1.cost; } return b1.color - b2.color; } }); int color = a[0].color; long curSum = a[0].cost; Pack[] packs = new Pack[n]; int len = 1; packs[0] = new Pack(curSum, len, color); for (int i = 1; i < n; i++) { if (color == a[i].color) { curSum += a[i].cost; len++; packs[i] = new Pack(curSum, len, color); } else { color = a[i].color; curSum = a[i].cost; len = 1; packs[i] = new Pack(curSum, len, color); } } Arrays.sort(packs, new Comparator<Pack>() { @Override public int compare(Pack p1, Pack p2) { if (p1.len == p2.len) { if (p2.cost == p1.cost) { return 0; } return p2.cost - p1.cost > 0 ? 1 : -1; } return p1.len - p2.len; } }); ArrayList<Pack> res = new ArrayList<Pack>(); HashMap<Integer, PackList> map = new HashMap<Integer, PackList>(); int lastLen = 1; int count = 1; res.add(packs[0]); for (int i = 1; i < n; i++) { if (lastLen == packs[i].len && count > 0) { res.add(packs[i]); count--; } else if (lastLen != packs[i].len) { lastLen = packs[i].len; count = 1; res.add(packs[i]); } } PackList buf = new PackList(); for (int i = 0; i < res.size();) { buf.clear(); if (i < res.size() - 1 && res.get(i).len == res.get(i + 1).len) { buf.add(res.get(i)); buf.add(res.get(i + 1)); map.put(res.get(i).len, new PackList(buf)); i += 2; } else { buf.add(res.get(i)); map.put(res.get(i).len, new PackList(buf)); i++; } } len = res.get(res.size() - 1).len; long max = 0; Pack part1 = null; Pack part2 = null; if (map.get(1).size() == 2) { max = map.get(1).get(0).cost + map.get(1).get(1).cost; part1 = map.get(1).get(0); part2 = map.get(1).get(1); } for (int l = 2; l <= len; l++) { if (map.get(l).size() == 2) { if (max < map.get(l).get(0).cost + map.get(l).get(1).cost) { max = map.get(l).get(0).cost + map.get(l).get(1).cost; part1 = map.get(l).get(0); part2 = map.get(l).get(1); } } for (Pack p1 : map.get(l)) { for (Pack p2 : map.get(l - 1)) { if (p1.color != p2.color && max < p1.cost + p2.cost) { max = p1.cost + p2.cost; part1 = p1; part2 = p2; } } } } outAnswer(part1, part2, b, a); } }
Java
["4\n1 2\n1 3\n2 4\n3 3", "2\n1 1\n2 1"]
1.5 seconds
["9\n3\n2 3 1", "2\n2\n2 1"]
null
Java 7
standard input
[ "data structures", "sortings", "*special", "greedy" ]
fa867bb7df94cc0edc03bcbf975de001
The first line contains an integer n (2 ≤ n ≤ 105) — the number of cubes. Next n lines contain the descriptions of the cubes, one description per line. A cube description consists of two space-separated integers ci and si (1 ≤ ci, si ≤ 109) — the i-th cube's color and size, correspondingly. It is guaranteed that there are at least two cubes of different colors.
1,700
Print the description of the Zebra Tower of the maximum height in the following form. In the first line print the tower's height, in the second line print the number of cubes that form the tower, and in the third line print the space-separated indices of cubes in the order in which they follow in the tower from the bottom to the top. Assume that the cubes are numbered from 1 to n in the order in which they were given in the input. If there are several existing Zebra Towers with maximum heights, it is allowed to print any of them. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
standard output
PASSED
30633b9aa7d8a4c6aba9731a9be46d4e
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class beautifulString { //FastScanner for Java public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String args[]) { FastScanner in = new FastScanner(); int n = in.nextInt(); for(int i = 0; i<n; i++) { char[] line = in.next().toCharArray(); if(line.length == 1) { if(line[0] == '?') System.out.println("a"); else System.out.println(line[0]); continue; } boolean flag = true; for(int j = 0; j<line.length; j++) { if(j<line.length-1) { if(line[j]!='?' && line[j+1]!='?' && line[j] == line[j+1]) { System.out.println(-1); flag = false; } } if(!flag) break; while(line[j] == '?') { if(j == 0) { if(line[j+1] == '?') line[j] = 'a'; else if(line[j+1] == 'a') line[j] = 'b'; else if(line[j+1] == 'b') line[j] = 'c'; else if(line[j+1] == 'c') line[j] = 'a'; } else if(j == line.length-1) { if(line[j-1] == '?') line[j] = 'a'; else if(line[j-1] == 'a') line[j] = 'b'; else if(line[j-1] == 'b') line[j] = 'c'; else if(line[j-1] == 'c') line[j] = 'a'; } else { char front = line[j+1]; char back = line[j-1]; if(front == 'a' && back == 'b') line[j] = 'c'; if(front == 'a' && back == 'c') line[j] = 'b'; if(front == 'a' && back == 'a') line[j] = 'c'; if(front == 'b' && back == 'a') line[j] = 'c'; if(front == 'b' && back == 'c') line[j] = 'a'; if(front == 'b' && back == 'b') line[j] = 'c'; if(front == 'c' && back == 'a') line[j] = 'b'; if(front == 'c' && back == 'b') line[j] = 'a'; if(front == 'c' && back == 'c') line[j] = 'a'; if(front == 'a' && back == '?') line[j] = 'c'; if(front == 'b' && back == '?') line[j] = 'c'; if(front == 'c' && back == '?') line[j] = 'a'; if(front == '?' && back == 'a') line[j] = 'c'; if(front == '?' && back == 'b') line[j] = 'c'; if(front == '?' && back == 'c') line[j] = 'a'; if(front == '?' && back == '?') line[j] = 'c'; } } } if(flag) System.out.println(line); } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
89ef1dc6d970134fc40b62f67854e77f
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; // import java.text.DecimalFormat; public class test{ 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; } } final static int N = (int) (1e5 + 10); static char[] a=new char[N]; static String s; static int sum; public static void main(String args[]){ FastReader sc=new FastReader(); int t=sc.nextInt(); while(t>0) { t--; s=sc.next(); s="0"+s+"0"; boolean flag=true; for(int i=1;i<s.length()-1;i++) { a[i]=s.charAt(i); if(s.charAt(i)=='?') { if(a[i-1]!='a'&&s.charAt(i+1)!='a') a[i]='a'; if(a[i-1]!='b'&&s.charAt(i+1)!='b') a[i]='b'; if(a[i-1]!='c'&&s.charAt(i+1)!='c') a[i]='c'; } else if(s.charAt(i)==s.charAt(i+1)) { flag=false; System.out.println(-1); break; } } if(flag) { for(int i=1;i<s.length()-1;i++) System.out.print(a[i]); System.out.println(); } } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
ec5f1b4b9e42f48e6590597797243e57
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.util.*; public class JavaApplication2{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); scan.nextLine(); String[] str = new String[n]; for (int i = 0; i < n; i++) { boolean f = true; str[i] = scan.nextLine(); if (!str[i].equals("?")) { char[] ch = str[i].toCharArray(); for (int j = 1; j < str[i].length(); j++) { if (ch[j] == '?') { ch[j] = 'a'; if (j != ch.length - 1) { if (ch[j - 1] == ch[j] || ch[j] == ch[j + 1]) { ch[j] = 'b'; if (ch[j - 1] == ch[j] || ch[j] == ch[j + 1]) { ch[j] = 'c'; } } } else { if (ch[j - 1] == ch[j]) { ch[j] = 'b'; if (ch[j - 1] == ch[j]) { ch[j] = 'c'; } } } } if (ch[0] == '?') { ch[0] = 'a'; if (ch[0] == ch[1]) { ch[0] = 'b'; } } if (ch[j - 1] == ch[j]) { f = false; break; } } if (!f) System.out.print("-1"); else System.out.print(new String(ch)); System.out.println(); } else System.out.println("a"); } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
c66d5f30215af7f0d7ffac0fa5d34470
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class s { public static void main (String[] args) throws java.lang.Exception { try { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ String s = sc.next(); int n = s.length(); char[] ch = new char[n+1]; for(int i=0;i<n;i++) ch[i] = s.charAt(i); boolean flag = true; if(n==1 && ch[0]=='?') ch[0] = 'a'; for(int i=0;i<n-1;i++){ if(i == 0 && ch[0]=='?'){ if(ch[1]!='a') ch[0] = 'a'; else if(ch[1]!='b') ch[0] = 'b'; else if(ch[1]!='c') ch[0] = 'c'; } else if(ch[i] == '?'){ if(ch[i-1]!='a' && ch[i+1]!='a') ch[i] = 'a'; else if(ch[i-1]!='b' && ch[i+1]!='b') ch[i] = 'b'; else if(ch[i-1]!='c' && ch[i+1]!='c') ch[i] = 'c'; } } if(ch[n-1] == '?'){ if(ch[n-2]!='a') ch[n-1] = 'a'; else if(ch[n-2]!='b') ch[n-1] = 'b'; else if(ch[n-2]!='c') ch[n-1] = 'c'; } for(int i=0;i<n-1;i++) if(ch[i] == ch[i+1]){ flag = false; break; } if(!flag) System.out.println(-1); else{ for(int i=0;i<n;i++) System.out.print(ch[i]); System.out.println(); } } } catch(Exception e) { return; } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
855f29ca5da72af1547b053f7262153c
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
//package cf1; import java.io.*; import java.util.*; public class utkarsh { BufferedReader br; PrintWriter out; long mod = (long) (1e9 + 7), inf = (long) (3e18); void solve() { int t = ni(); while(t-- > 0) { char s[] = ns().toCharArray(); int n = s.length; boolean possible = true; for(int i = 1; i < n; i++) { if(s[i] == '?' || s[i-1] == '?') continue; else if(s[i] == s[i-1]) { possible = false; break; } } if(!possible) { out.println(-1); continue; } for(int i = 0; i < n; i++) { if(s[i] == '?') { boolean vst[] = new boolean[3]; if(i > 0) vst[s[i-1] - 'a'] = true; if(i < n-1 && s[i+1] != '?') vst[s[i+1] - 'a'] = true; for(int j = 0; j < 3; j++) { if(!vst[j]) { s[i] = (char)(j + 'a'); break; } } } } out.println(new String(s)); } } long mp(long b, long e) { long r = 1; while(e > 0) { if( (e&1) == 1 ) r = (r * b) % mod; b = (b * b) % mod; e >>= 1; } return r; } // -------- I/O Template ------------- char nc() { return ns().charAt(0); } String nLine() { try { return br.readLine(); } catch(IOException e) { return "-1"; } } double nd() { return Double.parseDouble(ns()); } long nl() { return Long.parseLong(ns()); } int ni() { return Integer.parseInt(ns()); } StringTokenizer ip; String ns() { if(ip == null || !ip.hasMoreTokens()) { try { ip = new StringTokenizer(br.readLine()); } catch(IOException e) { throw new InputMismatchException(); } } return ip.nextToken(); } void run() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) { new utkarsh().run(); } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
e85202be5004fcc7f4371aad56a1471b
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { long k; void run(FastIO io) { int n = io.nextInt(); String next; char last, now; StringBuilder sb; boolean end; for (int i = 0; i < n; i++) { next = io.nextToken(); sb = new StringBuilder(); last = '-'; end = false; for (int j = 0; j < next.length() - 1 && !end; j++) { if (next.charAt(j) == last) { end = true; } if (next.charAt(j) == '?') { now = next.charAt(j + 1); //System.out.println("Рядом стоят " + last + ", ? и " + now); if (now == last || now == '?') { last = (char)((last - 96) % 3 + 97); //System.out.println("В центре встала " + last); } else { last = (char)(last == ((now - 96) % 3 + 97) ? ((last - 96) % 3 + 97) : ((now - 96) % 3 + 97)); //System.out.println("В центре встала " + last); } } else last = next.charAt(j); sb.append(last); //System.out.print(last); } now = next.charAt(next.length() - 1); if (now == '?') { sb.append((char)((last - 96) % 3 + 97)); } else { if (now == last) end = true; sb.append(now); } if (end) io.println(-1); else io.println(sb.toString()); } } class Pair implements Comparable<Pair> { int v, d; public Pair(int a, int b) { v = a; d = b; } @Override public int compareTo(Pair o) { if (d < o.d) return -1; return 1; } } public static void main(String[] args) throws InterruptedException { try (FastIO io = new FastIO(System.in, System.out)) { Thread t = new Thread(null, () -> new Main().run(io), "", (long) 3e7); t.start(); t.join(); } } static class FastIO extends PrintWriter { BufferedReader br; StringTokenizer stok; FastIO(InputStream is, OutputStream os) { super(os, false); br = new BufferedReader(new InputStreamReader(is)); stok = new StringTokenizer(""); } String nextToken() { while (!stok.hasMoreTokens()) { String s; try { s = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
305377156cf9466411595e24df25f929
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BeautifulString { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testcase = Integer.parseInt(br.readLine()); String input = null; int i = 0; boolean flag = false; char p = ' '; char n = ' '; while (testcase > 0) { input = br.readLine(); char[] arr = input.toCharArray(); i = 0; flag = false; while (i < input.length()) { if (i != 0) { p = arr[i - 1]; } if (i != input.length() - 1) { n = arr[i + 1]; } if (i != input.length() - 1) { if (input.charAt(i) == '?') { if (p == ' ') { if (n == 'a') { arr[i] = 'b'; } else if (n == 'b' || n == 'c') { arr[i] = 'a'; } else { arr[i] = 'c'; } } else if (n == '?' || n == ' ') { if (p == 'a') { arr[i] = 'b'; } else if (p == 'b' || p == 'c') { arr[i] = 'a'; } } else if (n == 'a') { if (p == 'a' || p == 'c') { arr[i] = 'b'; } else if (p == 'b') { arr[i] = 'c'; } } else if (n == 'b') { if (p == 'b' || p == 'c') { arr[i] = 'a'; } else if (p == 'a') { arr[i] = 'c'; } } else if (n == 'c') { if (p == 'a') { arr[i] = 'b'; } else if (p == 'b' || p == 'c') { arr[i] = 'a'; } } } else if (input.charAt(i) == input.charAt(i + 1)) { System.out.println("-1"); flag = true; break; } } else { if (arr[i] == '?') { if (p == 'a') { arr[i] = 'b'; } else if (p == 'b' || p == 'c') { arr[i] = 'a'; } else { arr[i]='c'; } } } i++; } if (flag == false) { System.out.println(String.valueOf(arr)); } testcase--; } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
e7249886982cce8c67912d960d7446e7
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; import javafx.util.Pair; public class HR27 { InputStream is; PrintWriter out; String INPUT = ""; //boolean codechef=true; boolean codechef=true; void solve() { int n = ni(); for(int i=0;i<n;i++) { String s=ns(); char[] ans=s.toCharArray(); char prev=' '; int f=1; for(int j=1;j<s.length()-1;j++) { HashSet<Character> set=new HashSet<>(); set.add('a'); set.add('b'); set.add('c'); if(s.charAt(j)=='?') { set.remove(ans[j-1]); set.remove(ans[j+1]); //out.println(set.toString()); for(char ch:set) { ans[j]=ch; break; } } else { if(s.charAt(j)==s.charAt(j-1)) { f=0; break; } } } if(ans.length==2) { if(ans[0]==ans[1] && ans[0]!='?') { out.println(-1); continue; } } if(ans.length==1) { if(ans[0]=='?') { out.println('a'); } else out.println(ans[0]); continue; } if(ans[0]=='?') { ans[0]=(char)(((int)(ans[1]-'a')+1)%3 + 'a'); } if(ans[ans.length-1]=='?') { ans[ans.length-1]=(char)(((int)(ans[ans.length-2]-'a')+1)%3 + 'a'); } for(int j=1;j<ans.length;j++) { if(ans[j]==ans[j-1]) { f=0; break; } } if(f==0) { out.println(-1); } else { out.println(new String(ans)); } } } static Pair[][] packD(int n, int[] from, Pair[] to) { Pair[][] g = new Pair[n][]; int[] p = new int[n]; for (int f : from) p[f]++; for (int i = 0; i < n; i++) g[i] = new Pair[p[i]]; for (int i = 0; i < from.length; i++) { g[from[i]][--p[from[i]]] = to[i]; } return g; } public static long[] radixSort(long[] f){ return radixSort(f, f.length); } public static long[] radixSort(long[] f, int n) { long[] to = new long[n]; { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>16&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>16&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>32&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>32&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>48&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>48&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } return f; } static class Pair { int a,b; public Pair(int a,int b) { this.a=a; this.b=b; } } static int bit[]; static void add(int x,int d,int n) { for(int i=x;i<=n;i+=i&-i)bit[i]+=d; } static int query(int x) { int ret=0; for(int i=x;i>0;i-=i&-i) ret+=bit[i]; return ret; } static long lcm(int a,int b) { long val=a; val*=b; return (val/gcd(a,b)); } static int gcd(int a,int b) { if(a==0)return b; return gcd(b%a,a); } static int pow(int a, int b, int p) { long ans = 1, base = a; while (b!=0) { if ((b & 1)!=0) { ans *= base; ans%= p; } base *= base; base%= p; b >>= 1; } return (int)ans; } static int inv(int x, int p) { return pow(x, p - 2, p); } void run() throws Exception { if(codechef)oj=true; is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception {new HR27().run();} private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
c16c3cf0a683f0ff85898c3b2a643d04
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; public class q1{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int test = scan.nextInt(); while(test-->0){ String str = scan.next(); int n = str.length(); char ch[] = str.toCharArray(); boolean res = true; if(n==1){ if(ch[0]!='?'){ System.out.println(str); continue; } else{ ch[0] ='a'; System.out.println(new String(ch)); continue; } } boolean pa = false; boolean pb = false; boolean pc = false; if(ch[0]=='?'){ if(ch[1]!='a'){ ch[0]='a'; } else if(ch[1]!='b'){ ch[0] = 'b'; } else { ch[0] = 'c'; } } for(int i=1;i<n;i++){ if(ch[i]==ch[i-1] ){ System.out.println("-1"); res = false; break; } else if(ch[i]=='?' && i+1<n){ if(ch[i-1]=='a' ){ if(ch[i+1]=='a'){ ch[i]='b'; } else if(ch[i+1]=='b'){ ch[i]='c'; } else if(ch[i+1]=='c'){ ch[i] ='b'; } else { ch[i] = 'b'; } } else if(ch[i-1]=='b'){ if(ch[i+1]=='a'){ ch[i]='c'; } else if(ch[i+1]=='b'){ ch[i]='a'; } else if(ch[i+1]=='c'){ ch[i] ='a'; } else { ch[i] = 'a'; } } else if(ch[i-1]=='c'){ if(ch[i+1]=='a'){ ch[i]='b'; } else if(ch[i+1]=='b'){ ch[i]='a'; } else if(ch[i+1]=='c'){ ch[i] ='a'; } else { ch[i] = 'a'; } } } else if(ch[i]=='?' && i+1>=n){ if(ch[i-1]=='a'){ ch[i] ='b'; } else if(ch[i-1]=='b'){ ch[i] ='a'; } else { ch[i] ='a'; } } } if(res == false){ continue; } String strin = new String(ch); System.out.println(strin); } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
dfc08328273393e89ace19d9d3847a57
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ProblemA { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { int number = Integer.parseInt(scanner.nextLine().trim()); for (int k = 0; k < number; k++) { String line = scanner.nextLine(); char[] chars = line.toCharArray(); int length = chars.length; Pattern p = Pattern.compile("(\\w)\\1+"); Matcher m = p.matcher(line); if (m.find()) { System.out.println("-1"); continue; } if (length == 1) { if (chars[0] == '?') { System.out.println("a"); continue; } else { System.out.println(chars[0]); } } if (length == 2) { char first = chars[0]; char second = chars[1]; if (first == '?' && second == '?') { System.out.println("ab"); } else if (first == second) { System.out.println("-1"); } else if (first == '?') { first = findSubstitute(second); System.out.println(first + "" + second); } else if (second == '?') { second = findSubstitute(first); System.out.println(first + "" + second); } else { System.out.println(first + "" + second); } continue; } for (int i = 0; i < length; i++) { if (chars[i] == '?' && i == 0) { chars[i] = findSubstitute(chars[i + 1]); } else if (chars[i] == '?' && i == length - 1) { if (chars[i - 1] == 'a') { chars[i] = 'b'; } if (chars[i - 1] == 'b') { chars[i] = 'c'; } if (chars[i - 1] == 'c') { chars[i] = 'b'; } } else if (chars[i] == '?') { chars[i] = findSubstitute(chars[i - 1], chars[i + 1]); } } System.out.println(new String(chars)); } } } private static char findSubstitute(char another) { if (another == 'a') { return 'b'; } if (another == 'b') { return 'c'; } if (another == 'c') { return 'a'; } if (another == '?') { return 'a'; } return 't'; } private static char findSubstitute(char prev, char next) { if (prev == 'a' && next == 'b') { return 'c'; } if (prev == 'a' && next == 'c') { return 'b'; } if (prev == 'b' && next == 'a') { return 'c'; } if (prev == 'b' && next == 'c') { return 'a'; } if (prev == 'c' && next == 'a') { return 'b'; } if (prev == 'c' && next == 'b') { return 'a'; } if (prev == 'a' && next == 'a') { return 'b'; } if (prev == 'b' && next == 'b') { return 'a'; } if (prev == 'c' && next == 'c') { return 'a'; } if (prev == 'a' && next == '?') { return 'b'; } if (prev == 'b' && next == '?') { return 'c'; } if (prev == 'c' && next == '?') { return 'a'; } return 't'; } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
342b8b2be3471e026f2ec822f1cad487
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; public class A{ public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int tc=Integer.parseInt(br.readLine()); int i; while(tc-->0) { char[] vec=br.readLine().toCharArray(); boolean hermoso=true; char aux=vec[0]; for(i=0;i<vec.length-1;i++) if(vec[i]!='?'&&vec[i]==vec[i+1]) { hermoso=false; break; } if(hermoso) { for(i=0;i<vec.length;i++) { if(i==0&&vec[i]=='?') { if(i+1<vec.length) { if(vec[i+1]=='a') vec[i]='b'; else if(vec[i+1]=='b') vec[i]='c'; else if(vec[i+1]=='c') vec[i]='a'; else vec[i]='a'; }else vec[i]='a'; }else { if(i+1<vec.length) { if(vec[i]=='?'&&vec[i+1]=='?') { if(vec[i-1]=='a') vec[i]='b'; else if(vec[i]=='b') vec[i]='c'; else vec[i]='a'; }else if(vec[i]=='?'&&vec[i+1]!='?') { if((vec[i-1]=='a'&&vec[i+1]=='b')||(vec[i-1]=='b'&&vec[i+1]=='a')){ vec[i]='c'; }else if((vec[i-1]=='a'&&vec[i+1]=='c')||(vec[i-1]=='c'&&vec[i+1]=='a')){ vec[i]='b'; }else if((vec[i-1]=='c'&&vec[i+1]=='b')||(vec[i-1]=='b'&&vec[i+1]=='c')){ vec[i]='a'; }else if((vec[i-1]=='a'&&vec[i+1]=='a')||(vec[i-1]=='a'&&vec[i+1]=='a')){ vec[i]='b'; }else if((vec[i-1]=='b'&&vec[i+1]=='b')||(vec[i-1]=='b'&&vec[i+1]=='b')){ vec[i]='a'; }else if((vec[i-1]=='c'&&vec[i+1]=='c')||(vec[i-1]=='c'&&vec[i+1]=='c')){ vec[i]='a'; } } }else if(i==vec.length-1&&vec[i]=='?') { if(vec[i-1]=='b') vec[i]='c'; else if(vec[i-1]=='a') vec[i]='b'; else vec[i]='a'; } } pw.append(vec[i]+""); } pw.append("\n"); }else pw.append(-1+"\n"); } pw.flush(); br.close(); pw.close(); } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
61db87068d0ccc754c657a6561dc3ff3
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); while(n-->0) { char[] arr=sc.next().toCharArray(); int l=arr.length; if(arr[0]=='?') { if(l>1) { if(arr[1]=='a'||arr[1]=='b') arr[0]='c'; else arr[0]='a'; } else arr[0]='a'; } int res=0; for(int i=1;i<l;i++) { if(arr[i]=='?') { if((i==(l-1))||arr[i+1]=='?') { if(arr[i-1]=='a'||arr[i-1]=='b') arr[i]='c'; else arr[i]='a'; } else { if(arr[i-1]=='a'&&arr[i+1]=='a') arr[i]='b'; if(arr[i-1]=='a'&&arr[i+1]=='c') arr[i]='b'; if(arr[i-1]=='a'&&arr[i+1]=='b') arr[i]='c'; if(arr[i-1]=='b'&&arr[i+1]=='a') arr[i]='c'; if(arr[i-1]=='b'&&arr[i+1]=='b') arr[i]='c'; if(arr[i-1]=='b'&&arr[i+1]=='c') arr[i]='a'; if(arr[i-1]=='c'&&arr[i+1]=='a') arr[i]='b'; if(arr[i-1]=='c'&&arr[i+1]=='b') arr[i]='a'; if(arr[i-1]=='c'&&arr[i+1]=='c') arr[i]='b'; } } if(arr[i]==arr[i-1]) { res=-1; break; } } if(res==0) System.out.println(arr); else System.out.println(res); } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
71c46c91f4352ffa70245e7ed9fa93d4
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Contest604_Div2_AProblem_ { static BufferedReader br; static StringBuilder ar; public static void main(String[] args) throws NumberFormatException, IOException { br = new BufferedReader(new InputStreamReader(System.in)); int cases = Integer.parseInt(br.readLine()); while(cases > 0) { solve(); cases--; } } private static void solve() throws IOException { ar = new StringBuilder(br.readLine()); //String ans = ""; char last = ' '; for (int i = 0; i < ar.length(); i++) { if(ar.charAt(i)=='?') { ar.setCharAt(i,'a'); if(ar.length()>1) { change(ar, i); } } } for(int i = 0; i < ar.length(); i++) { //ans+=ar.charAt(i); if(i>0 && last == ar.charAt(i)) { ar=new StringBuilder("-1"); break; }else { last=ar.charAt(i); } } System.out.println(ar); } private static StringBuilder change(StringBuilder ar, int i) { if(i==0) { if(ar.charAt(i+1)==ar.charAt(i)) { ar.setCharAt(i,'b'); } }else if(i == ar.length()-1) { if(ar.charAt(i-1)==ar.charAt(i)) { ar.setCharAt(i,'b'); } }else { if(ar.charAt(i-1)==ar.charAt(i)) { ar.setCharAt(i,'b'); if(ar.charAt(i+1)==ar.charAt(i)){ ar.setCharAt(i,'c'); } }else if(ar.charAt(i+1)==ar.charAt(i)){ ar.setCharAt(i,'b'); if(ar.charAt(i-1)==ar.charAt(i)){ ar.setCharAt(i,'c'); } } } return ar; } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
370d9e7ddf285a38d8120bc651e7e453
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Contest604_Div2_AProblem { static BufferedReader br; static String ar[]; public static void main(String[] args) throws NumberFormatException, IOException { br = new BufferedReader(new InputStreamReader(System.in)); int cases = Integer.parseInt(br.readLine()); while(cases > 0) { solve(); cases--; } } private static void solve() throws IOException { ar = br.readLine().split(""); String ans = ""; String last = null; for (int i = 0; i < ar.length; i++) { if(ar[i].equals("?")) { ar[i]="a"; if(ar.length>1) { change(ar, i); } } } for(int i = 0; i < ar.length; i++) { //ans+=ar[i]; if(i>0 && last.equals(ar[i])) { ans="-1"; break; }else { last=ar[i]; } } if(!ans.equals("-1")) { char[] x = new char[ar.length]; for (int i = 0; i < ar.length; i++) { x[i] = ar[i].charAt(0); } ans = new String(x); } System.out.println(ans); } private static String[] change(String[] ar, int i) { if(i==0) { if(ar[i+1].equals(ar[i])) { ar[i]="b"; } }else if(i == ar.length-1) { if(ar[i-1].equals(ar[i])) { ar[i]="b"; } }else { if(ar[i-1].equals(ar[i])) { ar[i]="b"; if(ar[i+1].equals(ar[i])){ ar[i]="c"; } }else if(ar[i+1].equals(ar[i])){ ar[i]="b"; if(ar[i-1].equals(ar[i])){ ar[i]="c"; } } } return ar; } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
1b8eaca865f508c069107de29c8a5c6e
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
//package com.company; import java.io.*; import java.util.*; import java.lang.*; public class Main{ public static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public char nextChar() { int c = read(); while (isSpaceChar(c)) c = read(); return (char)c; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a*b)/gcd(a, b); } static long func(long a[],long size,int s){ long max1=a[s]; long maxc=a[s]; for(int i=s+1;i<size;i++){ maxc=Math.max(a[i],maxc+a[i]); max1=Math.max(maxc,max1); } return max1; } public static void main(String args[]){ InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter w = new PrintWriter(outputStream); int t,i,j; t=in.nextInt(); for(i=0;i<t;i++){ String s=in.next(); char ch[]=s.toCharArray(); int n=s.length(),flag=0; for(j=1;j<n;j++){ if(ch[j]==ch[j-1]&&ch[j]!='?'){ flag=1; } } if(flag==1){ w.println(-1); continue; } for(j=1;j<n-1;j++){ if(ch[j]=='?'){ if(ch[j-1]=='a'){ if(ch[j+1]=='b'){ ch[j]='c'; }else{ ch[j]='b'; } } if(ch[j-1]=='b'){ if(ch[j+1]=='a'){ ch[j]='c'; }else{ ch[j]='a'; } } if(ch[j-1]=='c'){ if(ch[j+1]=='b'){ ch[j]='a'; }else{ ch[j]='b'; } } if(ch[j-1]=='?'){ if(ch[j+1]=='?'||ch[j+1]!='a'){ ch[j]='a'; }else{ ch[j]='b'; } } } } if(n>1){ if(ch[0]=='?'){ if(ch[1]=='a'){ ch[0]='b'; } if(ch[1]=='b'){ ch[0]='c'; } if(ch[1]=='c'){ ch[0]='b'; } } if(ch[n-1]=='?'){ if(ch[n-2]=='a'){ ch[n-1]='b'; } if(ch[n-2]=='b'){ ch[n-1]='c'; } if(ch[n-2]=='c'){ ch[n-1]='b'; } } } if(n==1){ ch[0]='a'; } if(n==2){ if(ch[0]=='?'&&ch[1]=='?'){ ch[0]='a'; ch[1]='b'; }else if(ch[0]=='?'||ch[1]=='?'){ if(ch[0]=='?'){ if(ch[1]=='a'){ ch[0]='b'; }else{ ch[0]='a'; } }if(ch[1]=='?'){ if(ch[0]=='a'){ ch[1]='b'; }else{ ch[1]='a'; } } } } w.println(ch); } w.close(); } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
29306dc6d50a25a44c6bfdc3c62ef70f
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { FastReader s = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int t=s.nextInt(); while(t-->0){ String st=s.next(); int w=0; for(int i=0;i<st.length()-1;i++){ if(st.charAt(i)!='?'&&(st.charAt(i)==st.charAt(i+1))){ System.out.println(-1); w=1; break; } } if(w==0){ char[] h=st.toCharArray(); char prev='z'; char next='y'; char[] letter=new char[3]; letter[0]='a'; letter[1]='b'; letter[2]='c'; for(int i=0;i<st.length();i++){ if(i>0) {prev=h[i-1];} if(i<st.length()-1) {next=h[i+1];} if(h[i]=='?'){ for(int it=0;it<3;it++){ if(prev!=letter[it]&&next!=letter[it]){ h[i]=letter[it]; break; } } } } String bg=String.valueOf(h); System.out.println(bg); } } } } 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\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
d9691823f8059d74e6d6356ca0413812
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Solver { public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); // br = new BufferedReader(new FileReader("data.in")); // PrintWriter pw = new PrintWriter("data.out"); int q = nextInt(); for (int i = 0; i < q; i++) { char[] a = next().toCharArray(); int cnt = 0; for (int j = 0; j < a.length - 1; j++) { if (a[j] == a[j + 1] && a[j] != '?') cnt++; } if (cnt == 0) { for (int j = 0; j < a.length - 1; j++) { if (j == 0) { if (a[j] == '?' && a[j + 1] == '?') a[j] = 'a'; else if (a[j] == '?' && a[j + 1] == 'a') a[j] = 'b'; else if (a[j] == '?' && a[j + 1] == 'b') a[j] = 'c'; else if (a[j] == '?' && a[j + 1] == 'c') a[j] = 'a'; } else { if (a[j - 1] == 'a' && a[j + 1] != 'c' && a[j] == '?')a[j] = 'c'; if (a[j - 1] == 'a' && a[j + 1] != 'b' && a[j] == '?')a[j] = 'b'; if (a[j - 1] == 'b' && a[j + 1] != 'a' && a[j] == '?')a[j] = 'a'; if (a[j - 1] == 'b' && a[j + 1] != 'c' && a[j] == '?')a[j] = 'c'; if (a[j - 1] == 'c' && a[j + 1] != 'a' && a[j] == '?')a[j] = 'a'; if (a[j - 1] == 'c' && a[j + 1] != 'b' && a[j] == '?')a[j] = 'b'; } } if (a.length != 1) { if (a[a.length - 1] == '?') { if (a[a.length - 2] == 'a') a[a.length - 1] = 'b'; if (a[a.length - 2] == 'b') a[a.length - 1] = 'c'; if (a[a.length - 2] == 'c') a[a.length - 1] = 'a'; } } else { if (a[a.length - 1] == '?') a[a.length - 1] = 'a'; } for (int j = 0; j < a.length; j++) { pw.print(a[j]); } pw.println(); } else { pw.println(-1); } } pw.close(); } static PrintWriter pw; static StringTokenizer st = new StringTokenizer(""); static BufferedReader br; static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
5f99c120c4f70021161b81045df56050
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.util.*; public class S { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++) { String s=sc.next(); StringBuilder sb=new StringBuilder(s); int flag=0; if(s.contains("aa") || s.contains("bb") || s.contains("cc")) { System.out.println(-1); flag=1; } else { // StringBuilder sb=new StringBuilder(s); for(int j=0;j<sb.length();j++) { if(sb.charAt(j)=='?') { if(j==0 && sb.length()==1) { sb.setCharAt(j,'a'); } else if(j==0 && sb.length()>1) { if(sb.charAt(j+1)=='?') { sb.setCharAt(j,'a'); } else if(sb.charAt(j+1)=='a') { sb.setCharAt(j,'b'); } else if(sb.charAt(j+1)=='b') { sb.setCharAt(j,'a'); } else if(sb.charAt(j+1)=='c') { sb.setCharAt(j,'a'); } } else if(j==sb.length()-1 && sb.length()>1) { if(sb.charAt(j-1)=='?') { sb.setCharAt(j,'a'); } else if(sb.charAt(j-1)=='a') { sb.setCharAt(j,'b'); } else if(sb.charAt(j-1)=='b') { sb.setCharAt(j,'a'); } else if(sb.charAt(j-1)=='c') { sb.setCharAt(j,'a'); } } else if(sb.length()>2) { if( sb.charAt(j+1)=='?' && sb.charAt(j-1)=='a') { sb.setCharAt(j,'b'); } else if(sb.charAt(j+1)=='?' && sb.charAt(j-1)=='b') { sb.setCharAt(j,'a'); } else if(sb.charAt(j+1)=='?' && sb.charAt(j-1)=='c') { sb.setCharAt(j,'a'); } ////////////////////////////////////////////////////////////// else if(sb.charAt(j+1)=='a' && sb.charAt(j-1)=='a') { sb.setCharAt(j,'b'); } else if(sb.charAt(j+1)=='b' && sb.charAt(j-1)=='a') { sb.setCharAt(j,'c'); } else if(sb.charAt(j+1)=='c' && sb.charAt(j-1)=='a') { sb.setCharAt(j,'b'); } ////////////////////////////////////////////////////////////// else if(sb.charAt(j+1)=='a' && sb.charAt(j-1)=='b') { sb.setCharAt(j,'c'); } else if(sb.charAt(j+1)=='b' && sb.charAt(j-1)=='b') { sb.setCharAt(j,'a'); } else if(sb.charAt(j+1)=='c' && sb.charAt(j-1)=='b') { sb.setCharAt(j,'a'); } ///////////////////////////////////////////////////////////// else if(sb.charAt(j+1)=='a' && sb.charAt(j-1)=='c') { sb.setCharAt(j,'b'); } else if(sb.charAt(j+1)=='b' && sb.charAt(j-1)=='c') { sb.setCharAt(j,'a'); } else if(sb.charAt(j+1)=='c' && sb.charAt(j-1)=='c') { sb.setCharAt(j,'a'); } } } } } if(flag==0) System.out.println(sb); } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
a548cd8e4a8ef74fab8211bd05a1d682
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String[] args) { FastScanner sc = new FastScanner(); int T = sc.nextInt(); PrintWriter pw = new PrintWriter(System.out); for(int t = 0; t < T; t++) { char[] s = sc.next().toCharArray(); int n = s.length; for(int i = 0; i < n; i++) { if(s[i] == '?') { HashSet<Character> set = new HashSet<>(); set.add('a'); set.add('b'); set.add('c'); if(i > 0) set.remove(s[i-1]); if(i < n-1) set.remove(s[i+1]); s[i] = set.iterator().next(); } } boolean no = false; for(int i = 1; i < n; i++) { if(s[i] == s[i-1]) { no = true; } } if(no) pw.println("-1"); else pw.println(new String(s)); } pw.flush(); } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
452971b227c6b9f1130fc67f6701a746
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; /** * Created by flk on 2019/12/8. */ public class Main { public static void main(String[] args) { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); Problem solver = new Problem(); solver.solve(in, out); out.flush(); } static class Problem { public void solve(InputReader in, PrintWriter out) { int t = in.nextInt(); while (t > 0) { String s = in.next(); StringBuilder res = new StringBuilder(""); boolean flag = true; for (int i = 0; i < s.length(); ++i) { char ch = s.charAt(i); Set<Character> set = new HashSet<>(); set.add('a'); set.add('b'); set.add('c'); if (ch == '?') { if (res.length() > 0) { set.remove(res.charAt(res.length() - 1)); } if (i < s.length() - 1 && s.charAt(i + 1) != '?') { set.remove(s.charAt(i + 1)); } for (Character c : set) { res.append(c); break; } } else { if (i > 0 && ch == s.charAt(i - 1)) { flag = false; break; } res.append(ch); } } if (flag) { out.println(res.toString()); } else { out.println(-1); } t--; } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
a67d6896cecdeca8917bd69f82cb91e9
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class A { private static String findVal(String a) { char[] ar = a.toCharArray(); int n = ar.length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { if (i < n - 1) { if (ar[i] != '?' && ar[i + 1] != '?') { if (ar[i + 1] == ar[i]) { return "-1"; } } } if (ar[i] == '?') { if (i == 0) { ar[i] = 'a'; if(i+1<n&&ar[i+1]=='a'){ ar[i]='b'; } } else { int pIdx = ar[i - 1] - 'a'; if (i == n - 1) { int cIdx = (pIdx + 1) % 3 + 'a'; ar[i] = (char) cIdx; } else { int bIdx = ar[i + 1]; int cIdx = (pIdx + 1) % 3 + 'a'; if (cIdx == bIdx) { cIdx = (bIdx -'a' + 1) % 3 + 'a'; } ar[i] = (char) cIdx; } } } sb.append(""+ar[i]); } return sb.toString(); } public static void main(String[] args) { // File file = new File("/Users/chihohar/IdeaProjects/CodeForce/input/input_a.txt"); // Scanner scan = null; // try { // scan = new Scanner(file); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } Scanner scan = new Scanner(System.in); int t = scan.nextInt(); for (int i = 0; i < t; i++) { String a = scan.next(); System.out.println(findVal(a)); } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
b8a946594109ab527e7c0eb640a5a3d5
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class A { private static String findVal(String a) { char[] ar = a.toCharArray(); int n = ar.length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { if (i < n - 1) { if (ar[i] != '?' && ar[i + 1] != '?') { if (ar[i + 1] == ar[i]) { return "-1"; } } } if (ar[i] == '?') { boolean[] choice = new boolean[3]; //a,b,c if(i>0){ choice[ar[i-1]-'a']=true; } if(i<n-1&&ar[i+1]!='?'){ choice[ar[i+1]-'a']=true; } for(int j=0;j<3;j++){ if(choice[j]==false){ ar[i]=(char) ('a'+j); } } } sb.append(""+ar[i]); } return sb.toString(); } public static void main(String[] args) { // File file = new File("/Users/chihohar/IdeaProjects/CodeForce/input/input_a.txt"); // Scanner scan = null; // try { // scan = new Scanner(file); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } Scanner scan = new Scanner(System.in); int t = scan.nextInt(); for (int i = 0; i < t; i++) { String a = scan.next(); System.out.println(findVal(a)); } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
ceae8e4359f5ccad69ca7ecf6f331bab
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class q4 { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(reader.readLine()); while(n-->0) { String tt=reader.readLine(); char arr[]=tt.toCharArray(); int ban=0; if(tt.length()==1) { System.out.println("a"); continue; } if (arr[0]=='?') { if (arr[1]=='a') arr[0]='b'; else { arr[0]='a'; } }int i=0; for( i=0;i<tt.length()-1;i++) { if(arr[i]==arr[i+1] && arr[i]!='?') { System.out.println(-1);ban=1; break; } if (arr[i]=='?') { if(arr[i-1]!='a' && arr[i+1]!='a') arr[i]='a'; else if(arr[i-1]!='b' && arr[i+1]!='b') arr[i]='b'; else if(arr[i-1]!='c' && arr[i+1]!='c') arr[i]='c'; } } if (ban==1) continue; if(arr[i]=='?') { if (arr[i-1]=='a') arr[i]='b'; else { arr[i]='a'; } } StringBuffer sb = new StringBuffer(); for (int k = 0; k < tt.length(); k++) sb.append(arr[k]); System.out.println(sb); } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
6eaafde052b698cd2d5ad4d8b7c31970
train_000.jsonl
1575556500
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; public class Solution { public static void main (String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); // String[] temp=br.readLine().trim().split(" "); int numTestCases=Integer.parseInt(br.readLine()); while(numTestCases-->0){ String str=br.readLine(); char[] ans=new char[str.length()]; for(int i=0;i<str.length();){ if(str.charAt(i)!='?') { ans[i]=str.charAt(i); i++; } else{ char addedCharacter; if(i-1>=0 && str.charAt(i-1)=='a'){ addedCharacter='b'; } else{ addedCharacter='a'; } int j=i; while(j<str.length() && str.charAt(j)=='?'){ ans[j]=addedCharacter; j++; addedCharacter=(addedCharacter=='a')?'b':'a'; } if(j<str.length() && str.charAt(j)==ans[j-1]){ if(j==1){ if(str.charAt(j)=='a'){ ans[j-1]='b'; } else if(str.charAt(j)=='b'){ ans[j-1]='a'; } else if(str.charAt(j)=='c'){ ans[j-1]='a'; } } else if(ans[j-2]!='a' && str.charAt(j)!='a'){ ans[j-1]='a'; } else if(ans[j-2]!='b' && str.charAt(j)!='b'){ ans[j-1]='b'; } else if(ans[j-2]!='c' && str.charAt(j)!='c'){ ans[j-1]='c'; } } i=j; } } int i=0; for(i=0;i<str.length()-1;i++){ if(ans[i]==ans[i+1]) { System.out.println(-1); break; } } if(i<str.length()-1){ continue; } for(i=0;i<str.length();i++){ System.out.print(ans[i]); } System.out.println(); } } }
Java
["3\na???cb\na??bbc\na?b?c"]
1 second
["ababcb\n-1\nacbac"]
NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".
Java 8
standard input
[ "constructive algorithms", "greedy" ]
98c08a3b5e5b5bb78804ff797ba24d87
The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.
1,000
For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
standard output
PASSED
636496ed547a8e979199c5a11fc29e3a
train_000.jsonl
1407690000
The game of bingo is played on a 5 × 5 square grid filled with distinct numbers between 1 and 75. In this problem you will consider a generalized version played on an n × n grid with distinct numbers between 1 and m (m ≥ n2). A player begins by selecting a randomly generated bingo grid (generated uniformly among all available grids). Then k distinct numbers between 1 and m will be called at random (called uniformly among all available sets of k numbers). For each called number that appears on the grid, the player marks that cell. The score at the end is 2 raised to the power of (number of completely marked rows plus number of completely marked columns).Determine the expected value of the score. The expected score may be very large. If the expected score is larger than 1099, print 1099 instead (for example as "1e99" without the quotes).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Popa Andrei */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(), M = in.nextInt(), K = in.nextInt(); double[][] Comb = new double[N + 1][N + 1]; for (int i = 0; i <= N; ++i) { Comb[i][0] = 1.0d; for (int j = 1; j <= i; ++j) Comb[i][j] = Comb[i - 1][j - 1] + Comb[i - 1][j]; } double[] P = new double[M + 1]; P[0] = 1.0d; for (int i = 1; i <= M; ++i) P[i] = P[i - 1] * (K - i + 1) / (M - i + 1); double Ans = 0.0d; for (int i = 0; i <= N; ++i) { for (int j = 0; j <= N; ++j) { int count = i * N + j * N - i * j; if (count <= K) Ans += Comb[N][i] * Comb[N][j] * P[count]; } } if (Ans > 1e99) out.println(1e99); else out.println(Ans); } } 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() { return Integer.parseInt(nextString()); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } }
Java
["1 2 1", "2 4 3", "7 59164 40872"]
1 second
["2.5", "4", "3.1415926538"]
null
Java 7
standard input
[ "combinatorics", "probabilities" ]
60f3c7528ee169be4ce63441802fec6b
Input will consist of three integers n, m, k (1 ≤ n ≤ 300; n2 ≤ m ≤ 100000; n ≤ k ≤ m).
2,700
Print the smaller of 1099 and the expected score. Your answer must be correct within an absolute or relative error of 10 - 9.
standard output
PASSED
5268bfd4e7eb0bace48658136d5a0a25
train_000.jsonl
1407690000
The game of bingo is played on a 5 × 5 square grid filled with distinct numbers between 1 and 75. In this problem you will consider a generalized version played on an n × n grid with distinct numbers between 1 and m (m ≥ n2). A player begins by selecting a randomly generated bingo grid (generated uniformly among all available grids). Then k distinct numbers between 1 and m will be called at random (called uniformly among all available sets of k numbers). For each called number that appears on the grid, the player marks that cell. The score at the end is 2 raised to the power of (number of completely marked rows plus number of completely marked columns).Determine the expected value of the score. The expected score may be very large. If the expected score is larger than 1099, print 1099 instead (for example as "1e99" without the quotes).
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); double[][] binom = new double[n + 1][n + 1]; for (int i = 0; i <= n; ++i) { binom[i][0] = 1; for (int j = 1; j <= i; ++j) { binom[i][j] = binom[i - 1][j - 1] + binom[i - 1][j]; } } double[] prob = new double[k + 1]; prob[0] = 1; for (int i = 1; i <= k; ++i) { prob[i] = prob[i - 1] * (k - i + 1) / (m - i + 1); } double answer = 0; for (int r = 0; r <= n; ++r) { for (int c = 0; c <= n; ++c) { int cell = (r + c) * n - r * c; if (cell > k) continue; answer += binom[n][r] * binom[n][c] * prob[cell]; } } answer = Math.min(answer, 1e99); out.printf("%.12e\n", answer); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { try { while(tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["1 2 1", "2 4 3", "7 59164 40872"]
1 second
["2.5", "4", "3.1415926538"]
null
Java 7
standard input
[ "combinatorics", "probabilities" ]
60f3c7528ee169be4ce63441802fec6b
Input will consist of three integers n, m, k (1 ≤ n ≤ 300; n2 ≤ m ≤ 100000; n ≤ k ≤ m).
2,700
Print the smaller of 1099 and the expected score. Your answer must be correct within an absolute or relative error of 10 - 9.
standard output
PASSED
5079180b41227bd60e3ee6357f9a921f
train_000.jsonl
1407690000
The game of bingo is played on a 5 × 5 square grid filled with distinct numbers between 1 and 75. In this problem you will consider a generalized version played on an n × n grid with distinct numbers between 1 and m (m ≥ n2). A player begins by selecting a randomly generated bingo grid (generated uniformly among all available grids). Then k distinct numbers between 1 and m will be called at random (called uniformly among all available sets of k numbers). For each called number that appears on the grid, the player marks that cell. The score at the end is 2 raised to the power of (number of completely marked rows plus number of completely marked columns).Determine the expected value of the score. The expected score may be very large. If the expected score is larger than 1099, print 1099 instead (for example as "1e99" without the quotes).
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); double[][] binom = new double[n + 1][n + 1]; for (int i = 0; i <= n; ++i) { binom[i][0] = 1; for (int j = 1; j <= i; ++j) { binom[i][j] = binom[i - 1][j - 1] + binom[i - 1][j]; } } double[] prob = new double[k + 1]; prob[0] = 1; for (int i = 1; i <= k; ++i) { prob[i] = prob[i - 1] * (k - i + 1) / (m - i + 1); } double answer = 0; for (int r = 0; r <= n; ++r) { for (int c = 0; c <= n; ++c) { int cell = (r + c) * n - r * c; if (cell > k) continue; answer += binom[n][r] * binom[n][c] * prob[cell]; } } answer = Math.min(answer, 1e99); out.println(answer); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { try { while(tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["1 2 1", "2 4 3", "7 59164 40872"]
1 second
["2.5", "4", "3.1415926538"]
null
Java 7
standard input
[ "combinatorics", "probabilities" ]
60f3c7528ee169be4ce63441802fec6b
Input will consist of three integers n, m, k (1 ≤ n ≤ 300; n2 ≤ m ≤ 100000; n ≤ k ≤ m).
2,700
Print the smaller of 1099 and the expected score. Your answer must be correct within an absolute or relative error of 10 - 9.
standard output
PASSED
2710c1a2f587f23cd6aa220f81141407
train_000.jsonl
1407690000
The game of bingo is played on a 5 × 5 square grid filled with distinct numbers between 1 and 75. In this problem you will consider a generalized version played on an n × n grid with distinct numbers between 1 and m (m ≥ n2). A player begins by selecting a randomly generated bingo grid (generated uniformly among all available grids). Then k distinct numbers between 1 and m will be called at random (called uniformly among all available sets of k numbers). For each called number that appears on the grid, the player marks that cell. The score at the end is 2 raised to the power of (number of completely marked rows plus number of completely marked columns).Determine the expected value of the score. The expected score may be very large. If the expected score is larger than 1099, print 1099 instead (for example as "1e99" without the quotes).
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); double[][] comb = new double[n + 1][n + 1]; comb[0][0] = 1; for (int i = 1; i <= n; ++i) { comb[i][0] = 1; for (int j = 1; j <= n; ++j) { comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; } } double[] prOne = new double[k + 1]; prOne[0] = 1.0; for (int i = 1; i <= k; ++i) { prOne[i] = prOne[i - 1] * (k - i + 1) / (m - i + 1); } double res = 0; for (int sum = 2 * n; sum >= 0; --sum) { for (int nrow = 0; nrow <= n; ++nrow) { int ncol = sum - nrow; if (ncol < 0 || ncol > n) continue; int totalCells = nrow * n + ncol * n - nrow * ncol; if (totalCells > k) continue; res += comb[n][nrow] * comb[n][ncol] * prOne[totalCells]; } } if (res > 1e99) res = 1e99; out.println(res); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["1 2 1", "2 4 3", "7 59164 40872"]
1 second
["2.5", "4", "3.1415926538"]
null
Java 7
standard input
[ "combinatorics", "probabilities" ]
60f3c7528ee169be4ce63441802fec6b
Input will consist of three integers n, m, k (1 ≤ n ≤ 300; n2 ≤ m ≤ 100000; n ≤ k ≤ m).
2,700
Print the smaller of 1099 and the expected score. Your answer must be correct within an absolute or relative error of 10 - 9.
standard output
PASSED
6a26aee361b014a60d163411fa218568
train_000.jsonl
1321337400
One day Anna got the following task at school: to arrange several numbers in a circle so that any two neighboring numbers differs exactly by 1. Anna was given several numbers and arranged them in a circle to fulfill the task. Then she wanted to check if she had arranged the numbers correctly, but at this point her younger sister Maria came and shuffled all numbers. Anna got sick with anger but what's done is done and the results of her work had been destroyed. But please tell Anna: could she have hypothetically completed the task using all those given numbers?
256 megabytes
import java.util.Map; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.util.HashMap; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.readInt(); int[] a = IOUtils.readIntArray(in, n); ArrayUtils.sort(a); int SHIFT = a[0]; for (int i = 0; i < n; ++i) { a[i] -= SHIFT; } if (a[n - 1] > n - 1) { out.println("NO"); return; } int[] freq = new int[n]; for (int i = 0; i < n; ++i) { freq[a[i]]++; } int HIGH = a[n - 1]; for (int i = HIGH; i >= 1; --i) { if (freq[i] <= 0) { out.println("NO"); return; } freq[i - 1] -= freq[i]; freq[i] = 0; } if (freq[0] == 0) { out.println("YES"); } else { out.println("NO"); } } } 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() { // InputMismatchException -> UnknownError if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } 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(); } else if (c == '+') { 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 static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] res = new int[size]; for (int i = 0; i < size; ++i) { res[i] = in.readInt(); } return res; } } class ArrayUtils { public static void sort(int[] a) { ArrayShuffler.shuffle(a); Arrays.sort(a); } } class ArrayShuffler { static Random random = new Random(7428429L); public static void shuffle(int[] p) { for (int i = 0; i < p.length; ++i) { int j = i + random.nextInt(p.length - i); int temp = p[i]; p[i] = p[j]; p[j] = temp; } } }
Java
["4\n1 2 3 2", "6\n1 1 2 2 2 3", "6\n2 4 1 1 2 2"]
2 seconds
["YES", "YES", "NO"]
null
Java 7
standard input
[ "constructive algorithms", "implementation" ]
de41c260a37ec9db2371efb9d246a470
The first line contains an integer n — how many numbers Anna had (3 ≤ n ≤ 105). The next line contains those numbers, separated by a space. All numbers are integers and belong to the range from 1 to 109.
2,000
Print the single line "YES" (without the quotes), if Anna could have completed the task correctly using all those numbers (using all of them is necessary). If Anna couldn't have fulfilled the task, no matter how hard she would try, print "NO" (without the quotes).
standard output
PASSED
361f6c6e955b146471145a7fe158fa0c
train_000.jsonl
1321337400
One day Anna got the following task at school: to arrange several numbers in a circle so that any two neighboring numbers differs exactly by 1. Anna was given several numbers and arranged them in a circle to fulfill the task. Then she wanted to check if she had arranged the numbers correctly, but at this point her younger sister Maria came and shuffled all numbers. Anna got sick with anger but what's done is done and the results of her work had been destroyed. But please tell Anna: could she have hypothetically completed the task using all those given numbers?
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeSet; 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); new TaskC().solve(in, out); out.close(); } } class TaskC { static final long mod=1000000009; public void solve(InputReader in,PrintWriter out) { int n=in.nextInt(); int[] d=new int[n]; TreeSet<Integer> se=new TreeSet<Integer>(); for(int i=0;i<n;i++) { d[i]=in.nextInt(); se.add(d[i]); } int[] y=d.clone(); Arrays.sort(d); boolean flag=true; for(int i=0;i<n-1;i++) { if(d[i+1]-d[i]>1) { flag=false; break; } } if(!flag) { out.println("NO"); return; } ArrayList<Integer> arr=new ArrayList<Integer>(); while(!se.isEmpty()) { arr.add(se.pollFirst()); } Object[] p=arr.toArray(); int mx=0; for(int i=0;i<n;i++) { y[i]=Arrays.binarySearch(p,y[i]); mx=Math.max(mx, y[i]); } int[] num=new int[n]; for(int i=0;i<y.length;i++) { num[(int) y[i]]++; } for(int i=0;i<mx;i++) { if(num[i]<=0){ flag=false; break; } else { num[i+1]-=num[i]; num[i]=0; } } if(!flag || num[mx]!=0) { out.println("NO"); } else { out.println("YES"); } } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["4\n1 2 3 2", "6\n1 1 2 2 2 3", "6\n2 4 1 1 2 2"]
2 seconds
["YES", "YES", "NO"]
null
Java 7
standard input
[ "constructive algorithms", "implementation" ]
de41c260a37ec9db2371efb9d246a470
The first line contains an integer n — how many numbers Anna had (3 ≤ n ≤ 105). The next line contains those numbers, separated by a space. All numbers are integers and belong to the range from 1 to 109.
2,000
Print the single line "YES" (without the quotes), if Anna could have completed the task correctly using all those numbers (using all of them is necessary). If Anna couldn't have fulfilled the task, no matter how hard she would try, print "NO" (without the quotes).
standard output
PASSED
26d8ce2f2b4cf2258d5638a7f84ea2c8
train_000.jsonl
1321337400
One day Anna got the following task at school: to arrange several numbers in a circle so that any two neighboring numbers differs exactly by 1. Anna was given several numbers and arranged them in a circle to fulfill the task. Then she wanted to check if she had arranged the numbers correctly, but at this point her younger sister Maria came and shuffled all numbers. Anna got sick with anger but what's done is done and the results of her work had been destroyed. But please tell Anna: could she have hypothetically completed the task using all those given numbers?
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.Arrays; import java.util.StringTokenizer; public class D94 { static StringTokenizer st; static BufferedReader in; static PrintWriter pw; public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int[]a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } Arrays.sort(a); int[]cnt = new int[n]; int m = a[n-1]-a[0]; if (n % 2==1 || m > n/2 || m==0) { System.out.println("NO"); return; } for (int i = 0; i < n; i++) { cnt[a[i]-a[0]]++; } int L = cnt[0]-1; for (int i = 1; i < m; i++) { if (cnt[i] < L+2) { System.out.println("NO"); return; } cnt[i] -= (L+2); L = cnt[i]; } if (L != cnt[m]-1) System.out.println("NO"); else System.out.println("YES"); 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(in.readLine()); } return st.nextToken(); } }
Java
["4\n1 2 3 2", "6\n1 1 2 2 2 3", "6\n2 4 1 1 2 2"]
2 seconds
["YES", "YES", "NO"]
null
Java 7
standard input
[ "constructive algorithms", "implementation" ]
de41c260a37ec9db2371efb9d246a470
The first line contains an integer n — how many numbers Anna had (3 ≤ n ≤ 105). The next line contains those numbers, separated by a space. All numbers are integers and belong to the range from 1 to 109.
2,000
Print the single line "YES" (without the quotes), if Anna could have completed the task correctly using all those numbers (using all of them is necessary). If Anna couldn't have fulfilled the task, no matter how hard she would try, print "NO" (without the quotes).
standard output
PASSED
ca94337e5ee9b0ef7b226cc2408393ed
train_000.jsonl
1321337400
One day Anna got the following task at school: to arrange several numbers in a circle so that any two neighboring numbers differs exactly by 1. Anna was given several numbers and arranged them in a circle to fulfill the task. Then she wanted to check if she had arranged the numbers correctly, but at this point her younger sister Maria came and shuffled all numbers. Anna got sick with anger but what's done is done and the results of her work had been destroyed. But please tell Anna: could she have hypothetically completed the task using all those given numbers?
256 megabytes
import java.util.*; public class Main { private static boolean solve() { Scanner cin = new Scanner(System.in); int N = 0; int list[] = new int[100010]; int cnt[] = new int[100010]; int minNum = 1000000001; int maxNum = -1; N = cin.nextInt(); for (int i = 0; i < N; i++) { list[i] = cin.nextInt(); if (list[i] < minNum) { minNum = list[i]; } if (list[i] > maxNum) { maxNum = list[i]; } } for (int i = 0; i < N; i++) { if (list[i] - (minNum - 1) >= 100010) { return false; } cnt[list[i] - (minNum - 1)]++; } maxNum -= (minNum - 1); /** step 1. go ascend to maxNum */ for (int i = 1; i < maxNum; i++) { //System.err.println("cnt " + i + " = " + cnt[i]); if (cnt[i] <= 0) { System.err.println("step 1"); return false; } else { cnt[i]--; } } /** step 2. eliminate from max to 1 */ for (int max = maxNum; max > 1; max--) { if (cnt[max] > 0) { if (cnt[max - 1] < cnt[max] - 1) { System.err.println("step 2: " + max); return false; } cnt[max - 1] -= cnt[max] - 1; cnt[max] = 0; } else { System.err.println("step 2: " + max); return false; } } /** step 3. check cnt[1] */ for (int i = 1; i <= maxNum; i++) { if (cnt[i] != 0) { System.err.println("step 3: " + i + " " + cnt[i]); return false; } } return true; } public static void main(String[] args) { if (solve()) { System.out.println("YES"); } else { System.out.println("NO"); } } }
Java
["4\n1 2 3 2", "6\n1 1 2 2 2 3", "6\n2 4 1 1 2 2"]
2 seconds
["YES", "YES", "NO"]
null
Java 7
standard input
[ "constructive algorithms", "implementation" ]
de41c260a37ec9db2371efb9d246a470
The first line contains an integer n — how many numbers Anna had (3 ≤ n ≤ 105). The next line contains those numbers, separated by a space. All numbers are integers and belong to the range from 1 to 109.
2,000
Print the single line "YES" (without the quotes), if Anna could have completed the task correctly using all those numbers (using all of them is necessary). If Anna couldn't have fulfilled the task, no matter how hard she would try, print "NO" (without the quotes).
standard output
PASSED
cdee7c9b59d8fa3dc3239f6c28c018ca
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author caoash */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); BArrayKColoring solver = new BArrayKColoring(); solver.solve(1, in, out); out.close(); } static class BArrayKColoring { public void solve(int testNumber, FastScanner br, PrintWriter pw) { int n = br.nextInt(); int k = br.nextInt(); Pair[] data = new Pair[n]; for (int i = 0; i < data.length; i++) { data[i] = new Pair(br.nextInt(), i); } Arrays.sort(data); int[] fin = new int[n]; int curr = 1; for (int i = 0; i < n; i++) { fin[i] = curr++; if (curr == k + 1) { curr = 1; } } int[] ret = new int[n]; boolean[][] used = new boolean[5001][5001]; for (int i = 0; i < n; i++) { ret[data[i].s] = fin[i]; } // for(int i = 0; i < n; i++){ // pw.print(ret[i] + " "); // } // pw.println(); for (int i = 0; i < n; i++) { if (used[data[i].f][fin[i]]) { pw.println("NO"); pw.close(); return; } else { used[data[i].f][fin[i]] = true; } } pw.println("YES"); for (int i = 0; i < n; i++) { pw.print(ret[i] + " "); } pw.close(); } } static class Pair implements Comparable<Pair> { public int f; public int s; public Pair(int f, int s) { this.f = f; this.s = s; } public int compareTo(Pair p) { return this.f == p.f ? this.s - p.s : this.f - p.f; } public String toString() { return "(" + f + "," + s + ")"; } } static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastScanner.SpaceCharFilter filter; public FastScanner(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
7b82eb711cb5d8f6c05765177fe843ed
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.util.*; import java.io.*; public class coloring{ public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); Scanner scan = new Scanner(System.in); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); StringTokenizer st = new StringTokenizer(bf.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); st = new StringTokenizer(bf.readLine()); int[] array = new int[n]; int[] print = new int[n]; int start=1; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0; i<n; i++){ array[i] = Integer.parseInt(st.nextToken()); print[i] = array[i]; } Arrays.sort(print); int curr=array[0]; map.put(print[0],1); int count=0; for(int i=0; i<n; i++){ if(print[i]!=curr){ map.put(print[i],i+1); curr=print[i]; } } curr=array[0]; for(int i=0; i<n; i++){ if(print[i]!=curr){ count=1; curr=print[i]; }else count++; if(count>k){ out.println("NO"); out.close(); System.exit(0); } } out.println("YES"); for(int i=0; i<n; i++){ if(map.get(array[i])%k==0){ out.print(k + " "); }else out.print(map.get(array[i])%k+ " "); map.put(array[i],map.get(array[i])+1); } out.println(""); out.close(); } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
9f142c1df55c0cc9dfc5f5623852a509
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.util.*; import java.io.*; //import javafx.util.Pair; public class Solution implements Runnable { class Pair implements Comparable <Pair> { long x,y; Pair(long x,long y) { this.x=x; this.y=y; } public int compareTo(Pair p) { return Long.compare(x,p.x); } } public static void main(String[] args) { new Thread(null, new Solution(), "rev", 1 << 29).start(); } public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1,in,out); out.close(); } class Task { void solve(int testNumber, InputReader in, PrintWriter out) { int n=in.nextInt(); int k=in.nextInt(),x; ArrayList <Integer>adj[]=new ArrayList[5001]; for(int i=1;i<=5000;i++) adj[i]=new ArrayList<>(); int []a=new int[n]; for(int i=0;i<n;i++) { x=in.nextInt(); adj[x].add(i); if(adj[x].size()>k) { out.println("NO"); return; } } out.println("YES"); x=1; for(int i=1;i<=5000;i++) { for(int j:adj[i]) { a[j]=(x%k==0)?k:x%k; x++; } } for(int i=0;i<n;i++) out.print(a[i]+" "); } } } 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 long[] nextLongArray(int n) { long a[]=new long[n]; for(int i=1; i<n; i++) a[i]=nextLong(); return a; } public String nextString() { 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 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
49b7af0fb791834c1d4071765819ebd5
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(), k = scan.nextInt(); int[] arr = new int[5001];Arrays.fill(arr, 0); Integer[][] arr1 = new Integer[n][2]; for(int i=0;i<n;i++) { int num = scan.nextInt()-1; arr[num]++; arr1[i][0]=num; arr1[i][1]=i; } Arrays.sort(arr1,new Comparator<Integer[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { return o1[0]-o2[0]; } }); int max=-1; for(int i=0;i<5001;i++) max = Math.max(arr[i], max); if (max>k) { System.out.println("NO"); } else { System.out.println("YES"); int i1=0; for (int i=0;i<arr1.length;i++) { arr1[i][0]=++i1; if(i1==k)i1=0; } Arrays.sort(arr1, new Comparator<Integer[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { return o1[1]-o2[1]; } }); for(Integer[] a:arr1) { System.out.print(a[0] + " "); } System.out.println(); } scan.close(); } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
90498ab01bf5b0b099f42fa6a666c28c
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void solve(InputReader in ) { int n = in.readInt(), k = in.readInt(); int a[] = new int[n]; int ans[] = new int[n]; int cnt[] = new int[50001]; for(int i = 0; i<n; i++) a[i] = in.readInt(); int Max = 0; for(int i = 0; i<n; i++) { if(Max + (n-i) == k) ans[i] = Max+1; else { cnt[a[i]]++; if(cnt[a[i]] > k ) { System.out.println("NO"); return; } ans[i] = cnt[a[i]]; } Max = Math.max(Max, ans[i]); } System.out.println("YES"); for(int i : ans) System.out.print(i + " "); System.out.println(); } public static void main(String[] args) { InputReader in = new InputReader(System.in); int t = 1; while (t-- > 0) solve(in); } } class InputReader{ private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
a89ee530701578e0604524efb52b01fa
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import java.util.Set; public class ArrayKcoloring1102_B { public static void main(String[] args) { Scanner s=new Scanner (System.in); int n=s.nextInt(); int k=s.nextInt(); int[] array=new int[n]; HashMap<Integer,ArrayList<Integer>> map=new HashMap<>(); for (int i=0;i<n;i++) { array[i]=s.nextInt(); if (map.containsKey(array[i])) { map.get(array[i]).add(i); } else { ArrayList<Integer> temp=new ArrayList<>(); temp.add(i); map.put(array[i],temp); } } s.close(); Set<Integer> keys=map.keySet(); int c=1; for (int i : keys) { if (map.get(i).size()>k) { System.out.println("NO"); return; } for (int j=0;j<map.get(i).size();j++) { if (c>k) c=1; array[map.get(i).get(j)]=c; c++; } } System.out.println("YES"); for (int i:array) System.out.print(i+" "); } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
55706d058c74c6975879b605ebf28fae
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws IOException { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int k = scn.nextInt(); int a[] = new int[n]; HashMap<Integer, Integer> hm = new HashMap<>(); for (int i = 0; i < n; i++) { a[i] = scn.nextInt(); hm.put(a[i], hm.getOrDefault(a[i], 0) + 1); } int max = Collections.max(hm.values()); if (max > k || (hm.size() == 1 && max != k)) { System.out.println("NO"); return; } int pv = k; for (int v : hm.keySet()) { int f = hm.get(v); if (f >= pv) { pv = 0; break; } hm.put(v, pv); pv = pv - f; } if (pv >= 1) { System.out.println("NO"); return; } System.out.println("YES"); for (int i = 0; i < n; i++) { System.out.print(hm.get(a[i]) + " "); hm.put(a[i], hm.get(a[i]) - 1); } } 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()); } } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
ee4e1ce47846927a43c2e3216b5a0a41
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
//package com.company; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner s=new Scanner(System.in); //BufferedReader s=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int n=s.nextInt();int k=s.nextInt();int[] ans=new int[n];int flag=0;int [] c=new int[n];int[] count=new int[5001]; Student[] a=new Student[n]; for(int i=0;i<n;i++){ a[i]=new Student(s.nextInt(),i); } Arrays.sort(a,new Sortbyroll()); for(int i=0;i<n;i++){ if(i==0 ) ans[a[i].r]=1;else ans[a[i].r]=ans[a[i-1].r]+1; if(ans[a[i].r]>k) ans[a[i].r]=1; count[a[i].l]++; if(count[a[i].l]>k) { flag=1;break; } } if(flag==1) System.out.println("NO"); else{ System.out.println("YES"); for(int i=0;i<n;i++) sb.append(ans[i]+" "); System.out.println(sb.toString()); } }static int[] vis; static double power(double x, long y, int p) { double res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static void fracion(double x) { String a = "" + x; String spilts[] = a.split("\\."); // split using decimal int b = spilts[1].length(); // find the decimal length int denominator = (int) Math.pow(10, b); // calculate the denominator int numerator = (int) (x * denominator); // calculate the nerumrator Ex // 1.2*10 = 12 int gcd = gcd(numerator, denominator); // Find the greatest common // divisor bw them String fraction = "" + numerator / gcd + "/" + denominator / gcd; // System.out.println((denominator/gcd)); long x1=modInverse(denominator / gcd,998244353 ); // System.out.println(x1); System.out.println((((numerator / gcd )%998244353 *(x1%998244353 ))%998244353 ) ); }static int max=Integer.MIN_VALUE; static int max1=Integer.MIN_VALUE;static int[] ans; public static int dfs(int papa, int i, ArrayList<Integer>[] h, int[] vis) { vis[i] = 1; if(h[i]==null){ans[i]=1; return 1;} for(Integer j:h[i]){ if(vis[j]==1) { ans[i]+=ans[j]; }else{ ans[i]+=dfs(papa,j,h,vis); } }ans[i]+=1;if(ans[i]>max){ max=ans[i];max1=i; } return ans[i]; } public static void bfs(int i, HashMap<Integer, Integer>[] h, int[] vis, int len, int papa) { Queue<Integer> q = new LinkedList<Integer>(); q.add(i); } static int i(String a) { return Integer.parseInt(a); } static long l(String a) { return Long.parseLong(a); } static String[] inp() throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); return s.readLine().trim().split("\\s+"); } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long modInverse(int a, int m) { { // If a and m are relatively prime, then modulo inverse // is a^(m-2) mode m return (power(a, m - 2, m)); } } // To compute x^y under modulo m static long power(int x, int y, int m) { if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } // Function to return gcd of a and b } class Student { int l,r; public Student(int l, int r) { this.l = l; this.r = r; } // Constructor // Used to print student details in main() public String toString() { return this.l+" "; } } class Sortbyroll implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student a, Student b){ return a.l-b.l; } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
eb26849f523a64d369c35a4881493961
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.util.*; public class Eighteen { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int k=s.nextInt(); int flag; int input[][]=new int[n][2]; for(int i=0;i<n;i++){ input[i][0]=s.nextInt(); } for(int i=1;i<=k;i++){ input[i-1][1]=i; } for(int j=1;j<=k;j++){ for(int i=k;i<n;i++){ flag=0; if(input[i][1]==0){ if(input[j-1][0]!=input[i][0]){ for(int l=k;l<i;l++){ if(input[l][0]==input[i][0]&&input[l][1]==j){ flag=1; break; } } if(flag==0){ input[i][1]=j; } } } } } flag=0; for(int i=0;i<n;i++){ if(input[i][1]==0){ flag=1; break; } } if(flag==0){ System.out.println("YES"); for(int i=0;i<n;i++){ System.out.print(input[i][1]+" "); } } else{ System.out.println("NO"); } } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
5917298db70b107a7237feab7d9244ea
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
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.Arrays; import java.util.Map; import java.util.Scanner; import java.util.HashMap; import java.util.Comparator; import java.util.ArrayList; /** * 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(); int k = in.nextInt(); E[] es = new E[n]; Map<Integer, List<Integer>> mp = new HashMap<Integer, List<Integer>>(); for (int i = 0; i < n; i++) { int v = in.nextInt(); es[i] = new E(v, i); } int[] res = new int[n]; Arrays.sort(es, new Comparator<E>() { public int compare(E o1, E o2) { return o1.val - o2.val; } }); int cur_color = 1; for (int i = 0; i < n; i++) { int idx = es[i].idx; int v = es[i].val; List<Integer> l = null; if (!mp.containsKey(v)) l = new ArrayList<Integer>(); else l = mp.get(v); l.add(idx); mp.put(v, l); } for (int v : mp.keySet()) { List<Integer> idx_l = mp.get(v); if (idx_l.size() > k) { out.println("NO"); return; } for (int idx : idx_l) { res[idx] = (cur_color) % k + 1; cur_color++; } } if (cur_color < k) { out.println("NO"); return; } out.println("YES"); for (int i = 0; i < n; i++) { out.print(res[i]); if (i < n - 1) out.print(" "); } out.println(); } class E { int val; int idx; public E(int val, int idx) { this.val = val; this.idx = idx; } } } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
ea620525675e5e53175c215ee46463bc
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.util.Scanner; public class ArrayKColoring { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int[] ans = new int[n], ar = new int[n]; for(int i = 0; i < n; i++) ar[i] = in.nextInt()-1; boolean used[][] = new boolean[5000][k]; for(int i = 0; i < k; i++) { ans[i] = i; used[ar[i]][i] = true; } for(int i = k; i < n; i++) { boolean good = false; for(int j = 0; j < k; j++) { if(!used[ar[i]][j]) { used[ar[i]][j] = true; good = true; ans[i] = j; break; } } if(!good) { System.out.println("NO"); return; } } System.out.println("YES"); for(int x : ans) { System.out.print((x+1) + " "); } } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
76397168d6f0f3f773e7171fe4f4c4db
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class Main { public static void main(String args[]) { try{ new Solve().start(); } catch(Exception e) { System.out.println(e); System.exit(1); } } } class Solve { void start() { run(); } void run() { Scanner sc =new Scanner(System.in); int n =sc.nextInt(); int k = sc.nextInt(); int arr[][] = new int[5007][5007]; int index[] =new int [5007]; for(int i =0 ; i <5007 ;i++) index[i]=0; int ans [] = new int [n+1]; for(int i = 1 ; i <= n ; i++ ) { int input; input = sc.nextInt(); arr[input][index[input]]=i; index[input]++; } int k1=1; for(int i=0; i<5004; i++) { if(index[i] > k) { System.out.println("NO"); return; } for(int j=0;j < index[i];j++) { if(k1>k) k1=1; ans[arr[i][j]]=k1; k1++; } } System.out.println("YES"); for(int i =1;i<=n;i++) System.out.print(ans[i] + " "); } } class Tools { }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
b051b8596c44ef333a7a43463eb4791e
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class Main { public static void main(String args[]) { try{ new Solve().start(); } catch(Exception e) { System.out.println(e); System.exit(1); } } } class Solve extends Thread { public void run() { try { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int arr[][] = new int[5007][5007]; int index[] = new int[5007]; for (int i = 0; i < 5007; i++) index[i] = 0; int ans[] = new int[n + 1]; for (int i = 1; i <= n; i++) { int input; input = sc.nextInt(); arr[input][index[input]] = i; index[input]++; } int k1 = 1; for (int i = 0; i < 5004; i++) { if (index[i] > k) { System.out.println("NO"); return; } for (int j = 0; j < index[i]; j++) { if (k1 > k) k1 = 1; ans[arr[i][j]] = k1; k1++; } } System.out.println("YES"); String res=""; for (int i = 1; i <= n; i++) res=res + ans[i] + " "; System.out.print(res); } catch (Exception e) { System.out.print(e); } } } class Tools { }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
f02b60a441a021000942168c9f1033cb
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class Main { public static void main(String args[]) { try{ new Solve().start(); } catch(Exception e) { System.out.println(e); System.exit(1); } } } class Solve { void start() { run(); } void run() { Scanner sc =new Scanner(System.in); int n =sc.nextInt(); int k = sc.nextInt(); int arr[][] = new int[5007][5007]; int index[] =new int [5007]; for(int i =0 ; i <5007 ;i++) index[i]=0; int ans [] = new int [n+1]; for(int i = 1 ; i <= n ; i++ ) { int input; input = sc.nextInt(); arr[input][index[input]]=i; index[input]++; } for( int i =1 ; i < 5007 ; i++ ) { if(index[i] > k) { System.out.println("NO"); return; } } int k1=1; System.out.println("YES"); for(int i=0; i<5007; i++) { for(int j=0;j < index[i];j++) { if(k1>k) k1=1; ans[arr[i][j]]=k1; k1++; } } for(int i =1;i<=n;i++) System.out.print(ans[i] + " "); } } class Tools { }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
f705ed066beddb91c2ee7b85fb888115
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class Main { public static void main(String args[]) { try{ new Solve().start(); } catch(Exception e) { System.out.println(e); System.exit(1); } } } class Solve { void start() { run(); } void run() { Scanner sc =new Scanner(System.in); int n =sc.nextInt(); int k = sc.nextInt(); int arr[][] = new int[5007][5007]; int hash []=new int [5007]; int index[] =new int [5007]; for(int i =0 ; i <5007 ;i++) index[i]=0; int ans [] = new int [n+1]; for(int i = 1 ; i <= n ; i++ ) { int input; input = sc.nextInt(); arr[input][index[input]]=i; index[input]++; hash[input]++; } for( int i =1 ; i < 5007 ; i++ ) { if(hash[i] > k) { System.out.println("NO"); return; } } int k1=1; System.out.println("YES"); for(int i=0; i<5007; i++) { for(int j=0;j < index[i];j++) { if(k1>k) k1=1; ans[arr[i][j]]=k1; k1++; } } for(int i =1;i<=n;i++) System.out.print(ans[i] + " "); } } class Tools { }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
ca81bb1e9f01771c54b824444e084443
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class Main { public static void main(String args[]) { try{ new Solve().start(); } catch(Exception e) { System.out.println(e); System.exit(1); } } } class Solve extends Thread { public void run() { try { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int arr[][] = new int[5007][5007]; int index[] = new int[5007]; for (int i = 0; i < 5007; i++) index[i] = 0; int ans[] = new int[n + 1]; for (int i = 1; i <= n; i++) { int input; input = sc.nextInt(); arr[input][index[input]] = i; index[input]++; } int k1 = 1; for (int i = 0; i < 5004; i++) { if (index[i] > k) { System.out.println("NO"); return; } for (int j = 0; j < index[i]; j++) { if (k1 > k) k1 = 1; ans[arr[i][j]] = k1; k1++; } } System.out.println("YES"); for (int i = 1; i <= n; i++) System.out.print(ans[i] + " "); } catch (Exception e) { System.out.print(e); } } } class Tools { }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
70bc509794ff90d6819ebb004b9c56f3
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; //import java.math.*; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class Node implements Comparable<Node> { public int val; public int col; public int pos; public Node(int val) { this.val = val; this.pos=0; this.col=0; } @Override public int compareTo(Node o) { return (int)(this.val - o.val); } public double getVal() { return val; } } static int MD= 998244353 ; static int N=300000; public static void main(String[] args) throws IOException { OutputStream outputStream = System.out; InputReader in = new InputReader(); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException { int t=1; while(t-->0) { int n=in.nextInt(); int k=in.nextInt(); int c=0; Node[] arr=new Node[n]; for(int i=0;i<n;i++) { arr[i]=new Node(in.nextInt()); arr[i].pos=i; } Arrays.sort(arr); arr[0].col=1; int b=1; for(int i=1;i<n;i++) { if(arr[i].val==arr[i-1].val) { arr[i].col=Math.max(1,(arr[i-1].col+1)%(k+1)); b++; } else { b=1; arr[i].col=Math.max(1,(arr[i-1].col+1)%(k+1)); } if(b>k) { out.println("NO"); c++; break; } } if(c==0) { sort(arr,0,n); out.println("YES"); for(int i=0;i<n;i++) { out.print(arr[i].col+" "); } out.println(); } } } } static long modexp(long x, long n) { if (n == 0) { return 1; } else if (n % 2 == 0) { return modexp((x * x) % MD, n / 2); } else { return (x * modexp((x * x) % MD, (n - 1) / 2) % MD); } } static long getInv(long b) { long d = modexp(b, MD - 2); long ans = (d % MD) ; return ans; } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader() { 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 sort(Node[] a, int low, int high) { int N = high - low; if (N <= 1) return; int mid = low + N/2; // recursively sort sort(a, low, mid); sort(a, mid, high); // merge two sorted subarrays Node[] temp = new Node[N]; int i = low, j = mid; for (int k = 0; k < N; k++) { if (i == mid) temp[k] = a[j++]; else if (j == high) temp[k] = a[i++]; else if (a[j].pos<a[i].pos) temp[k] = a[j++]; else temp[k] = a[i++]; } for (int k = 0; k < N; k++) a[low + k] = temp[k]; } static void lsort(long[] a, int low, int high) { int N = high - low; if (N <= 1) return; int mid = low + N/2; lsort(a, low, mid); lsort(a, mid, high); long[] temp = new long[N]; int i = low, j = mid; for (int k = 0; k < N; k++) { if (i == mid) temp[k] = a[j++]; else if (j == high) temp[k] = a[i++]; else if (a[j]<a[i]) temp[k] = a[j++]; else temp[k] = a[i++]; } for (int k = 0; k < N; k++) a[low + k] = temp[k]; } public static long fexp(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long lgcd(long a, long b) { if (b == 0) return a; return lgcd(b, a % b); } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
a53843b152f95ea89dc9964aaf878fbf
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
/** * */ import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * @author moham * */ public class B { /** * @param args */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(), k = scanner.nextInt(); int[] numberColour = new int[n + 1]; // ArrayList<List<Integer>> colours = new ArrayList<List<Integer>>(); boolean[][] colours = new boolean[5001][k]; // int[] lastIndexColours = new int[k + 1]; int temp; // for (int i = 0; i < n + 1; i++) { //// colours.add(IntStream.rangeClosed(0, k).boxed().collect(Collectors.toList())); // List<Integer> list = new LinkedList<>(); // for (int j = 0; j <= k; j++) { // list.add(j); // } // colours.add(list); // } for (int i = 0; i < n; i++) { temp = scanner.nextInt(); int index = getTrue(colours[temp]); if (index == -1) { System.out.println("NO"); return; } if (i < k) { numberColour[i] = i + 1; colours[temp][i] = true; continue; } // numberColour[i] = colours.get(temp).remove(colours.get(temp).size() - 1); numberColour[i] = index + 1; colours[temp][index] = true; } System.out.println("YES"); for (int i = 0; i < n; i++) { System.out.print(numberColour[i] + " "); } } static int getTrue(boolean[] numbers) { for (int i = 0; i < numbers.length; i++) { if (!numbers[i]) { // numbers[i] = true; return i; } } return -1; } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
ec37f3743ae8a1847bc29d58f01004f4
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
/** * Date: 12 Jan, 2019 * Link: * * @author Prasad-Chaudhari * @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/ * @git: https://github.com/Prasad-Chaudhari */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class newProgram8 { public static void main(String[] args) throws IOException { // TODO code application logic here FastIO in = new FastIO(); int n = in.ni(); int k = in.ni(); int a[] = in.gia(n); int c[] = new int[n]; ArrayList<Set<Integer>> s = new ArrayList<>(); for (int i = 0; i <= 5000; i++) { s.add(new HashSet<>()); } boolean b[] = new boolean[n]; int color[] = new int[5001]; for (int i = 0; i < k; i++) { s.get(a[i]).add(i); c[i] = i + 1; } for (int i = k; i < n; i++) { for (int j = 0; j < k; j++) { if (!s.get(a[i]).contains(j)) { c[i] = j + 1; s.get(a[i]).add(j); break; } } } for (int i : c) { if (i == 0) { System.out.println("NO"); return; } } System.out.println("YES"); for (int i : c) { System.out.println(i); } } static class FastIO { private final BufferedReader br; private final BufferedWriter bw; private String s[]; private int index; private StringBuilder sb; public FastIO() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8")); s = br.readLine().split(" "); sb = new StringBuilder(); index = 0; } public int ni() throws IOException { return Integer.parseInt(nextToken()); } public double nd() throws IOException { return Double.parseDouble(nextToken()); } public long nl() throws IOException { return Long.parseLong(nextToken()); } public String next() throws IOException { return nextToken(); } public String nli() throws IOException { try { return br.readLine(); } catch (IOException ex) { } return null; } public int[] gia(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public int[] gia(int n, int start, int end) throws IOException { validate(n, start, end); int a[] = new int[n]; for (int i = start; i < end; i++) { a[i] = ni(); } return a; } public double[] gda(int n) throws IOException { double a[] = new double[n]; for (int i = 0; i < n; i++) { a[i] = nd(); } return a; } public double[] gda(int n, int start, int end) throws IOException { validate(n, start, end); double a[] = new double[n]; for (int i = start; i < end; i++) { a[i] = nd(); } return a; } public long[] gla(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nl(); } return a; } public long[] gla(int n, int start, int end) throws IOException { validate(n, start, end); long a[] = new long[n]; for (int i = start; i < end; i++) { a[i] = nl(); } return a; } public int[][] gg(int n, int m) throws IOException { int adja[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = ni(); to[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][--count[from[i]]] = to[i]; adja[to[i]][--count[to[i]]] = from[i]; } return adja; } public void print(String s) throws IOException { bw.write(s); } public void println(String s) throws IOException { bw.write(s); bw.newLine(); } private String nextToken() throws IndexOutOfBoundsException, IOException { if (index == s.length) { s = br.readLine().split(" "); index = 0; } return s[index++]; } private void validate(int n, int start, int end) { if (start < 0 || end >= n) { throw new IllegalArgumentException(); } } } static class Data implements Comparable<Data> { int a, b; public Data(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Data o) { if (a == o.a) { return Integer.compare(b, o.b); } return Integer.compare(a, o.a); } public static void sort(int a[]) { Data d[] = new Data[a.length]; for (int i = 0; i < a.length; i++) { d[i] = new Data(a[i], 0); } Arrays.sort(d); for (int i = 0; i < a.length; i++) { a[i] = d[i].a; } } } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
444bc34c1ee04a225620c7379746e2e0
train_000.jsonl
1547044500
You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that: Each element of the array should be colored in some color; For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array; For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
256 megabytes
//package codeforces.div2; import java.util.*; public class ArrayKColoring { static public void print(int arr[], int k) { HashMap<Integer, Integer> map = new HashMap<>(); int max = 0; int va = 0; for(int i = 0; i < arr.length; i++) { map.put(arr[i], map.getOrDefault(arr[i], 0) + 1); if(map.get(arr[i]) > max) { max = Math.max(max, map.get(arr[i])); va = arr[i]; } } if(max > k || arr.length < k) { System.out.println("NO"); } else { System.out.println("YES"); int res[] = new int[arr.length]; int col = 1; if(arr.length==k) { for(int i = 0; i < arr.length; i++) { res[i] = col++; } } else { map = new HashMap<>(); for (int i = 0; i < arr.length; i++) { int val = arr[i]; res[i] = map.getOrDefault(val, 0) + 1; map.put(val, res[i]); } int rem = k - max; if(rem > 0 && k > 0) { HashSet<Integer> set = new HashSet<>(); for (int i = arr.length-1; i >= 0; i--) { if(set.contains(res[i]) && rem > 0) { res[i] = k; k--; rem--; } set.add(res[i]); } } } for(int i : res) { System.out.print(i + " "); } } } public static void main(String []args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int i = 0; int arr[] = new int[n]; while ( i < n) { arr[i++] = sc.nextInt(); } print(arr, k); } }
Java
["4 2\n1 2 2 3", "5 2\n3 2 1 2 3", "5 2\n2 1 1 2 1"]
2 seconds
["YES\n1 1 2 2", "YES\n2 1 1 2 1", "NO"]
NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.
Java 8
standard input
[ "sortings", "greedy" ]
3d4df21eebf32ce15841179bb85e6f2f
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.
1,400
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
standard output
PASSED
87a4a4457643d9c9917b31d7a4dbec36
train_000.jsonl
1354960800
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i &lt; n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
256 megabytes
import java.io.*; import java.util.Scanner; public class Main { public static void main(String args[]) throws java.lang.Exception { //BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String[] S; File inFile=new File("input.txt"); Scanner sc=new Scanner(inFile); /*File outFile=new File("output.txt"); FileWriter friter=new FileWriter(outFile,true); PrintWriter priter=new PrintWriter(friter);*/ FileOutputStream out=new FileOutputStream("output.txt"); int n=0,m=0; while(sc.hasNextLine()) { S=sc.nextLine().split(" "); n=Integer.parseInt(S[0]); m=Integer.parseInt(S[1]); } int max=n>m?n:m; char Odd,Even; int l=n+m; if(max==n) { Odd='B'; Even='G'; for(int i=1;i<=l;i++) { if((i&1)!=0||m==0)out.write((int)Odd); //priter.print(Odd); else if(m>0) { out.write((int)Even); //priter.print(Even); m--; } } } else { Odd='G'; Even='B'; for(int i=1;i<=l;i++) { if((i&1)!=0||n==0)out.write((int)Odd); //priter.print(Odd); else if(n>0) { out.write((int)Even); //priter.print(Even); n--; } } } //priter.close(); //System.out.println(); } }
Java
["3 3", "4 2"]
1 second
["GBGBGB", "BGBGBB"]
NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.
Java 7
input.txt
[ "greedy" ]
5392996bd06bf52b48fe30b64493f8f5
The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.
1,100
Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl. Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.
output.txt
PASSED
eb6723766c4c40f184a28655f3481845
train_000.jsonl
1354960800
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i &lt; n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
256 megabytes
/** * Created with IntelliJ IDEA. * User: Venky */ import java.io.*; import java.util.StringTokenizer; public class Main { static void solve() throws IOException { int n = nextInt(); int m = nextInt(); StringBuffer sb = new StringBuffer(); if(n > m) { boolean f = false; for(;n>0&&m>0;) { if(!f) { sb.append('B'); n--; } else { sb.append('G'); m--; } f = !f; } while(n>0) { sb.append('B'); n--; } out.println(sb); } else { boolean f = true; for(;n>0&&m>0;) { if(!f) { sb.append('B'); n--; } else { sb.append('G'); m--; } f = !f; } while(m>0) { sb.append('G'); m--; } while(n>0) { sb.append('B'); n--; } out.println(sb); } } static BufferedReader br; static StringTokenizer st; static PrintWriter out; public static void main(String[] args) throws IOException { InputStream input = new FileInputStream("input.txt"); br = new BufferedReader(new InputStreamReader(input)); out = new PrintWriter(new FileOutputStream("output.txt")); solve(); out.close(); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } }
Java
["3 3", "4 2"]
1 second
["GBGBGB", "BGBGBB"]
NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.
Java 7
input.txt
[ "greedy" ]
5392996bd06bf52b48fe30b64493f8f5
The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.
1,100
Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl. Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.
output.txt
PASSED
9f937022030406371b0aec1e7d18ceca
train_000.jsonl
1354960800
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i &lt; n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
256 megabytes
import static java.util.Arrays.deepToString; import java.io.*; import java.util.*; public class Main { static int binarySearch(int[] a, int x){ int n = a.length; int left = -1; int right = n; while(right - left > 1){ int mid = (left + right) / 2; if(x >= a[mid]){ left = mid; }else{ right = mid; } } if(right < n && a[right] == x){ return right; }else{ return right - 1; } } static void solve() throws Exception { int n = nextInt(); int m = nextInt(); if(n > m){ int k = n - m; for(int i = 0; i < k; i++){ out.print("B"); } for(int i = 0; i < m; i++){ out.print("GB"); } }else if(n < m){ int k = m - n; for(int i = 0; i < k; i++){ out.print("G"); } for(int i = 0; i < n; i++){ out.print("BG"); } }else{ for(int i = 0; i < n; i++){ out.print("BG"); } } } static BufferedReader br; static StringTokenizer st; static PrintWriter out; static void debug(Object... a) { System.err.println(deepToString(a)); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) { try { File file = new File("input.txt"); InputStream input = System.in; OutputStream output = System.out; if (file.canRead()) { input = (new FileInputStream(file)); output = (new PrintStream("output.txt")); } br = new BufferedReader(new InputStreamReader(input)); out = new PrintWriter(output); solve(); out.close(); br.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } }
Java
["3 3", "4 2"]
1 second
["GBGBGB", "BGBGBB"]
NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.
Java 7
input.txt
[ "greedy" ]
5392996bd06bf52b48fe30b64493f8f5
The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.
1,100
Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl. Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.
output.txt
PASSED
971369d4f240d92b02e572a2b74c27b7
train_000.jsonl
1354960800
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i &lt; n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
256 megabytes
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class practice { public static void main(String[] args) { Scanner sc = null; try { sc = new Scanner(new File("input.txt")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } PrintWriter out = null; try { out = new PrintWriter(new File("output.txt")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int b = sc.nextInt(); int g = sc.nextInt(); if (b >= g) { for (int i = 0; i < g; i++) { out.print("BG"); b--; } while (b-- > 0) out.print("B"); } else { for (int i = 0; i < b; i++) { out.print("GB"); g--; } while (g-- > 0) out.print("G"); } out.flush(); out.close(); } }
Java
["3 3", "4 2"]
1 second
["GBGBGB", "BGBGBB"]
NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.
Java 7
input.txt
[ "greedy" ]
5392996bd06bf52b48fe30b64493f8f5
The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.
1,100
Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl. Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.
output.txt
PASSED
e5538ebde80cf43b9d1cb5854c20e421
train_000.jsonl
1354960800
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i &lt; n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { public static void main(String[] args) throws IOException { Scanner scan = new Scanner (new File("input.txt")); PrintStream out = new PrintStream (new File("output.txt")); int b, q; b = scan.nextInt(); q = scan.nextInt(); String ans = ""; if(b > q){ for(int i = 1; i <= q; i++){ ans += "BG"; } for(int i = 1; i<= b - q; i++){ ans += "B"; } out.println(ans); }else{ for(int i = 1; i <= b; i++){ ans += "GB"; } for(int i = 1; i<= q - b; i++){ ans += "G"; } out.println(ans); } scan.close(); out.close(); } }
Java
["3 3", "4 2"]
1 second
["GBGBGB", "BGBGBB"]
NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.
Java 7
input.txt
[ "greedy" ]
5392996bd06bf52b48fe30b64493f8f5
The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.
1,100
Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl. Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.
output.txt
PASSED
84c0ed16febce6040c97e667a27664b0
train_000.jsonl
1354960800
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i &lt; n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; import java.util.StringTokenizer; public class Main { BufferedReader in; StringTokenizer str; PrintWriter out; String SK; String next() throws IOException { while ((str == null) || (!str.hasMoreTokens())) { SK = in.readLine(); if (SK == null) return null; str = new StringTokenizer(SK); } return str.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } void solve() throws IOException { int n = nextInt(); int m = nextInt(); StringBuilder sb = new StringBuilder(); char B = 'B'; char G = 'G'; char firstInSeq; char secondInSeq; int l; int d; char additional; if (n > m){ l = m; d = n - m; firstInSeq = B; secondInSeq = G; additional = B; } else { l = n; d = m - n; firstInSeq = G; secondInSeq = B; additional = G; } for (int i = 0; i < l; i++){ sb.append(firstInSeq); sb.append(secondInSeq); } for (int i = 0; i < d; i++){ sb.append(additional); } out.println(sb.toString()); } void run() throws IOException { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); solve(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["3 3", "4 2"]
1 second
["GBGBGB", "BGBGBB"]
NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.
Java 7
input.txt
[ "greedy" ]
5392996bd06bf52b48fe30b64493f8f5
The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.
1,100
Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl. Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.
output.txt
PASSED
1058e76b02cef127de924743a1c433ac
train_000.jsonl
1354960800
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i &lt; n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter( new FileWriter(new File("output.txt"))); int n = in.nextInt(); int m = in.nextInt(); if (n > m) { for (int i = 0; i < m; i++) { out.print("BG"); } for (int i = 0; i < n - m; i++) { out.print("B"); } out.println(); } else { for (int i = 0; i < n; i++) { out.print("GB"); } for (int i = 0; i < m - n; i++) { out.print("G"); } out.println(); } out.close(); } }
Java
["3 3", "4 2"]
1 second
["GBGBGB", "BGBGBB"]
NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.
Java 7
input.txt
[ "greedy" ]
5392996bd06bf52b48fe30b64493f8f5
The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.
1,100
Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl. Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.
output.txt
PASSED
e802f176298eb8a1311e9105839ac1e9
train_000.jsonl
1354960800
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i &lt; n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.math.BigInteger; import java.util.Arrays; import java.util.TreeMap; public class Main { // static BufferedReader br = new BufferedReader(new InputStreamReader( // System.in)); static BufferedReader br; // static PrintWriter out = new PrintWriter(new // OutputStreamWriter(System.out)); static PrintWriter out; static StreamTokenizer in; static int n, m, k; static char[][] arr; public static void main(String[] args) throws IOException { br = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); in = new StreamTokenizer(br); n = nextInt(); m = nextInt(); if (n > m) { for (int i = 1; i <= n; i++) { out.print("B"); if (i <= m) out.print("G"); } } else { for (int i = 1; i <= m; i++) { out.print("G"); if (i <= n) out.print("B"); } } out.println(); out.flush(); out.close(); } static String next() throws IOException { in.nextToken(); return in.sval; } static long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } static int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } }
Java
["3 3", "4 2"]
1 second
["GBGBGB", "BGBGBB"]
NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.
Java 7
input.txt
[ "greedy" ]
5392996bd06bf52b48fe30b64493f8f5
The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.
1,100
Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl. Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.
output.txt
PASSED
d65eaead2c9cd9152d9d52d99cb50ec9
train_000.jsonl
1354960800
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i &lt; n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package cf154; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class Cf154 { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File("input.txt")); //Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(new File("output.txt")); int n = sc.nextInt(); int m = sc.nextInt(); if (n > m){ for (int i = 0 ; i < m ; i++){ out.print("BG"); } for (int i = 0; i < n-m;i++){ out.print("B"); } } else if(n < m){ for (int i = 0 ; i < n ; i++){ out.print("GB"); } for (int i = 0; i < m-n;i++){ out.print("G"); } } else{ for (int i = 0 ; i < n ; i++){ out.print("BG"); } } sc.close(); out.close(); } }
Java
["3 3", "4 2"]
1 second
["GBGBGB", "BGBGBB"]
NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.
Java 7
input.txt
[ "greedy" ]
5392996bd06bf52b48fe30b64493f8f5
The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.
1,100
Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl. Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.
output.txt
PASSED
06a927c8b0b1fa00605e0437b9f98b2b
train_000.jsonl
1354960800
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i &lt; n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class CF154D2A { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("input.txt")); PrintWriter out = new PrintWriter("output.txt"); String s[] = in.readLine().trim().split(" "); int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]); if (n > m) { for (int i = 0; i < m; i++) { out.print("BG"); } for (int i = 0; i < n-m; i++) { out.print("B"); } out.println(); } else { for (int i = 0; i < n; i++) { out.print("GB"); } for (int i = 0; i < m-n; i++) { out.print("G"); } out.println(); } out.close(); } }
Java
["3 3", "4 2"]
1 second
["GBGBGB", "BGBGBB"]
NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.
Java 7
input.txt
[ "greedy" ]
5392996bd06bf52b48fe30b64493f8f5
The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.
1,100
Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl. Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.
output.txt
PASSED
3e607184f35dfe99f8a3a2d37c409c4c
train_000.jsonl
1354960800
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i &lt; n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.InputMismatchException; import java.util.StringTokenizer; public class Main{ static class InputReader { final private int BUFFER_SIZE = 1 << 17; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public InputReader(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public byte next() { try { return read(); } catch (Exception e) { throw new InputMismatchException(); } } public String nextString() { StringBuilder sb = new StringBuilder(""); byte c = next(); while (c <= ' ') { c = next(); } do { sb.append((char) c); c = next(); } while (c > ' '); return sb.toString(); } public int nextInt() { int ret = 0; byte c = next(); while (c <= ' ') { c = next(); } boolean neg = c == '-'; if (neg) { c = next(); } do { ret = (ret << 3) + (ret << 1) + c - '0'; c = next(); } while (c > ' '); if (neg) { return -ret; } return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); } catch (IOException e) { throw new InputMismatchException(); } if (bytesRead == -1) { buffer[0] = -1; } } private byte read() { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } } public static void main(String arg[]) throws IOException { // InputReader r=new InputReader(System.in); BufferedReader r=new BufferedReader(new FileReader("input.txt")); // BufferedReader r=new BufferedReader(new InputStreamReader(System.in)); BufferedWriter wr=new BufferedWriter(new PrintWriter("output.txt")); PrintWriter p=new PrintWriter(System.out,false); StringTokenizer str=new StringTokenizer(r.readLine()); int n=Integer.parseInt(str.nextToken()); int m=Integer.parseInt(str.nextToken()); char N='B',M='G'; if(n<m) { int temp=n; n=m; m=temp; char t=N; N=M; M=t; } while(n>0||m>0) { if(n>0) { wr.append(N); n--; } if(m>0) { wr.append(M); m--; } } wr.flush(); }}
Java
["3 3", "4 2"]
1 second
["GBGBGB", "BGBGBB"]
NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.
Java 7
input.txt
[ "greedy" ]
5392996bd06bf52b48fe30b64493f8f5
The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.
1,100
Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl. Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.
output.txt
PASSED
4d007f1c96712b1df82c436ec5b105df
train_000.jsonl
1354960800
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i &lt; n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.Map.Entry; public class Main { public static void main(String[] args) throws IOException { (new Main()).solve(); } public Main() { } //MyReader in = new MyReader(); //PrintWriter out = new PrintWriter(System.out); void solve() throws IOException { //BufferedReader in = new BufferedReader(new //InputStreamReader(System.in)); //Scanner in = new Scanner(System.in); Scanner in = new Scanner(new FileReader("input.txt")); PrintWriter out = new PrintWriter("output.txt"); int n = in.nextInt(); int m = in.nextInt(); StringBuilder s = new StringBuilder(""); if (n > m) { for (int i = 0; i < m; i++) { s.append("BG"); } for (int i = 0; i < n - m; i++) { s.append("B"); } } else { for (int i = 0; i < n; i++) { s.append("GB"); } for (int i = 0; i < m - n; i++) { s.append("G"); } } out.println(s.toString()); out.close(); } class MyReader { private BufferedReader in; String[] parsed; int index = 0; public MyReader() { in = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt() throws NumberFormatException, IOException { if (parsed == null || parsed.length == index) { read(); } return Integer.parseInt(parsed[index++]); } public long nextLong() throws NumberFormatException, IOException { if (parsed == null || parsed.length == index) { read(); } return Long.parseLong(parsed[index++]); } public double nextDouble() throws NumberFormatException, IOException { if (parsed == null || parsed.length == index) { read(); } return Double.parseDouble(parsed[index++]); } public String nextString() throws IOException { if (parsed == null || parsed.length == index) { read(); } return parsed[index++]; } private void read() throws IOException { parsed = in.readLine().split(" "); index = 0; } public String readLine() throws IOException { return in.readLine(); } }; };
Java
["3 3", "4 2"]
1 second
["GBGBGB", "BGBGBB"]
NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.
Java 7
input.txt
[ "greedy" ]
5392996bd06bf52b48fe30b64493f8f5
The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.
1,100
Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl. Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.
output.txt
PASSED
1cca7f6b1bd6ecff6d96156712104952
train_000.jsonl
1531578900
Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$  $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.Map.Entry; public class Main { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private PrintWriter pw; private long mod = 1000000 + 3; private StringBuilder ans_sb; private void soln() { int n = nextInt(); int m = nextInt(); if(m < n-1) { pw.println("Impossible"); }else { int m1 = m; int n1 = n; m1 -= n1-1; while(m1 != 0 && n1 > 0) { for(int i=2;i<n1;i++) { if(gcd(i,n1) == 1) { m1--; if(m1 == 0) break; } } n1--; } //debug(n1 +" "+m1); if(n1 == 0 && m1 != 0) pw.println("Impossible"); else { pw.println("Possible"); m -= n-1; for(int i=2;i<=n;i++) { pw.println(1+" "+i); } while(m != 0) { for(int i=2;i<n;i++) { if(gcd(i,n) == 1) { m--; pw.println(i+" "+n); if(m == 0) break; } } n--; } } } } private String solveEqn(long a, long b) { long x = 0, y = 1, lastx = 1, lasty = 0, temp; while (b != 0) { long q = a / b; long r = a % b; a = b; b = r; temp = x; x = lastx - q * x; lastx = temp; temp = y; y = lasty - q * y; lasty = temp; } return lastx + " " + lasty; } private void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } private long pow(long a, long b, long c) { if (b == 0) return 1; long p = pow(a, b / 2, c); p = (p * p) % c; return (b % 2 == 0) ? p : (a * p) % c; } private long gcd(long n, long l) { if (l == 0) return n; return gcd(l, n % l); } public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { @Override public void run() { new Main().solve(); } }, "1", 1 << 26).start(); //new Main().solve(); } public StringBuilder solve() { InputReader(System.in); /* * try { InputReader(new FileInputStream("C:\\Users\\hardik\\Desktop\\in.txt")); * } catch(FileNotFoundException e) {} */ pw = new PrintWriter(System.out); // ans_sb = new StringBuilder(); soln(); pw.close(); // System.out.println(ans_sb); return ans_sb; } public void InputReader(InputStream stream1) { stream = stream1; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private 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 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 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 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 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 int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } private long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private void pArray(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); return; } private void pArray(long[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); return; } private boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private char nextChar() { int c = read(); while (isSpaceChar(c)) c = read(); char c1 = (char) c; while (!isSpaceChar(c)) c = read(); return c1; } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["5 6", "6 12"]
2 seconds
["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"]
NoteHere is the representation of the graph from the first example:
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "math", "brute force" ]
0ab1b97a8d2e0290cda31a3918ff86a4
The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges.
1,700
If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them.
standard output
PASSED
1fa3b34578d109b08d6f9ef78e637835
train_000.jsonl
1531578900
Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$  $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them.
256 megabytes
import java.io.*; import java.util.*; public class Main { static StringBuilder ans = new StringBuilder(); static StringBuilder ans1 = new StringBuilder(); static long mod = 1000000007; static boolean[] primes; static boolean co(int a, int b) { int min = Math.min(a, b); for(int i=1;i<=min;i++) { if(primes[i]) { if(a%i==0 && b%i==0) { return false; } } } return true; } public static void main(String[] args)throws IOException { Reader in=new Reader(); // int t = in.nextInt(); // System.out.println(pr("0",0)); int t = 1; while(t-->0) { int n = in.nextInt(); int m = in.nextInt(); primes(100000); ans.append("Impossible"); if(m<n-1) { exit(); } else { int count = 0; ans1.append("Possible\n"); // while(m-->0) // { outer:for(int i=1;i<=n;i++) { for(int j=i+1;j<=n;j++) { if(co(i,j)) { ans1.append(""+i+" "+j+"\n"); count++; if(count == m) break outer; } } } if(count == m) { System.out.println(ans1); } else { System.out.println(ans); } // } } } } static void primes(int n) { primes = new boolean[n + 1]; for (int i = 2; i < primes.length; i++) { primes[i] = true; } int num = 2; while (true) { for (int i = 2;; i++) { int multiple = num * i; if (multiple > n) { break; } else { primes[multiple] = false; } } boolean nextNumFound = false; for (int i = num + 1; i < n + 1; i++) { if (primes[i]) { num = i; nextNumFound = true; break; } } if (!nextNumFound) { break; } } } /////////////////////////////// /////////////////////////////// /////////////////////////////// /////////////////////////////// /////////////////////////////// /////////////////////////////// static void exit(){System.out.print(ans);System.exit(0);} static int min(int... a){int min=a[0];for(int i:a)min=Math.min(min, i);return min;} static int max(int... a){int max=a[0];for(int i:a)max=Math.max(max, i);return max;} static int gcd(int... a){int gcd=a[0];for(int i:a)gcd=gcd(gcd, i);return gcd;} static long min(long... a){long min=a[0];for(long i:a)min=Math.min(min, i);return min;} static long max(long... a){long max=a[0];for(long i:a)max=Math.max(max, i);return max;} static long gcd(long... a){long gcd=a[0];for(long i:a)gcd=gcd(gcd, i);return gcd;} static String pr(String a, long b){String c="";while(b>0){if(b%2==1)c=c.concat(a);a=a.concat(a);b>>=1;}return c;} static long powm(long a, long b, long m){long an=1;long c=a;while(b>0){if(b%2==1)an=(an*c)%m;c=(c*c)%m;b>>=1;}return an;} static int gcd(int a, int b){if(b==0)return a;return gcd(b, a%b);} static long gcd(long a, long b){if(b==0)return a;return gcd(b, a%b);} static class Reader { BufferedReader reader; StringTokenizer tokenizer; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } String next() {while (tokenizer == null || !tokenizer.hasMoreTokens()) { try {tokenizer = new StringTokenizer(reader.readLine());} catch (IOException e) {throw new RuntimeException(e);}} return tokenizer.nextToken();} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble() {return Double.parseDouble(next());} } }
Java
["5 6", "6 12"]
2 seconds
["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"]
NoteHere is the representation of the graph from the first example:
Java 8
standard input
[ "greedy", "graphs", "constructive algorithms", "math", "brute force" ]
0ab1b97a8d2e0290cda31a3918ff86a4
The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges.
1,700
If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them.
standard output