exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
32aa33c8bfc76aa938dac9d366d1a4b3
train_003.jsonl
1342020600
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
256 megabytes
import java.util.*; public class S { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] time = new int[n]; int min = Integer.MAX_VALUE, ind = 0; for(int i = 0; i<n; i++) { time[i] = in.nextInt(); if(time[i] < min) { min = time[i]; ind = i+1; } } Arrays.sort(time); if(time.length > 1 && time[0]==time[1]) { System.out.println("Still Rozdil"); }else { System.out.println(ind); } } }
Java
["2\n7 4", "7\n7 4 47 100 4 9 12"]
2 seconds
["2", "Still Rozdil"]
NoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil".
Java 11
standard input
[ "implementation", "brute force" ]
ce68f1171d9972a1b40b0450a05aa9cd
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.
900
Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).
standard output
PASSED
f6263bbec074ff137669d1b496f49ee6
train_003.jsonl
1342020600
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
256 megabytes
import java.util.*; public class Main { public static void main(String args[]) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;i++){ arr[i] = s.nextInt(); } int ind = -1; int min = Integer.MAX_VALUE; for(int i=0;i<n;i++){ if(arr[i]<min){ ind = i; min = arr[i]; } } int count = 0; for(int i=0;i<n;i++){ if(arr[i]==min){ count++; } } if(count>1){ System.out.println("Still Rozdil"); }else{ System.out.println(ind+1); } } }
Java
["2\n7 4", "7\n7 4 47 100 4 9 12"]
2 seconds
["2", "Still Rozdil"]
NoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil".
Java 11
standard input
[ "implementation", "brute force" ]
ce68f1171d9972a1b40b0450a05aa9cd
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.
900
Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).
standard output
PASSED
ba77954771ae046d70b2089ebc615c51
train_003.jsonl
1342020600
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
256 megabytes
import java.util.*;import java.io.*;import java.math.*; public class Main { public static void process()throws IOException { int n=ni(); int[]A=nai(n); int ind=0,min=Integer.MAX_VALUE; for(int i=0;i<n;i++) { if(A[i]<min) { min=A[i]; ind=i+1; } } Arrays.sort(A); if(A.length>1 && A[0]==A[1]) pn("Still Rozdil"); else pn(ind); } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} int t=1; // t=ni(); while(t-->0) {process();} out.flush();out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;} static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["2\n7 4", "7\n7 4 47 100 4 9 12"]
2 seconds
["2", "Still Rozdil"]
NoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil".
Java 11
standard input
[ "implementation", "brute force" ]
ce68f1171d9972a1b40b0450a05aa9cd
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.
900
Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).
standard output
PASSED
fc28e08c29a8ac7951412af0213bab08
train_003.jsonl
1342020600
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class main { static StringBuilder out=new StringBuilder(); static FastReader in=new FastReader(); public static int[] getIntArray(int n){ int arr[]=new int[n]; for(int i=0;i<n;i++){ arr[i]=in.nextInt(); } return arr; } static int mod=(int)1e9 +7; static int [][]dp; public static void solve(){ int n=in.nextInt(); int arr[][]=new int[n][]; for(int i=0;i<n;i++){ arr[i]=new int[]{in.nextInt(), i+1}; } Arrays.sort(arr, new Comparator<int[]>() { public int compare(int a[], int b[]){ return Integer.compare(a[0],b[0]); } }); if(n>1 && arr[0][0]==arr[1][0]){ out.append("Still Rozdil"); return; } out.append(arr[0][1]); } public static void main(String args[]){ int t=1; while(t-->0){ solve(); out.append('\n'); } System.out.println(out); } } 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
["2\n7 4", "7\n7 4 47 100 4 9 12"]
2 seconds
["2", "Still Rozdil"]
NoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil".
Java 11
standard input
[ "implementation", "brute force" ]
ce68f1171d9972a1b40b0450a05aa9cd
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.
900
Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).
standard output
PASSED
24e22a23bdedfeee78a2cb64d3b02ef3
train_003.jsonl
1342020600
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
256 megabytes
// import java.io.*; // import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; // import java.util.Scanner; import java.util.StringTokenizer; public class rozdil { 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 s=new FastReader(); int n = s.nextInt(); int a[] = new int[n]; int min = Integer.MAX_VALUE; int pos=0,c=0; for (int i = 0; i < n; i++) { a[i] = s.nextInt(); if(a[i]<min){ min=a[i]; pos=i; } } for (int i = 0; i < n; i++) { if(min==a[i]){ c++; } } if(c>=2)System.out.println("Still Rozdil"); else System.out.println(pos+1); } }
Java
["2\n7 4", "7\n7 4 47 100 4 9 12"]
2 seconds
["2", "Still Rozdil"]
NoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil".
Java 11
standard input
[ "implementation", "brute force" ]
ce68f1171d9972a1b40b0450a05aa9cd
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.
900
Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).
standard output
PASSED
a990df97d895cd6d46ec117d72b05c79
train_003.jsonl
1342020600
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
256 megabytes
import java.io.*; import java.util.*; public class Main { final static long mod = (long)10e9+7; public static void main(String[] args) { InputReader sc = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); Random gen = new Random(); int test = 1;//sc.nextInt(); while(test-->0) { int n = sc.nextInt(); ArrayList<Long> l = new ArrayList<>(); for(int i=0;i<n;i++) l.add(sc.nextLong()); if(Collections.frequency(l,Collections.min(l))>1) pw.println("Still Rozdil"); else pw.println(l.indexOf(Collections.min(l))+1); } pw.close(); } static class Data implements Comparable<Data>{ int x, a; public Data (int m, int n) { x = m; a = n; } @Override public int compareTo(Data o) { return a - o.a; } } 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 static int[] shuffle(int[] a, Random gen) { for(int i = 0, n = a.length;i < n;i++) { int ind = gen.nextInt(n-i)+i; int d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["2\n7 4", "7\n7 4 47 100 4 9 12"]
2 seconds
["2", "Still Rozdil"]
NoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil".
Java 11
standard input
[ "implementation", "brute force" ]
ce68f1171d9972a1b40b0450a05aa9cd
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.
900
Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).
standard output
PASSED
4d84bc7ad6e42a671aece3bcfead8f86
train_003.jsonl
1342020600
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskG solver = new TaskG(); solver.solve(1, in, out); out.close(); } static class TaskG { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); ArrayList<pair> list = new ArrayList<>(); for (int i = 0; i < n; i++) { pair p = new pair(in.nextInt(), i); list.add(p); } Collections.sort(list, new Comparator<pair>() { public int compare(pair o1, pair o2) { return o1.val - o2.val; } }); if (n > 1) { if (list.get(0).val == list.get(1).val) { out.println("Still Rozdil"); } else { out.println(list.get(0).idx + 1); } } else { out.println(list.get(0).idx + 1); } } public class pair { int val; int idx; public pair(int val, int idx) { this.val = val; this.idx = idx; } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2\n7 4", "7\n7 4 47 100 4 9 12"]
2 seconds
["2", "Still Rozdil"]
NoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil".
Java 11
standard input
[ "implementation", "brute force" ]
ce68f1171d9972a1b40b0450a05aa9cd
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.
900
Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).
standard output
PASSED
331bde9f3be93ae2fee865de402fc759
train_003.jsonl
1342020600
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
256 megabytes
import java.util.*; public class P37 { static class Pair{ int count; int index; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int min=Integer.MAX_VALUE; int mini=-1; HashMap<Integer,Pair> hm=new HashMap<>(); boolean flag=false; for(int i=0;i<n;i++) { int val=sc.nextInt(); if(hm.containsKey(val)) { Pair obj=hm.get(val); obj.count=obj.count+1; hm.put(val,obj); }else { Pair newObj=new Pair(); newObj.count=1; newObj.index=i+1; hm.put(val,newObj); } if(val<min) { min=val; } } if(hm.get(min).count>1) { System.out.println("Still Rozdil"); }else { System.out.println(hm.get(min).index); } } }
Java
["2\n7 4", "7\n7 4 47 100 4 9 12"]
2 seconds
["2", "Still Rozdil"]
NoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil".
Java 11
standard input
[ "implementation", "brute force" ]
ce68f1171d9972a1b40b0450a05aa9cd
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.
900
Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).
standard output
PASSED
d8bb8bc9bda9dd8e2d255f4f2a75a81e
train_003.jsonl
1566484500
You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x &lt; n$$$ and $$$1 \le y &lt; m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class B { 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()); } 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) { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.nextInt(); } } solve(n, m, a, out); out.flush(); out.close(); } private static void solve(int n, int m, int[][] a, PrintWriter out) { boolean[][] b = new boolean[n][m]; StringBuffer sb = new StringBuffer(); int ans = 0; for (int i = 0; i < n-1 ; i++) { for (int j = 0; j < m-1 ; j++) { if(a[i][j] * a[i+1][j] * a[i+1][j+1] * a[i][j+1] > 0) { a[i][j] = 2; a[i][j+1] = 2; a[i+1][j+1] = 2; a[i+1][j] = 2; sb.append(i + 1).append(" ").append(j+ 1).append("\n"); ans++; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if(a[i][j] == 1) { out.println(-1); return; } } } out.println(ans); out.println(sb.toString()); } }
Java
["3 3\n1 1 1\n1 1 1\n0 1 1", "3 3\n1 0 1\n1 0 1\n0 0 0", "3 2\n0 0\n0 0\n0 0"]
1 second
["3\n1 1\n1 2\n2 2", "-1", "0"]
NoteThe sequence of operations in the first example: $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
ad641a44ecaf78ca253b199f3d40ef96
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.
1,200
If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.
standard output
PASSED
410d8171661e42e68ecff0884086ad16
train_003.jsonl
1566484500
You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x &lt; n$$$ and $$$1 \le y &lt; m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.
256 megabytes
import java.io.*; import java.util.*; public class SquareFilling { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] a = br.readLine().split(" "); int rows = Integer.parseInt(a[0]); int cols = Integer.parseInt(a[1]); boolean[][] values = new boolean[rows][cols]; Queue<Integer> ansRows = new LinkedList<Integer>(); Queue<Integer> ansCols = new LinkedList<Integer>(); for (int i = 0; i < rows; i++) { a = br.readLine().split(" "); for (int j = 0; j < cols; j++) { if (Integer.parseInt(a[j]) == 1){ values[i][j] = true; } } } boolean valid = true; if (!(rows > 1) || !(cols > 1)) { valid = false; } if (values[0][0] && rows > 1 && cols > 1) { if (values[1][0] && values[0][1] && values[1][1]) { ansRows.add(0); ansCols.add(0); } else { valid = false; } } if (values[rows-1][0] && rows > 1 && cols > 1) { if (values[rows-2][0] && values[rows-1][1] && values[rows-2][1]) { } else { valid = false; } } if (values[0][cols-1] && rows > 1 && cols > 1) { if (values[1][cols-1] && values[0][cols-2] && values[1][cols-2]) { }else { valid = false; } } if (values[rows-1][cols-1] && rows > 1 && cols > 1) { if (values[rows-2][cols-1] && values[rows-1][cols-2] && values[rows-2][cols-2]) { } else { valid = false; } } for (int r = 1; r < rows - 1; r++) { int c = 0; if (values[r][c]) { if (values[r+1][c] && values[r][c+1] && values[r+1][c+1]) { ansRows.add(r); ansCols.add(c); } else if (values[r-1][c] && values[r][c+1] && values[r-1][c+1]) { } else { valid = false; break; } } c = cols - 1; if (values[r][c]) { if (values[r-1][c] && values[r][c-1] && values[r-1][c-1]) { } else if (values[r+1][c] && values[r][c-1] && values[r+1][c-1]) { } else { valid = false; break; } } } for (int c = 1; c < cols - 1; c++) { int r = 0; if (values[r][c]) { if (values[r+1][c] && values[r][c+1] && values[r+1][c+1]) { ansRows.add(r); ansCols.add(c); } else if (values[r+1][c] && values[r][c-1] && values[r+1][c-1]) { } else { valid = false; break; } } r = rows - 1; if (values[r][c]) { if (values[r-1][c] && values[r][c+1] && values[r-1][c+1]) { } else if (values[r-1][c] && values[r][c-1] && values[r-1][c-1]) { } else { valid = false; break; } } } for (int r = 1; r < rows - 1; r++) { for (int c = 1; c < cols - 1; c++) { if (values[r][c]) { if (values[r+1][c] && values[r][c+1] && values[r+1][c+1]) { ansRows.add(r); ansCols.add(c); } else if (values[r-1][c] && values[r][c+1] && values[r-1][c+1]) { } else if (values[r-1][c] && values[r][c-1] && values[r-1][c-1]) { } else if (values[r+1][c] && values[r][c-1] && values[r+1][c-1]) { } else { valid = false; break; } } } if (!valid) { break; } } if (!valid) { System.out.println(-1); } else { System.out.println(ansRows.size()); while(!ansRows.isEmpty()) { System.out.println((ansRows.poll()+1) + " " + (ansCols.poll()+1)); } } } }
Java
["3 3\n1 1 1\n1 1 1\n0 1 1", "3 3\n1 0 1\n1 0 1\n0 0 0", "3 2\n0 0\n0 0\n0 0"]
1 second
["3\n1 1\n1 2\n2 2", "-1", "0"]
NoteThe sequence of operations in the first example: $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
ad641a44ecaf78ca253b199f3d40ef96
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.
1,200
If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.
standard output
PASSED
cde49858e75d31c9f542865076b77e4f
train_003.jsonl
1566484500
You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x &lt; n$$$ and $$$1 \le y &lt; m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.
256 megabytes
import java.util.*; public class Solution { static int a[][];static int b[][]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int r = sc.nextInt(); int c = sc.nextInt(); a = new int[r][c];b=new int[r][c]; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) b[i][j]=a[i][j]=sc.nextInt(); }StringBuffer sb=new StringBuffer(); int k = 0; for (int i = 0; i < r - 1; i++) { for (int j = 0; j < c - 1; j++) if (check(i, j)) { k++; sb.append((i + 1) + " " + (j + 1) + "\n"); } } for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { if(b[i][j]==1) {System.out.println(-1); System.exit(0); } } } System.out.println(k); System.out.println(sb); } public static boolean check(int i, int j) { if (a[i][j] == 1 && a[i][j + 1] == 1 && a[i + 1][j] == 1 && a[i + 1][j + 1] == 1) { b[i][j]=b[i][j + 1]=b[i + 1][j]= b[i + 1][j + 1]= 0; return true; } return false; } }
Java
["3 3\n1 1 1\n1 1 1\n0 1 1", "3 3\n1 0 1\n1 0 1\n0 0 0", "3 2\n0 0\n0 0\n0 0"]
1 second
["3\n1 1\n1 2\n2 2", "-1", "0"]
NoteThe sequence of operations in the first example: $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
ad641a44ecaf78ca253b199f3d40ef96
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.
1,200
If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.
standard output
PASSED
0260e6d074081036a5836ecf5ad75465
train_003.jsonl
1566484500
You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x &lt; n$$$ and $$$1 \le y &lt; m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.
256 megabytes
import java.util.Scanner; import java.util.ArrayList; public class ProbB2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n,m,a,b,count=0,counto=0 ; boolean possible=true; n = input.nextInt(); m = input.nextInt(); int[][] matrix = new int[n][m] ; ArrayList<Integer> index = new ArrayList<Integer>(n); for(a=0;a<n;a++) { for(b=0;b<m;b++) { matrix[a][b] = input.nextInt(); } } loop:for(a=0;a<n-1;a++) { for(b=0;b<m-1;b++) { if(matrix[a][b]==1) { if(matrix[a][b+1]!=0) { if(matrix[a+1][b]!=0) { if(matrix[a+1][b+1]!=0) { matrix[a][b]=matrix[a][b+1]=matrix[a+1][b]=matrix[a+1][b+1]=-1; count++; index.add(a+1); index.add(b+1); } else { possible = false ; break loop ; } } else { possible = false ; break loop ; } } else { possible = false ; break loop ; } } else if(matrix[a][b]==-1) { if(matrix[a][b+1]!=0) { if(matrix[a+1][b]!=0) { if(matrix[a+1][b+1]!=0) { matrix[a][b]=matrix[a][b+1]=matrix[a+1][b]=matrix[a+1][b+1]=-1; count++; index.add(a+1); index.add(b+1); } } } } } } if(possible) { loop2:for(a=n-1,b=0;b<m;b++) { if(matrix[a][b]==1) { possible = false ; break loop2 ; } } loop3:for(a=0,b=m-1;a<n;a++) { if(matrix[a][b]==1) { possible = false ; break loop3 ; } } } if(possible) { System.out.println(count); for(int x=0;x<2*count;x=x+2) System.out.println(index.get(x)+" "+index.get(x+1)); } else System.out.println("-1"); } }
Java
["3 3\n1 1 1\n1 1 1\n0 1 1", "3 3\n1 0 1\n1 0 1\n0 0 0", "3 2\n0 0\n0 0\n0 0"]
1 second
["3\n1 1\n1 2\n2 2", "-1", "0"]
NoteThe sequence of operations in the first example: $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
ad641a44ecaf78ca253b199f3d40ef96
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.
1,200
If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.
standard output
PASSED
271650594e964fb55a73620bde1e8bcf
train_003.jsonl
1566484500
You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x &lt; n$$$ and $$$1 \le y &lt; m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.
256 megabytes
/* / フフ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ム / )\⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀Y (⠀⠀| ( ͡° ͜ʖ ͡°)⠀⠀⠀ ⌒(⠀ ノ (⠀ ノ⌒ Y ⌒ヽ-く __/ | _⠀。ノ| ノ。 |/ (⠀ー '_人`ー ノ ⠀|\  ̄ _人'彡ノ ⠀ )\⠀⠀ 。⠀⠀ / ⠀⠀(\⠀ #⠀ / ⠀/⠀⠀⠀/ὣ========D- /⠀⠀⠀/⠀ \ \⠀⠀\ ( (⠀)⠀⠀⠀⠀ ) ).⠀) (⠀⠀)⠀⠀⠀⠀⠀( | / |⠀ /⠀⠀⠀⠀⠀⠀ | / [_] ⠀⠀⠀⠀⠀[___] */ //1:-segment tree (class segment_tree) //2:-Prime check (class Prime_check) //3:-greatest common divisor (class GFG) //4:-modulus class (class mod_) import java.util.*; import java.io.*; import java.math.BigInteger; import java.math.BigDecimal; public class srx2 { static class segment_tree { static int st[]; public static void cons(int a[]) { int x=(int)Math.ceil((Math.log(a.length)/Math.log(2))); int size=2*((int)(Math.pow(2,x)))-1; st=new int[size]; consut(a,0,a.length-1,0); } public static int consut(int a[],int ss,int se,int si) { if(ss==se) { st[si]=a[ss]; return st[si]; } int mid=(ss+se)/2; st[si]=consut(a,ss,mid,2*si+1)+consut(a,mid+1,se,2*si+2); return st[si]; } public static int getsum(int ss,int se,int qs,int qe,int si) { if(qs<=ss && qe>=se) return st[si]; if(qs>se || ss>qe) return 0; int mid=(ss+se)/2; return getsum(ss,mid,qs,qe,2*si+1)+getsum(mid+1,se,qs,qe,2*si+2); } public static void update(int ss,int se,int i,int diff,int si) { if(i<ss || i>se) return; st[si]+=diff; int mid=(ss+se)/2; if(ss!=se) { update(ss,mid,i,diff,2*si+1); update(mid+1,se,i,diff,2*si+2); } } } static class Prime_check { public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (long i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } } static class GFG { public static long gfg(long a,long b) { if(b==0) return a; else return gfg(b,a%b); } } static class mod_ { static long MOD=1000000007; public static long fast_exp(long x, long y) { long res = 1; x = x % MOD; while (y > 0) { if((y & 1)==1) res = (res * x) % MOD; y = y >> 1; x = (x * x) % MOD; } return res; } } static class obj { int a; int b; public obj(int x,int y) { a=x; b=y; } } public static void main(String args[])throws IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int a[][]=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=sc.nextInt(); } } int b[][]=new int[n][m]; int c[][]=new int[n][m]; int ff=0; ArrayList<obj> ar=new ArrayList<>(); outer:for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(a[i][j]==1) { int flag=0; try{ if(a[i+1][j+1]==1 && a[i+1][j]==1 && a[i][j+1]==1) {flag=1; c[i+1][j+1]=1; c[i+1][j]=1; c[i][j+1]=1;} } catch(Exception e) {} if(flag==1) { c[i][j]=1; ar.add(new obj(i,j)); } else{ if(c[i][j]==0){ ff=1;break outer;}} } } } if(ff==1) System.out.println("-1"); else { if(ar.size()==0) System.out.println(0); else { System.out.println(ar.size()); for(int i=0;i<ar.size();i++) System.out.println((ar.get(i).a+1)+" "+(ar.get(i).b+1)); } } } }
Java
["3 3\n1 1 1\n1 1 1\n0 1 1", "3 3\n1 0 1\n1 0 1\n0 0 0", "3 2\n0 0\n0 0\n0 0"]
1 second
["3\n1 1\n1 2\n2 2", "-1", "0"]
NoteThe sequence of operations in the first example: $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
ad641a44ecaf78ca253b199f3d40ef96
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.
1,200
If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.
standard output
PASSED
6c620bf13f304becd6696f5ae1aad622
train_003.jsonl
1566484500
You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x &lt; n$$$ and $$$1 \le y &lt; m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.
256 megabytes
import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class SquareFilling { public static void main(String[] args) { Scanner input = new Scanner(System.in); int m = input.nextInt(); int n = input.nextInt(); int[][] matrix = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { matrix[i][j] = input.nextInt(); } } List<Integer[]> xys = new ArrayList<>(); for (int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if (i < m-1 && j < n-1 && matrix[i][j] * matrix[i][j+1] * matrix[i+1][j] * matrix[i+1][j+1] > 0) { matrix[i][j] = 2; matrix[i][j + 1] = 2; matrix[i + 1][j] = 2; matrix[i + 1][j + 1] = 2; xys.add(new Integer[] {i + 1, j + 1}); } } } int count = 0; for (int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if (matrix[i][j] == 1) { count++; } } } if(count != 0) { System.out.println(-1); } else { System.out.println(xys.size()); for(Integer[] xy: xys) { System.out.println(xy[0] + " " + xy[1]); } } } }
Java
["3 3\n1 1 1\n1 1 1\n0 1 1", "3 3\n1 0 1\n1 0 1\n0 0 0", "3 2\n0 0\n0 0\n0 0"]
1 second
["3\n1 1\n1 2\n2 2", "-1", "0"]
NoteThe sequence of operations in the first example: $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
ad641a44ecaf78ca253b199f3d40ef96
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.
1,200
If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.
standard output
PASSED
c9ee32e386105885caf7f7c4fdfafafa
train_003.jsonl
1566484500
You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x &lt; n$$$ and $$$1 \le y &lt; m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.
256 megabytes
// B. Square Filling import java.io.*; import java.util.*; public class CF082219_B { FastScanner in; PrintWriter out; void solve() { int m = in.nextInt(), n = in.nextInt(); int[][] expect = new int[m][n]; ArrayList<Index> ar = new ArrayList<Index>(); int i, j, k; int[][] ret = new int[m][n]; for(i=0; i<m; i++) { for(j=0; j<n; j++) { expect[i][j] = in.nextInt(); if((m<2 || n<2) && expect[i][j]==1) { out.println("-1"); return; } } } for(i=0; i<m; i++) { for(j=0; j<n; j++) { if(expect[i][j]==0) continue; if(expect[i][j]==1 && ret[i][j]==1) { if(i<m-1 && j<n-1) { if(expect[i+1][j]==0 || expect[i][j+1]==0 || expect[i+1][j+1]==0) { continue; } ret[i+1][j] = ret[i][j+1] = ret[i+1][j+1] = 1; ar.add(new Index(i, j)); } continue; } if(i==m-1 || j==n-1) { out.println("-1"); return; } if(expect[i+1][j]==0 || expect[i][j+1]==0 || expect[i+1][j+1]==0) { out.println("-1"); return; } ret[i+1][j] = ret[i][j+1] = ret[i+1][j+1] = 1; ar.add(new Index(i, j)); } } out.println(ar.size()); for(i=0; i<ar.size(); i++) { Index ind = ar.get(i); out.print((ind.x+1) + " " + (ind.y+1)); out.println(); } } void run() { try { in = new FastScanner(new File("RealA.in")); out = new PrintWriter(new File("RealA.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } private class Index { int x; int y; public Index(int a, int b) { x = a; y = b; } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new CF082219_B().runIO(); } }
Java
["3 3\n1 1 1\n1 1 1\n0 1 1", "3 3\n1 0 1\n1 0 1\n0 0 0", "3 2\n0 0\n0 0\n0 0"]
1 second
["3\n1 1\n1 2\n2 2", "-1", "0"]
NoteThe sequence of operations in the first example: $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
ad641a44ecaf78ca253b199f3d40ef96
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.
1,200
If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.
standard output
PASSED
bd2440fad82ee1c0f890d93f1ef444d5
train_003.jsonl
1566484500
You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x &lt; n$$$ and $$$1 \le y &lt; m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.
256 megabytes
import javafx.util.Pair; import java.io.*; import java.util.Deque; import java.util.LinkedList; import java.util.StringTokenizer; public class Div2B71 { public static void main(String[] args) throws IOException { IoHandler ioHandler = new IoHandler(); new Task().solve(ioHandler, ioHandler.out); ioHandler.out.close(); } private static class Task { private void solve(IoHandler reader, PrintWriter writer) throws IOException { int n = reader.nextInt(), m = reader.nextInt(); int[][] mat = new int[n][m]; //read matrix for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { mat[i][j] = reader.nextInt(); } } Deque<Pair<Integer, Integer>> deque = new LinkedList<>(); //now iterate and check if 2*2 matrix ending at i,j is filled with 1, if so then include this in solution for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) { if (mat[i - 1][j - 1] * mat[i - 1][j] * mat[i][j - 1] * mat[i][j] > 0) { mat[i - 1][j - 1] = 2; mat[i - 1][j] = 2; mat[i][j - 1] = 2; mat[i][j] = 2; deque.addLast(new Pair<>(i, j)); } } } int count = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (mat[i][j] == 1) { count++; } } } if (count > 0) { writer.println(-1); } else { writer.println(deque.size()); while (!deque.isEmpty()) { Pair<Integer, Integer> index = deque.pollFirst(); writer.println(index.getKey() + " " + index.getValue()); } } } } private static class IoHandler { private final PrintWriter out; private final BufferedReader reader; private StringTokenizer tokenizer; IoHandler() throws IOException { boolean local = new File("input").exists(); InputStream stream = local ? new FileInputStream("input") : System.in; out = local ? new PrintWriter(new FileOutputStream("output")) : new PrintWriter(System.out); reader = new BufferedReader(new InputStreamReader(stream), 32768); } private String nextString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextString()); } } }
Java
["3 3\n1 1 1\n1 1 1\n0 1 1", "3 3\n1 0 1\n1 0 1\n0 0 0", "3 2\n0 0\n0 0\n0 0"]
1 second
["3\n1 1\n1 2\n2 2", "-1", "0"]
NoteThe sequence of operations in the first example: $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
ad641a44ecaf78ca253b199f3d40ef96
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.
1,200
If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.
standard output
PASSED
7fb8b742cd78b4200c78eadb11dd8199
train_003.jsonl
1566484500
You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x &lt; n$$$ and $$$1 \le y &lt; m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.
256 megabytes
import org.omg.CORBA.INTERNAL; import java.io.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; public class Newbie { static InputReader sc = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { solver s = new solver(); long t = 1; while (t > 0) { s.solve(); t--; } out.close(); } /* static class descend implements Comparator<pair1> { public int compare(pair1 o1, pair1 o2) { if (o1.pop != o2.pop) return (int) (o1.pop - o2.pop); else return o1.in - o2.in; } }*/ static class InputReader { public BufferedReader br; public StringTokenizer token; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream), 32768); token = null; } public String sn() { while (token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } public int ni() { return Integer.parseInt(sn()); } public String snl() throws IOException { return br.readLine(); } public long nlo() { return Long.parseLong(sn()); } public double nd() { return Double.parseDouble(sn()); } public int[] na(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.ni(); return a; } public long[] nal(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = sc.nlo(); return a; } } static class card { long a; int cnt; int i; public card(long a, int cnt, int i) { this.a = a; this.cnt = cnt; this.i = i; } } static class ascend implements Comparator<String> { public int compare(String o1, String o2) { if (o1.length() != o2.length()) return o1.length() - o2.length(); else return (o1.compareTo(o2)); } } static class extra { static boolean v[] = new boolean[100001]; static List<Integer> l = new ArrayList<>(); static int t; static void shuffle(int a[]) { for (int i = 0; i < a.length; i++) { int t = (int) Math.random() * a.length; int x = a[t]; a[t] = a[i]; a[i] = x; } } static void shufflel(long a[]) { for (int i = 0; i < a.length; i++) { int t = (int) Math.random() * a.length; long x = a[t]; a[t] = a[i]; a[i] = x; } } static long gcd(long a, long b) { if (b == 0) return a; else return gcd(b, a % b); } static boolean valid(int i, int j, int r, int c) { if (i >= 0 && i < r && j >= 0 && j < c) { // System.out.println(i+" /// "+j); return true; } else { // System.out.println(i+" //f "+j); return false; } } static void seive() { for (int i = 2; i < 100001; i++) { if (!v[i]) { t++; l.add(i); for (int j = 2 * i; j < 100001; j += i) v[j] = true; } } } static int binary(LinkedList<Integer> a, long val, int n) { int mid = 0, l = 0, r = n - 1, ans = 0; while (l <= r) { mid = (l + r) >> 1; if (a.get(mid) == val) { r = mid - 1; ans = mid; } else if (a.get(mid) > val) r = mid - 1; else { l = mid + 1; ans = l; } } return (ans + 1); } static long fastexpo(long x, long y) { long res = 1; while (y > 0) { if ((y & 1) == 1) { res *= x; } y = y >> 1; x = x * x; } return res; } static long lfastexpo(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; } /* void dijsktra(int s, List<pair> l[], int n) { PriorityQueue<pair> pq = new PriorityQueue<>(new ascend()); int dist[] = new int[100005]; boolean v[] = new boolean[100005]; for (int i = 1; i <= n; i++) dist[i] = 1000000000; dist[s] = 0; for (int i = 1; i < n; i++) { if (i == s) pq.add(new pair(s, 0)); else pq.add(new pair(i, 1000000000)); } while (!pq.isEmpty()) { pair node = pq.remove(); v[node.a] = true; for (int i = 0; i < l[node.a].size(); i++) { int v1 = l[node.a].get(i).a; int w = l[node.a].get(i).b; if (v[v1]) continue; if ((dist[node.a] + w) < dist[v1]) { dist[v1] = dist[node.a] + w; pq.add(new pair(v1, dist[v1])); } } } }*/ } static class pair { int a; int b; public pair(int a, int b) { this.a = a; this.b = b; } } static class pair1 { pair p; int in; public pair1(pair a, int n) { this.p = a; this.in = n; } } static int inf = 5000013; static class solver { DecimalFormat df = new DecimalFormat("0.000000"); extra e = new extra(); int mod = 1000000007; int n, m; int a[][]; void solve() throws IOException { n = sc.ni(); m = sc.ni(); a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = sc.ni(); } } int f[][] = new int[n][m]; List<pair> l = new ArrayList<>(); for (int i = 0; i < n-1; i++) { for (int j = 0; j < m-1; j++) { if (a[i][j] == 1) { if (v1(i, j)) { int x1[] = {0, 1, 1}; int y1[] = {1, 0, 1}; for (int ii = 0; ii < 3; ii++) { int x = i + x1[ii]; int y = j + y1[ii]; if (e.valid(x, y, n, m)) f[x][y] = 1; } f[i][j] = 1; l.add(new pair(i + 1, j + 1)); } } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (a[i][j] == 1 && f[i][j] != 1) { System.out.println(-1); System.exit(0); } } } int len = l.size(); System.out.println(len); l.forEach(n1 -> System.out.println(n1.a + " " + n1.b)); } boolean v1(int i, int j) { int x1[] = {0, 1, 1}; int y1[] = {1, 0, 1}; for (int ii = 0; ii < 3; ii++) { int x = i + x1[ii]; int y = j + y1[ii]; if (e.valid(x, y, n, m) && a[x][y] == 0) return false; } return true; } } }
Java
["3 3\n1 1 1\n1 1 1\n0 1 1", "3 3\n1 0 1\n1 0 1\n0 0 0", "3 2\n0 0\n0 0\n0 0"]
1 second
["3\n1 1\n1 2\n2 2", "-1", "0"]
NoteThe sequence of operations in the first example: $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
ad641a44ecaf78ca253b199f3d40ef96
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.
1,200
If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.
standard output
PASSED
c3d9b7309652f7ed6c30cc83277c84c4
train_003.jsonl
1566484500
You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x &lt; n$$$ and $$$1 \le y &lt; m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Comp { public static void main(String[] args) throws Exception { BufferedReader bReader = new BufferedReader( new InputStreamReader(System.in)); String[] arr = bReader.readLine().split(" "); int row = Integer.parseInt(arr[0]), col = Integer.parseInt(arr[1]); Integer[][] mat = new Integer[row][col]; Integer[][] mat1 = new Integer[row][col]; for (int i = 0; i < row; i++) { String[] arr1 = bReader.readLine().split(" "); for (int j = 0; j < col; j++) { mat[i][j] = Integer.parseInt(arr1[j]); mat1[i][j] = 0; } } List<String> steps = new ArrayList<String>(); for (int i = 0; i < row - 1; i++) { for (int j = 0; j < col - 1; j++) { if (mat[i][j] == 1 && mat[i + 1][j] == 1 && mat[i][j + 1] == 1 && mat[i + 1][j + 1] == 1) { mat1[i][j] = 1; mat1[i][j + 1] = 1; mat1[i + 1][j + 1] = 1; mat1[i + 1][j] = 1; int s = i + 1, p = j + 1; steps.add(s + " " + p); } } } boolean possible = true; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (mat[i][j] != mat1[i][j]) { possible = false; break; } } } if (!possible) { System.out.println(-1); } else if (steps.size() == 0) { System.out.println(0); } else { System.out.println(steps.size()); for (String val : steps) { System.out.println(val); } } } }
Java
["3 3\n1 1 1\n1 1 1\n0 1 1", "3 3\n1 0 1\n1 0 1\n0 0 0", "3 2\n0 0\n0 0\n0 0"]
1 second
["3\n1 1\n1 2\n2 2", "-1", "0"]
NoteThe sequence of operations in the first example: $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
ad641a44ecaf78ca253b199f3d40ef96
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.
1,200
If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.
standard output
PASSED
330ea5f9e73a00906293363d0910dde2
train_003.jsonl
1566484500
You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x &lt; n$$$ and $$$1 \le y &lt; m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.
256 megabytes
// This template code suggested by KT BYTE Computer Science Academy // for use in reading and writing files for USACO problems. // https://content.ktbyte.com/problem.java import java.util.*; import java.io.*; public class SquareFilling { static StreamTokenizer in; static int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } static int n; static int m; static int[][] A; static int[][] B; public static void main(String[] args) throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); n = nextInt(); m = nextInt(); A = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { A[i][j] = nextInt(); } } B = new int[n][m]; boolean not_work = false; StringBuilder sb = new StringBuilder(); int steps = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (A[i][j] == 1 && B[i][j] != 1) { // we need to check the 4 (2 by 2s) surrounding String check_results = check(i, j); if (check_results.equals("-1")) { out.println(check_results); not_work = true; break; } sb.append(check_results); sb.append('\n'); steps++; } } if (not_work) break; } if (!not_work) { out.println(steps); out.println(sb.toString()); } out.close(); } static String check(int i, int j) { if (i - 1 >= 0 && j + 1 < m) { if (A[i-1][j] == 1 && A[i-1][j+1] == 1 && A[i][j] == 1 && A[i][j+1] == 1) { B[i-1][j] = 1; B[i-1][j+1] = 1; B[i][j] = 1; B[i][j+1] = 1; return (i) + " " + (j+1); } } if (i - 1 >= 0 && j - 1 >= 0) { if (A[i-1][j] == 1 && A[i-1][j-1] == 1 && A[i][j] == 1 && A[i][j-1] == 1) { B[i-1][j] = 1; B[i-1][j-1] = 1; B[i][j] = 1; B[i][j-1] = 1; return (i) + " " + (j); } } if (i + 1 < n && j + 1 < m) { if (A[i][j] == 1 && A[i][j+1] == 1 && A[i+1][j] == 1 && A[i+1][j+1] == 1) { B[i][j] = 1; B[i][j+1] = 1; B[i+1][j] = 1; B[i+1][j+1] = 1; return (i+1) + " " + (j+1); } } if (i + 1 < n && j - 1 >= 0) { if (A[i+1][j] == 1 && A[i+1][j-1] == 1 && A[i][j] == 1 && A[i][j-1] == 1) { B[i+1][j] = 1; B[i+1][j-1] = 1; B[i][j] = 1; B[i][j-1] = 1; return (i+1) + " " + (j); } } return "-1"; } }
Java
["3 3\n1 1 1\n1 1 1\n0 1 1", "3 3\n1 0 1\n1 0 1\n0 0 0", "3 2\n0 0\n0 0\n0 0"]
1 second
["3\n1 1\n1 2\n2 2", "-1", "0"]
NoteThe sequence of operations in the first example: $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
ad641a44ecaf78ca253b199f3d40ef96
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.
1,200
If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.
standard output
PASSED
57dc977c3ffeb179a8919bece6647e5c
train_003.jsonl
1566484500
You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x &lt; n$$$ and $$$1 \le y &lt; m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.
256 megabytes
import java.util.Scanner; public class NewClass{ public static void main(String args[]) throws Exception{ Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int m = scn.nextInt(); int[][]a = new int[n][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ a[i][j] = scn.nextInt(); } } int moves = 0; int[]b = new int[5005]; int[][]fin = new int[n][m]; int x = 0; for(int i = 0; i < n-1; i++){ for(int j = 0; j < m-1; j++){ if(a[i][j]==1&&a[i+1][j]==1&&a[i][j+1]==1&&a[i+1][j+1]==1){ fin[i][j] = 1; fin[i][j+1] = 1; fin[i+1][j] = 1; fin[i+1][j+1] = 1; b[x++] = i+1; b[x++] = j+1; moves++; } } } for(int i = 0; i < n; i++){ for(int j = 0 ; j < m; j++){ if(a[i][j]!=fin[i][j]){ System.out.println(-1); System.exit(0); } } } System.out.println(moves); for(int i=0; i < moves*2; i+=2){ System.out.println(b[i]+" "+b[i+1]); } } }
Java
["3 3\n1 1 1\n1 1 1\n0 1 1", "3 3\n1 0 1\n1 0 1\n0 0 0", "3 2\n0 0\n0 0\n0 0"]
1 second
["3\n1 1\n1 2\n2 2", "-1", "0"]
NoteThe sequence of operations in the first example: $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy" ]
ad641a44ecaf78ca253b199f3d40ef96
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.
1,200
If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.
standard output
PASSED
74012a66f6c8282bac7bb8c5c73a06a5
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
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 Pradyumn Agrawal coderbond007 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int[] from = new int[n - 1]; int[] to = new int[n - 1]; for (int i = 0; i < n - 1; i++) { from[i] = in.nextInt() - 1; to[i] = in.nextInt() - 1; } int[][] g = packU(n, from, to); TaskC.MinHeap h = new TaskC.MinHeap(n); for (int i = 0; i < n; i++) { h.update(i, -(a[i] + 2)); } int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { h.update(i, -a[i]); for (int e : g[i]) { h.update(e, -(a[e] + 1)); } min = Math.min(min, -h.min()); h.update(i, -(a[i] + 2)); for (int e : g[i]) { h.update(e, -(a[e] + 2)); } } out.println(min); } static int[][] packU(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) p[f]++; for (int t : to) p[t]++; 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]; g[to[i]][--p[to[i]]] = from[i]; } return g; } public static class MinHeap { public int[] a; public int[] map; public int[] imap; public int n; public int pos; public static int INF = Integer.MAX_VALUE; public MinHeap(int m) { n = m + 2; a = new int[n]; map = new int[n]; imap = new int[n]; Arrays.fill(a, INF); Arrays.fill(map, -1); Arrays.fill(imap, -1); pos = 1; } public int update(int ind, int x) { int ret = imap[ind]; if (imap[ind] < 0) { a[pos] = x; map[pos] = ind; imap[ind] = pos; pos++; up(pos - 1); } else { int o = a[ret]; a[ret] = x; up(ret); down(ret); // if(a[ret] > o){ // up(ret); // }else{ // down(ret); // } } return x; } public int min() { return a[1]; } private void up(int cur) { for (int c = cur, p = c >>> 1; p >= 1 && a[p] > a[c]; c >>>= 1, p >>>= 1) { int d = a[p]; a[p] = a[c]; a[c] = d; int e = imap[map[p]]; imap[map[p]] = imap[map[c]]; imap[map[c]] = e; e = map[p]; map[p] = map[c]; map[c] = e; } } private void down(int cur) { for (int c = cur; 2 * c < pos; ) { int b = a[2 * c] < a[2 * c + 1] ? 2 * c : 2 * c + 1; if (a[b] < a[c]) { int d = a[c]; a[c] = a[b]; a[b] = d; int e = imap[map[c]]; imap[map[c]] = imap[map[b]]; imap[map[b]] = e; e = map[c]; map[c] = map[b]; map[b] = e; c = b; } else { break; } } } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int pnumChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c == ',') { c = read(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } 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
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
3db046ff75820cff911356ed326304f5
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
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.Iterator; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.AbstractMap; import java.util.TreeMap; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int M; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] a = IOUtils.readIntArray(in, n); M = ArrayUtils.maxElement(a); ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < adj.length; i++) adj[i] = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { int v = in.readInt() - 1, u = in.readInt() - 1; adj[v].add(u); adj[u].add(v); } TreeMap<Integer, Integer> counts = new TreeMap<>(); for (int val : a) incr(val, counts); int res = Integer.MAX_VALUE; for (int start = 0; start < n; start++) { decr(a[start], counts); for (int nxt : adj[start]) decr(a[nxt], counts); int here = counts.isEmpty() ? Integer.MIN_VALUE : counts.lastKey() + 2; for (int nxt : adj[start]) here = Math.max(here, a[nxt] + 1); here = Math.max(here, a[start]); res = Math.min(res, here); incr(a[start], counts); for (int nxt : adj[start]) incr(a[nxt], counts); } out.printLine(res); } private void incr(int val, TreeMap<Integer, Integer> counts) { if (val < M - 2 || val > M) return; counts.merge(val, 1, Integer::sum); } private void decr(int val, TreeMap<Integer, Integer> counts) { if (val < M - 2 || val > M) return; counts.merge(val, -1, Integer::sum); if (counts.get(val) == 0) counts.remove(val); } } static interface IntReversableCollection extends IntCollection { } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void removeAt(int index); default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } static class ArrayUtils { public static int maxElement(int[] array) { return new IntArray(array).max(); } } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } default public int max() { int result = Integer.MIN_VALUE; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { int current = it.value(); if (current > result) { result = current; } } return result; } } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void removeAt(int index) { throw new UnsupportedOperationException(); } } static interface IntCollection extends IntStream { public int size(); } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } 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 int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return 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
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
480c946a3c44d545050cc1d2a03d272d
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
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.Iterator; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.AbstractMap; import java.util.TreeMap; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int M; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] a = IOUtils.readIntArray(in, n); M = ArrayUtils.maxElement(a); ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < adj.length; i++) adj[i] = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { int v = in.readInt() - 1, u = in.readInt() - 1; adj[v].add(u); adj[u].add(v); } TreeMap<Integer, Integer> counts = new TreeMap<>(); for (int val : a) incr(val, counts); int res = Integer.MAX_VALUE; for (int start = 0; start < n; start++) { decr(a[start], counts); for (int nxt : adj[start]) decr(a[nxt], counts); int here = counts.isEmpty() ? Integer.MIN_VALUE : counts.lastKey() + 2; for (int nxt : adj[start]) here = Math.max(here, a[nxt] + 1); here = Math.max(here, a[start]); res = Math.min(res, here); incr(a[start], counts); for (int nxt : adj[start]) incr(a[nxt], counts); } out.printLine(res); } private void incr(int val, TreeMap<Integer, Integer> counts) { if (val < M - 5 || val > M + 5) return; counts.merge(val, 1, Integer::sum); } private void decr(int val, TreeMap<Integer, Integer> counts) { if (val < M - 5 || val > M + 5) return; counts.merge(val, -1, Integer::sum); if (counts.get(val) == 0) counts.remove(val); } } static interface IntReversableCollection extends IntCollection { } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void removeAt(int index); default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } static class ArrayUtils { public static int maxElement(int[] array) { return new IntArray(array).max(); } } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } default public int max() { int result = Integer.MIN_VALUE; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { int current = it.value(); if (current > result) { result = current; } } return result; } } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void removeAt(int index) { throw new UnsupportedOperationException(); } } static interface IntCollection extends IntStream { public int size(); } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } 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 int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return 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
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
d1428a51a5aa0ee63a30cecd2d99066c
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.Map; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.io.BufferedWriter; import java.io.IOException; import java.util.AbstractMap; import java.util.TreeMap; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] a = IOUtils.readIntArray(in, n); int MAX = ArrayUtils.maxElement(a); ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < adj.length; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int u = in.readInt() - 1; int v = in.readInt() - 1; adj[u].add(v); adj[v].add(u); } Counter counter = new Counter(MAX); for (int val : a) counter.inc(val); int res = Integer.MAX_VALUE; for (int start = 0; start < n; start++) { int here = a[start]; counter.dec(a[start]); for (int nxt : adj[start]) { counter.dec(a[nxt]); here = Math.max(here, a[nxt] + 1); } if (!counter.isEmpty()) { here = Math.max(here, counter.lastKey() + 2); } for (int nxt : adj[start]) { counter.inc(a[nxt]); } counter.inc(a[start]); res = Math.min(res, here); } out.printLine(res); } class Counter { TreeMap<Integer, Integer> tm = new TreeMap<>(); int LOWER_BOUND; public Counter(int MAX) { LOWER_BOUND = MAX - 2; } void inc(int key) { if (key < LOWER_BOUND) return; tm.merge(key, 1, Integer::sum); } void dec(int key) { if (key < LOWER_BOUND) return; tm.merge(key, -1, Integer::sum); if (tm.get(key) == 0) tm.remove(key); } boolean isEmpty() { return tm.isEmpty(); } int lastKey() { if (tm.isEmpty()) throw new RuntimeException(); return tm.lastKey(); } } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void removeAt(int index); default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } } 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 int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return 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); } } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } default public int max() { int result = Integer.MIN_VALUE; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { int current = it.value(); if (current > result) { result = current; } } return result; } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static interface IntReversableCollection extends IntCollection { } static class ArrayUtils { public static int maxElement(int[] array) { return new IntArray(array).max(); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static interface IntCollection extends IntStream { public int size(); } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void removeAt(int index) { throw new UnsupportedOperationException(); } } }
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
5c309a0fe04cde0b569693d964342847
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.Map; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.io.BufferedWriter; import java.io.IOException; import java.util.AbstractMap; import java.util.TreeMap; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] a = IOUtils.readIntArray(in, n); int MAX = ArrayUtils.maxElement(a); ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < adj.length; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int u = in.readInt() - 1; int v = in.readInt() - 1; adj[u].add(v); adj[v].add(u); } Counter counter = new Counter(MAX); for (int val : a) counter.inc(val); int res = Integer.MAX_VALUE; for (int start = 0; start < n; start++) { int here = a[start]; counter.dec(a[start]); for (int nxt : adj[start]) { counter.dec(a[nxt]); here = Math.max(here, a[nxt] + 1); } if (!counter.isEmpty()) { here = Math.max(here, counter.lastKey() + 2); } for (int nxt : adj[start]) { counter.inc(a[nxt]); } counter.inc(a[start]); res = Math.min(res, here); } out.printLine(res); } class Counter { TreeMap<Integer, Integer> tm = new TreeMap<>(); int LOWER_BOUND; public Counter(int MAX) { LOWER_BOUND = MAX - 1; } void inc(int key) { if (key < LOWER_BOUND) return; tm.merge(key, 1, Integer::sum); } void dec(int key) { if (key < LOWER_BOUND) return; tm.merge(key, -1, Integer::sum); if (tm.get(key) == 0) tm.remove(key); } boolean isEmpty() { return tm.isEmpty(); } int lastKey() { if (tm.isEmpty()) throw new RuntimeException(); return tm.lastKey(); } } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void removeAt(int index); default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } } 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 int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return 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); } } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } default public int max() { int result = Integer.MIN_VALUE; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { int current = it.value(); if (current > result) { result = current; } } return result; } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static interface IntReversableCollection extends IntCollection { } static class ArrayUtils { public static int maxElement(int[] array) { return new IntArray(array).max(); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static interface IntCollection extends IntStream { public int size(); } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void removeAt(int index) { throw new UnsupportedOperationException(); } } }
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
36f9ad1240f34665e0d0501b30e9811a
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; /** * Created by Marcos on 23/8/2017. */ public class C { public static void main(String[] args) { InputReader in = new InputReader(System.in); int n = in.nextInt(); int maximumBankStrength = Integer.MIN_VALUE; int computerStrength; int x = 0, y = 0; int[] bankStrength = new int[n + 1]; boolean[] bankOffline = new boolean[n + 1]; ArrayList[] connections = new ArrayList[n + 1]; for(int i = 1; i <= n; i++){ bankStrength[i] = in.nextInt(); if(maximumBankStrength < bankStrength[i]) maximumBankStrength = bankStrength[i]; } for(int i = 0; i <= n; i++) connections[i] = new ArrayList(); for(int i = 0; i < n - 1; i++){ int u = in.nextInt(); int v = in.nextInt(); connections[u].add(v); connections[v].add(u); } for(int i=1; i<=n; i++){ if(bankStrength[i] == maximumBankStrength) x++; else if(bankStrength[i] == maximumBankStrength-1) y++; } int res = maximumBankStrength + 2; for(int i=1; i<=n; i++){ // minus if(bankStrength[i] == maximumBankStrength) x--; else if(bankStrength[i] == maximumBankStrength-1) y--; for(int j=0; j<connections[i].size(); j++){ int pos = (int) connections[i].get(j); if(bankStrength[pos] == maximumBankStrength){ x--; y++; } else if(bankStrength[pos] == maximumBankStrength-1) y--; } // check the needed strength and update the answer if(x == 0){ res = Math.min(res, maximumBankStrength+1); if(y == 0) res = Math.min(res, maximumBankStrength); } // plus if(bankStrength[i] == maximumBankStrength) x++; else if(bankStrength[i] == maximumBankStrength-1) y++; for(int j=0; j<connections[i].size(); j++){ int pos = (int) connections[i].get(j); if(bankStrength[pos] == maximumBankStrength){ x++; y--; } else if(bankStrength[pos] == maximumBankStrength-1) y++; } } System.out.println(res); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
eb98c1231819faa6ad1ff3181db343fc
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.stream.IntStream; import java.util.Arrays; import java.io.IOException; import java.util.OptionalInt; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; 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; MyBufferedReader in = new MyBufferedReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, MyBufferedReader in, PrintWriter out) { int n = in.getAnInt(); int[] strengths = in.getALineOfInts(n); ArrayList<ArrayList<Integer>> edges = new ArrayList<>(); for (int i = 0; i < n; i++) { edges.add(new ArrayList<>()); } for (int i = 0; i < n - 1; i++) { int[] data = in.getALineOfInts(2); int v1 = data[0] - 1; int v2 = data[1] - 1; edges.get(v1).add(v2); edges.get(v2).add(v1); } int maxStrength = Arrays.stream(strengths).max().getAsInt(); int[] cnts = new int[3]; for (int s : strengths) { int diff = maxStrength - s; if (diff < 3) { cnts[diff]++; } } int minNeeded = Integer.MAX_VALUE; for (int start = 0; start < n; start++) { int neededIfAtStart = strengths[start]; int diffWithStart = maxStrength - strengths[start]; if (diffWithStart < 3) { cnts[diffWithStart]--; } for (int nbr : edges.get(start)) { int diff = maxStrength - strengths[nbr]; if (diff < 3) { cnts[diff]--; } neededIfAtStart = Math.max(neededIfAtStart, strengths[nbr] + 1); } for (int diff = 0; diff < 3; diff++) { if (cnts[diff] > 0) { neededIfAtStart = Math.max(neededIfAtStart, maxStrength - diff + 2); break; } } for (int nbr : edges.get(start)) { int diff = maxStrength - strengths[nbr]; if (diff < 3) { cnts[diff]++; } } if (diffWithStart < 3) { cnts[diffWithStart]++; } minNeeded = Math.min(minNeeded, neededIfAtStart); } out.println(minNeeded); } } static class MyBufferedReader { BufferedReader in; public MyBufferedReader(InputStream s) { this.in = new BufferedReader(new InputStreamReader(s)); } public int getAnInt() { int res = -1; try { res = Integer.parseInt(new StringTokenizer(in.readLine()).nextToken()); } catch (IOException e) { e.printStackTrace(); } return res; } public int[] getALineOfInts(int numExpected) { if (numExpected == 0) { return new int[0]; } int[] res = new int[numExpected]; StringTokenizer st = null; try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } for (int i = 0; i < numExpected; i++) res[i] = Integer.parseInt(st.nextToken()); return res; } } }
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
01696dbde6c946fddcd341fdafc8b896
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.StringTokenizer; /** */ public class MainC { public static void main(String[] args) { FastScanner in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); run(in, System.out); } public static void runTest(InputStream is, PrintStream out) { FastScanner in = new FastScanner(new BufferedReader(new InputStreamReader(is))); run(in, out); } public static class Node { int idx; int str; boolean offline = false; List<Integer> links = new ArrayList<>(); public Node(int idx, int str) { this.idx = idx; this.str = str; } } public static void run(FastScanner sc, PrintStream out) { int n = sc.nextInt(); Node[] nodes = new Node[n]; int maxstr = 0; for (int i = 0; i < n; i++) { int str = sc.nextInt(); nodes[i] = new Node(i, str); if (str > nodes[maxstr].str) maxstr = i; } for (int i = 0; i < n - 1; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; nodes[a].links.add(b); nodes[b].links.add(a); } Queue<Node> queue = new LinkedList<Node>(); System.err.println("Node max = " + (maxstr + 1)); int start = maxstr; // If there is a semineighbour with same str, it is best to start in // the middle. for (Integer i : nodes[maxstr].links) { for (Integer j : nodes[i].links) { if (j != maxstr && nodes[j].str == nodes[maxstr].str) { //System.err.println("As str["+j+"]="+nodes[j].str +", start will be " + start); start = i; break; } } } System.err.println("Start = " + (start + 1)); queue.add(nodes[start]); int res = Integer.MIN_VALUE; while (!queue.isEmpty()) { // Get the Node with biggest str Node node = queue.poll(); node.offline = true; //System.err.println("Killing node " + (node.idx + 1)); if (node.str > res) res = node.str; // Increase str for (Integer i : node.links) { if (!nodes[i].offline) { nodes[i].str++; queue.add(nodes[i]); for (Integer j : nodes[i].links) { if (node.idx != j) nodes[j].str++; } } } } out.print(res); } static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
95a7728eeb1d6a2529e196a28c46f5d0
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import sun.misc.resources.Messages_pt_BR; import javax.print.attribute.standard.MediaPrintableArea; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; /** * Created by Firеfly on 1/1/2017. */ public class Task { public static void main(String[] args) throws IOException { Emaxx emaxx = new Emaxx(); } } class Emaxx { FScanner fs; PrintWriter pw; int n, m; ArrayList<Integer>[] graph; Emaxx() throws IOException { fs = new FScanner(new InputStreamReader(System.in)); // pw = new PrintWriter(new FileWriter("arithnumbers.out")); // fs = new FScanner(new FileReader("C:\\Users\\Firеfly\\Desktop\\New Text Document.txt")); // fs = new FScanner(new FileReader("input.txt"));; // pw = new PrintWriter("output.txt"); PrintWriter pw = new PrintWriter(System.out); int n = fs.nextInt(); int[] vals = new int[n]; for (int i = 0; i<n; i++) vals[i] = fs.nextInt(); ArrayList<Integer> graph[] = new ArrayList[n]; for (int i = 0;i<n; i++) graph[i] = new ArrayList<>(); for (int i = 0; i<n-1; i++) { int to = fs.nextInt()-1, from = fs.nextInt()-1; graph[to].add(from); graph[from].add(to); } int max = (int) -1e9; for (int i = 0; i<n; i++) max = Math.max(max, vals[i]); int[] howm = new int[2]; for (int i = 0; i<n; i++) { if (vals[i] == max) howm[1]++; else if (vals[i] == max-1) howm[0]++; } int lowest = max+2; int on = howm[1], zer = howm[0]; for (int i = 0; i<n; i++) { int curr = max+2; if (vals[i] == max) howm[1]--; else if (vals[i] == max-1) howm[0]--; for (int j : graph[i]) { if (vals[j] == max) { howm[1]--; howm[0]++; } else if (vals[j] == max-1) howm[0]--; } if (howm[1] == 0) { curr = howm[0] == 0? max : max+1; } lowest = Math.min(lowest, curr); howm[1] = on; howm[0] = zer; } pw.println(lowest); pw.close(); } int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a%b); } long bin(long need) { long res = 1; for (long q = 0; q<need; q++) res*=2; return res; } } class FScanner { BufferedReader br; StringTokenizer st; FScanner(InputStreamReader isr) { br = new BufferedReader(isr); } FScanner(FileReader fr) { br = new BufferedReader(fr); } String nextToken() throws IOException{ while (st == null || !st.hasMoreTokens()) { String s = br.readLine(); if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { return br.readLine(); } char nextChar() throws IOException { return (char) br.read(); } }
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
4e6ac344a70ea4fc5278fcc618e48b65
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class P796C { static Bank[] banks; public static void main(String[] args) { FastScanner scan = new FastScanner(); int n = scan.nextInt(); banks = new Bank[n]; for (int i = 0; i < n; i++) banks[i] = new Bank(i, scan.nextInt()); for (int i = 0; i < n-1; i++) { int a = scan.nextInt()-1; int b = scan.nextInt()-1; banks[a].add(b); banks[b].add(a); } int maxS = Integer.MIN_VALUE; for (int i = 0; i < n; i++) maxS = Math.max(maxS, banks[i].strength); int start = -1; int neigh = -1; for (int i = 0; i < n; i++) { int num = numNeigh(banks[i], maxS); if (num > neigh) { if (banks[i].strength == maxS || num > 1) { start = i; neigh = num; } } } banks[start].online = false; System.out.println(max(start, 0)); } static int max(int start, int add) { int m = banks[start].strength; for (int i = 0; i < banks[start].next.size(); i++) { int x = banks[start].next.get(i); if (!banks[x].online) continue; banks[x].strength += 1+add; banks[x].online = false; m = Math.max(m, max(x, 1)); } return m; } static int numNeigh(Bank bank, int str) { int n = 0; for (int i = 0; i < bank.next.size(); i++) if (banks[bank.next.get(i)].strength == str) n++; return n; } static class Bank { boolean online = true; int index, strength; ArrayList<Integer> next = new ArrayList<>(); Bank(int i, int s) { index = i; strength = s; } void add(int n) { next.add(n); } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextLine() { String line = ""; try { line = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return line; } } }
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
53a6f5a0bea9f9dd0c6b7b8bd29626fd
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.Queue; public class C { public static void main(String[] args) { FastScannerC sc = new FastScannerC(System.in); int N = sc.nextInt(); Vertex[] ver = new Vertex[N]; int max = Integer.MIN_VALUE; int max_times = 0; int max_ind = -1; for(int i = 0; i<N; i++){ int p = sc.nextInt(); ver[i] = new Vertex(p); if(p > max){ max_ind = i; max_times = 1; max = p; } else if(p == max){ max_times++; } } for(int i = 1; i<N; i++){ int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; ver[a].edges.add(b); ver[b].edges.add(a); } boolean found = false; if(max_times == 1){ //BFS Queue<Integer> q = new LinkedList<>(); q.add(max_ind); int steps = 1; ver[max_ind].visited = true; while(!q.isEmpty()){ for(int i = 0, len = q.size(); i<len; i++){ int current = q.remove(); if(ver[current].power > max){ found = true; break; } for(int e : ver[current].edges){ if(!ver[e].visited){ q.add(e); ver[e].visited = true; ver[e].power += steps; } } } if(steps < 2) steps++; } if(!found) System.out.println(max); else System.out.println(max + 1); } else{ for(int i = 0; i<N; i++){ int count = 0; if(ver[i].power == max) count = 1; for(int e : ver[i].edges){ if(ver[e].power == max) count++; } if(count == max_times){ found = true; break; } } if(found) System.out.println(max + 1); else System.out.println(max + 2); } } } class Vertex{ ArrayList<Integer> edges; int power; boolean visited; Vertex(int p){ visited = false; power = p; edges = new ArrayList<>(); } } class FastScannerC{ private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastScannerC(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 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 String nextLine() { int c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isLineEndChar(c)); return res.toString(); } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isLineEndChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
6cd3bf1a8c1929122532dd42c4780b45
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import static java.lang.System.out; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; // There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. // All banks are initially online. Each bank i has initial strength ai. // Bank i and j are neighboring if and only if there exists a wire directly connecting them. // Bank i and j are semi-neighboring if and only if there exists an ONLINE bank k such that i and k are neighboring and k and j are neighboring. // When a bank is hacked, it becomes offline, and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1. // From above, we can conclude that each bank strength increase at most 2 // Pick a bank to start, then repeat, each must be neighboring to some offline bank and strength<=hacker // find the minimum strength of hacker's computer strength // IDEA: find m=max(bank 1 to n), answer can only be one of m, m+1, or m+2 // count # of banks with strength m, or m-1. other banks does impact answer // Iterate each bank, find its neighbours with strength m or m-1. find if there are other banks with strength m or m-1 (use simple math as total m or m-1 is known). // if other bank has m, then ans=m+2, else if other bank has m-1, then ans=m+1, else if neighbor has m, ans=m+1, else ans=m // final answer is min (ans from 1 to n) public class BankHacking796C { int strength[]; //- 10^9 ≤ ai ≤ 10^9, 1 ≤ n ≤ 3·10^5 List<List<Integer>> adj;//1 ≤ ui, vi ≤ n int MIN_VAL=-1000000000; // int mV=MIN_VAL; BankHacking796C() { strength = sc.ria(sc.ni()); adj = new ArrayList<>(strength.length+1); for (int i=0; i<strength.length; i++) adj.add(new ArrayList<>(10)); for (int i=0; i<strength.length-1; i++) { int u = sc.ni()-1; // index from 0 int v = sc.ni()-1; adj.get(u).add(v); adj.get(v).add(u); } //out.println(adj); solve(); } void solve() { for (int i=0; i<strength.length; i++) if (mV<strength[i]) mV=strength[i]; int answer=mV+2; // largest answer int cntMax=0; // count of max int cntMax_1=0; // count of max-1 for (int i=0; i<strength.length; i++) { if (mV==strength[i]) cntMax++; else if (mV-1==strength[i]) cntMax_1++; } //out.println("mV="+mV+" cntMax="+cntMax+" cntMax1="+cntMax_1); for (int i=0; i<strength.length; i++) { int maxNb=0; int maxNb1=0; List<Integer> neb = adj.get(i); for (int j=0; j<neb.size(); j++) { if (strength[neb.get(j)]==mV) maxNb++; else if (strength[neb.get(j)]==mV-1) maxNb1++; } int maxOther = cntMax-maxNb; int maxOther1 = cntMax_1-maxNb1; if (mV==strength[i]) maxOther--; else if (mV-1==strength[i]) maxOther1--; int ansMax=mV; if ( maxOther>0) ansMax += 2; else if ( maxOther1>0 || maxNb>0) ansMax++; if (ansMax < answer) answer = ansMax; // if (answer==mV) break; // find the minmal, no need to further } out.println(answer); } static MyScannerXX sc = new MyScannerXX(); public static void main(String[] args) { new BankHacking796C(); } } class MyScannerXX { BufferedReader br; StringTokenizer st; public MyScannerXX() { 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 int ni() { return nextInt(); } public long nl() { return nextLong(); } public int[] ria(int N) { // read int array int L[]=new int[N]; for (int i=0; i<N; i++) L[i]=nextInt(); return L; } public long[] rla(int N) { // read long array long L[]=new long[N]; for (int i=0; i<N; i++) L[i]=nextLong(); return L; } } /* failed test case 10 -1000000000 -1000000000 -1000000000 -1000000000 -1000000000 -1000000000 -1000000000 -1000000000 -1000000000 -1000000000 10 3 7 4 2 6 9 2 5 10 1 8 7 8 7 2 10 6 */
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
ba3c7b5122893f791d9243ee62c49892
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class BankHacking { public static FastScanner in = new FastScanner(System.in); public static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner(InputStream i) { reader = new BufferedReader(new InputStreamReader(i)); tokenizer = new StringTokenizer(""); } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) { try { int n = in.nextInt(); int[] banks = new int[n]; int[] nbLinksWithMax = new int[n]; int[] nbLinksWithMaxMinus1 = new int[n]; int vMax = Integer.MIN_VALUE; int firstIndexMax = 0; for (int i = 0; i < n; i++) { banks[i] = in.nextInt(); if (vMax < banks[i]) { firstIndexMax = i; vMax = banks[i]; } } int nbVmax = 0; int nbVmaxMinus1 = 0; for (int i = 0; i < n; i++) { if (banks[i] == vMax) { nbVmax++; nbLinksWithMax[i]++; } if (banks[i] == vMax - 1) { nbVmaxMinus1++; nbLinksWithMaxMinus1[i]++; } } for (int i = 0; i < n - 1; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; if (banks[u] == vMax) nbLinksWithMax[v]++; if (banks[v] == vMax) nbLinksWithMax[u]++; if (banks[u] == vMax - 1) nbLinksWithMaxMinus1[v]++; if (banks[v] == vMax - 1) nbLinksWithMaxMinus1[u]++; } int result; if (!hasNode(nbLinksWithMax, nbVmax)) result = vMax + 2; else if (nbVmax == 1 && isNode(nbLinksWithMaxMinus1[firstIndexMax], nbVmaxMinus1)) result = vMax; else result = vMax + 1; System.out.println(result); in.close(); } catch (Exception e) { e.printStackTrace(); } } private static boolean hasNode(int[] nbLinks, int sizeLink) { for (int nb : nbLinks) if (isNode(nb, sizeLink)) return true; return false; } private static boolean isNode(int nb, int sizeLink) { return nb == sizeLink; } }
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
013f261b355baa48c611bcbf58e2b852
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ConcurrentSkipListSet; public class Main { public static void main(String[] args) throws FileNotFoundException { ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out)); //String test = "C-large"; //ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\Competitions\\GCJ17\\quals\\" + test + ".in"), new PrintWriter(new File("D:\\Dropbox\\Competitions\\GCJ17\\quals\\" + test + "-out.txt"))); new Main(io).solve(); io.close(); } ConsoleIO io; Main(ConsoleIO io) { this.io = io; } long MOD = 1_000_000_007; List<List<Integer>> gr = new ArrayList<>(); int[] str; public void solve() { int n = io.ri(); str = new int[n]; int max = Integer.MIN_VALUE; for(int i=0;i<n;i++) { gr.add(new ArrayList<>()); int v = io.ri(); str[i] = v; max = Math.max(max, v); } for(int i = 1;i<n;i++) { int a = io.ri() - 1, b = io.ri() - 1; gr.get(a).add(b); gr.get(b).add(a); } int count = 0; int cc = 0; for(int i = 0;i<n;i++){ if(str[i]==max)count++; else if(str[i]==max-1)cc++; } int res = Integer.MAX_VALUE; for(int i = 0;i<n;i++) { int k = str[i]==max?1:0; int k2 = str[i]==max-1?1:0; int cur = max; List<Integer> ch = gr.get(i); for (int j = 0; j < ch.size(); j++) { int v = ch.get(j); int x = str[v]; if (x == max) { k++; cur = max + 1; }else if(x==max-1){ k2++; } } if (k < count) cur = max + 2; if(k2<cc)cur = Math.max(cur,max+1); res = Math.min(cur, res); } io.writeLine(res+""); } } 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; }} }
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
cb4dde04ec35a0daf769ff891e82b34f
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { List<Integer>[] graph; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); graph = new List[n + 1]; int arr[] = new int[n + 1]; for (int i = 0; i < n + 1; i++) { graph[i] = new ArrayList<>(); } for (int i = 1; i <= n; i++) { arr[i] = in.nextInt(); } int ans = arr[1]; for (int i = 1; i <= n; i++) { ans = Math.max(ans, arr[i]); } for (int i = 1; i < n; i++) { int a = in.nextInt(); int b = in.nextInt(); graph[a].add(b); graph[b].add(a); } int temp = -1, cnt = 0, cur = 0; int nn[] = new int[n + 1]; int mm[] = new int[n + 1]; for (int i = 1; i <= n; i++) { if (ans == arr[i]) { nn[i]++; for (int x : graph[i]) { nn[x]++; } cur++; temp = i; } if (ans == arr[i] + 1) { mm[i]++; for (int x : graph[i]) { mm[x]++; } cnt++; } } int zz = 0, cc = 0; for (int i = 1; i <= n; i++) { zz = Math.max(zz, nn[i]); cc = Math.max(cc, mm[i]); } if (cur == 1 && mm[temp] == cnt) { out.println(ans); } else if (zz == cur) { out.println(ans + 1); } else { out.println(ans + 2); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
290f7cebb977123d0e853141c09c79be
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import java.util.*; import java.math.*; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); ArrayList[] arr = new ArrayList[n+1]; int []a = new int[n]; int ma = 0; int max_pos = 0; int mb = 0; int max = sc.nextInt(); int maxs =0; a[0] = max ; for(int i=1;i<n;i++) { a[i] = sc.nextInt(); max = Math.max(max,a[i]); } maxs = max - 1; for(int i=0;i<n;i++) { arr[i+1] = new ArrayList(); if(a[i] == max) { ma++; max_pos = i; } if(a[i] == maxs) mb++; } for(int i=1;i<n;i++) { int x,y; x = sc.nextInt(); y = sc.nextInt(); arr[x].add(y); arr[y].add(x); } if(ma == 1) { int c = 0; for(int i=0;i<arr[max_pos+1].size();i++) { if(a[(int)arr[max_pos+1].get(i)-1] == maxs) { c++; } } if(c == mb) System.out.println(max); else System.out.println(max+1); } else{ int c = 0; int flag = 0; for(int i=0;i<n;i++) { c = 0; if(a[i] == max) c++; for(int j=0;j<arr[i+1].size();j++) { int id = (int)arr[i+1].get(j)-1; if(a[id] == max) { c++; } } if(c == (ma)) { flag = 1; break; } } if(flag == 1) System.out.println(max+1); else System.out.println(max+2); } } }
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
cbe2cd1b99669afdb83459eb1c14097f
train_003.jsonl
1491842100
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class C_Round_408_Div2 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int[] data = new int[n]; ArrayList<Integer>[] map = new ArrayList[n]; for (int i = 0; i < n; i++) { data[i] = in.nextInt(); map[i] = new ArrayList(); } for (int i = 0; i < n - 1; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; map[u].add(v); map[v].add(u); } // boolean[] visit = new boolean[n]; // int com = 0; // for (int i = 0; i < n; i++) { // if (!visit[i]) { // com++; // LinkedList<Integer> q = new LinkedList(); // q.add(i); // visit[i] = true; // while (!q.isEmpty()) { // int node = q.poll(); // for (int j : map[node]) { // if (!visit[j]) { // q.add(j); // visit[j] = true; // } // } // } // } // } // if (com > 1) { // System.out.println("VCL"); // } TreeMap<Integer, Integer> set = new TreeMap(); for (int i = 0; i < n; i++) { set.put(data[i] + 2, set.getOrDefault(data[i] + 2, 0) + 1); } int result = set.lastKey(); for (int i = 0; i < n; i++) { HashMap<Integer, Integer> cur = new HashMap(); cur.put(data[i] + 2, 1); int tmp = data[i]; for (int j : map[i]) { cur.put(data[j] + 2, cur.getOrDefault(data[j] + 2, 0) + 1); tmp = Integer.max(tmp, data[j] + 1); } Integer v = set.lastKey(); while (v != null) { if (!cur.containsKey(v) || set.get(v).compareTo(cur.get(v)) != 0) { tmp = Integer.max(tmp, v); break; } else { v = set.lowerKey(v); } } result = Integer.min(result, tmp); } out.println(result); out.close(); } static class Node implements Comparable<Node> { int index; int val; public Node(int index, int val) { super(); this.index = index; this.val = val; } @Override public int compareTo(Node o) { if (val != o.val) { return Integer.compare(val, o.val); } return Integer.compare(index, o.index); } } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new // BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new // FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4"]
2 seconds
["5", "93", "8"]
NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Java 8
standard input
[ "dp", "constructive algorithms", "trees", "data structures" ]
9d3ab9c33b69c4f8e60454d369704b30
The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
1,900
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
standard output
PASSED
b89e87339c5d7d117137870d6e810983
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { private static Set<Integer> visited = new HashSet<>(); private static ArrayList<Integer>[] graph; private static boolean fail = false; private static Set<List<Integer>> oneList = new LinkedHashSet<>(); private static Set<List<Integer>> twoList = new LinkedHashSet<>(); private static Set<List<Integer>> threeList = new LinkedHashSet<>(); private static void dfs(int index, List<Integer> team){ if(fail){ return; } if(visited.contains(index)){ return; } visited.add(index); if(team.size() > 3){ fail = true; return; } for(int node : graph[index]){ if(!visited.contains(node)){ team.add(node); dfs(node, team); } } if(team.size() > 3){ fail = true; return; } //store team if(team.size() == 1){ oneList.add(new ArrayList<>(team)); } else if(team.size() == 2){ twoList.add(new ArrayList<>(team)); } else { threeList.add(new ArrayList<>(team)); } } public static void main(String[] args) throws IOException { //Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer line1 = new StringTokenizer(br.readLine().trim()); int n = Integer.parseInt(line1.nextToken().trim()); int m = Integer.parseInt(line1.nextToken().trim()); if(m == 0){ for(int i = 1; i <= n; i++){ System.out.print(i + " "); if(i % 3 == 0){ System.out.println(); } } return; } graph = new ArrayList[n + 1]; for(int i = 0; i < graph.length; i++){ graph[i] = new ArrayList<>(); } for(int i = 0; i < m; i++){ StringTokenizer row = new StringTokenizer(br.readLine().trim()); int first = Integer.parseInt(row.nextToken().trim()); int second = Integer.parseInt(row.nextToken().trim()); graph[first].add(second); graph[second].add(first); } for(int i = 1; i < graph.length; i++){ if(!visited.contains(i)){ ArrayList<Integer> list = new ArrayList<>(); list.add(i); dfs(i, list); } if(fail){ break; } } if(fail){ System.out.println("-1"); return; } if(twoList.size() > oneList.size()){ System.out.println("-1"); return; } // display three lists for(List<Integer> threeSet : threeList){ System.out.println(threeSet.get(0) + " " + threeSet.get(1) + " " + threeSet.get(2)); } // combine two and one int count = 0; List<List<Integer>> oneRevList = new ArrayList<>(); oneRevList.addAll(oneList); for(List<Integer> twoSet : twoList){ System.out.println(twoSet.get(0) + " " + twoSet.get(1) + " " + oneRevList.get(count).get(0)); count++; } List<Integer> combinedOne = new ArrayList<>(); for(int i = count; i < oneRevList.size(); i++){ combinedOne.add(oneRevList.get(i).get(0)); } // for(int num : combinedOne){ System.out.print(num + " "); } } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
7c0d378f58d5df016037f29846b6ef5a
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class Coach { private static HashMap<Integer, Set<Integer>> groups; private static Deque<Integer> withoutGroup; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] nm = br.readLine().split(" "); int n = Integer.parseInt(nm[0]); initHashGroups(n/3); int m = Integer.parseInt(nm[1]); int[][] graph = new int[n][n]; for(int u = 0; u < m; u++){ String[] ij = br.readLine().split(" "); int i = Integer.parseInt(ij[0]) - 1; int j = Integer.parseInt(ij[1]) - 1; graph[i][j] = 1; graph[j][i] = 1; } int numberGroup = 2; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(graph[i][j] != 1) continue; //visited if(numberGroup - 1 > n/3) { System.out.println("-1"); return; } if(makeGroup(graph, i, j, numberGroup) > 3){ System.out.println("-1"); return; } numberGroup++; } } withoutGroup = new ArrayDeque<Integer>(); boolean hasPreference = false; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++) if(graph[i][j] != 0) hasPreference = true; if(!hasPreference) withoutGroup.add(i); hasPreference = false; } StringBuilder sb = new StringBuilder(); for(Set<Integer> group: groups.values()){ while(group.size() < 3) group.add(withoutGroup.removeFirst()+1); for(int member: group) sb.append(member).append(" "); sb.append('\n'); } System.out.println(sb.toString()); } private static int makeGroup(int[][] graph, int i, int j, int numberGroup) { graph[i][j] = numberGroup; graph[j][i] = numberGroup; addGroup(i, j, numberGroup); for(int u = 0; u < graph.length; u++){ if(graph[i][u] != 0 && graph[i][u] != numberGroup) makeGroup(graph, i, u, numberGroup); if(graph[j][u] != 0 && graph[j][u] != numberGroup) makeGroup(graph, u, j, numberGroup); } return groups.get(numberGroup).size(); } private static void addGroup(int i, int j, int numberGroup) { Set<Integer> group = groups.get(numberGroup); group.add(i+1); group.add(j+1); } private static void initHashGroups(int i) { groups = new HashMap<Integer, Set<Integer>>(); for(int u = 0; u < i; u++){ Set<Integer> group = new HashSet<Integer>(3); groups.put(u+2, group); } } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
6e20a6c10eed9e94349d542cbddf2d9d
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Main { private static StreamTokenizer inputReader = new StreamTokenizer( new BufferedReader(new InputStreamReader(System.in))); public static void main(String[] args) { int studetNumber = nextInt(); int requestNumber = nextInt(); List<Set<Integer>> teams = new ArrayList<>(); boolean[] seen = new boolean[studetNumber]; for (int i = 0; i < requestNumber; i++) { int x = nextInt(); int y = nextInt(); if (!seen[x - 1] && !seen[y - 1]) { Set<Integer> team = new HashSet<>(); team.add(x); team.add(y); teams.add(team); } else { for (int j = 0; j < teams.size(); j++) { Set<Integer> team = teams.get(j); if (team.contains(x)) { team.add(y); } if (team.contains(y)) { team.add(x); } } } seen[x - 1] = true; seen[y - 1] = true; } while (teams.size() < studetNumber / 3) { Set<Integer> team = new HashSet<>(); teams.add(team); } int currentIndex = 0; for (Set<Integer> team : teams) { while (team.size() < 3 && currentIndex != -1) { currentIndex = getNextStudent(seen, currentIndex); team.add(currentIndex + 1); } } StringBuilder builder = new StringBuilder(); for (Set<Integer> team : teams) { if (team.size() != 3 || team.contains(-1)) { System.out.println(-1); return; } else { for (Integer student : team) { builder.append(student); builder.append(" "); } builder.append("\n"); } } System.out.println(builder); } private static int getNextStudent(boolean[] students, int currentStrudent) { for (int i = currentStrudent; i < students.length; i++) { if (!students[i]) { students[i] = true; return i; } } return -1; } public static int nextInt() { int a = -1; try { inputReader.nextToken(); a = (int) inputReader.nval; } catch (Exception e) { } return a; } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
7ace671462941cc96974f88c89d97fc3
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
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.List; import java.util.stream.Stream; /** * @author madi.sagimbekov */ public class C300B { private static BufferedReader in; private static BufferedWriter out; private static List<Integer>[] list; private static int[] arr; private static int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; private static boolean[] used; private static List<Integer>[] teams; private static List<Integer> currTeam; public static void main(String[] args) throws IOException { open(); arr = readInts(); int n = arr[0]; int m = arr[1]; list = buildAdjacencyList(n, m); teams = new ArrayList[4]; for (int i = 1; i < 4; i++) { teams[i] = new ArrayList<>(); } used = new boolean[n + 1]; for (int i = 1; i <= n; i++) { if (!used[i]) { currTeam = new ArrayList<>(); dfs(i); if (currTeam.size() > 3) { out.write("-1\n"); close(); return; } else { for (int item : currTeam) { teams[currTeam.size()].add(item); } } } } List<Integer> team3 = teams[3]; List<Integer> team2 = teams[2]; List<Integer> team1 = teams[1]; int team2Size = team2.size(); int team1Size = team1.size(); if (team2Size / 2 > team1Size || (team1Size - team2Size / 2) % 3 != 0) { out.write("-1\n"); close(); return; } for (int i = 0; i < team3.size(); i += 3) { out.write(team3.get(i) + " " + team3.get(i + 1) + " " + team3.get(i + 2) + "\n"); } int idx = 0; for (int i = 0; i < team2.size(); i += 2) { out.write(team2.get(i) + " " + team2.get(i + 1) + " " + team1.get(idx++) + "\n"); } for (; idx < team1.size(); idx += 3) { out.write(team1.get(idx) + " " + team1.get(idx + 1) + " " + team1.get(idx + 2) + "\n"); } close(); } private static void dfs(int x) { used[x] = true; currTeam.add(x); for (int next : list[x]) { if (!used[next]) { dfs(next); } } } private static int[] readInts() throws IOException { return Stream.of(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } private static int readInt() throws IOException { return Integer.parseInt(in.readLine()); } private static long[] readLongs() throws IOException { return Stream.of(in.readLine().split(" ")).mapToLong(Long::parseLong).toArray(); } private static long readLong() throws IOException { return Long.parseLong(in.readLine()); } private static double[] readDoubles() throws IOException { return Stream.of(in.readLine().split(" ")).mapToDouble(Double::parseDouble).toArray(); } private static double readDouble() throws IOException { return Double.parseDouble(in.readLine()); } private static String readString() throws IOException { return in.readLine(); } private static List<Integer>[] buildAdjacencyList(int n, int m) throws IOException { List<Integer>[] list = new ArrayList[n + 1]; for (int i = 0; i <= n; i++) { list[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int[] e = readInts(); list[e[0]].add(e[1]); list[e[1]].add(e[0]); } return list; } private static void open() { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter((System.out))); } private static void close() throws IOException { out.flush(); out.close(); in.close(); } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
698e7ecc35f3e5775228856ca9ba648a
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.util.Scanner; import java.util.HashSet; import java.util.ArrayList; public class Main { static boolean[][] adj = new boolean[50][50]; // describes what is connected (u, v) static boolean[] vis = new boolean[50]; // visited - tracks past locations static HashSet<Integer> free = new HashSet<>(); // duplicates not allowed; only contains elements static ArrayList<ArrayList<Integer> > teams = new ArrayList<>(); static int N; public static void dfs (int u, ArrayList<Integer> result) { vis[u] = true; result.add(u); // result is ArrayList for (int v = 1; v <= N; ++v) { // vertex v if (adj[u][v] && !vis[v]) // if (u, v) connected and v has not already been visited dfs(v, result); // run through v } } public static void main (String[] args) { Scanner scan = new Scanner(System.in); N = scan.nextInt(); int m = scan.nextInt(); boolean canDo = true; for (int i = 1; i <= N; ++i) free.add(i); // free is set containing all n number of students for (int i = 0; i < m; ++i) { int u, v; u = scan.nextInt(); v = scan.nextInt(); if (free.contains(u)) free.remove(u); if (free.contains(v)) free.remove(v); adj[u][v] = true; adj[v][u] = true; } for (int u = 1; u <= N; ++u) { if (vis[u] || free.contains(u)) continue; ArrayList<Integer> result = new ArrayList<>(); dfs(u, result); if (result.size() < 3 && free.size() > 0) { ArrayList<Integer> fromFree = new ArrayList<>(); for (int v: free) { fromFree.add(v); if (result.size()+fromFree.size() == 3) break; } for (int v: fromFree) { result.add(v); vis[v] = true; free.remove(v); } } if (result.size() != 3) canDo = false; /*System.out.println(result);*/ teams.add(result); } if (free.size() > 0) { if (free.size() % 3 == 0) { ArrayList<Integer> freeList = new ArrayList<>(free); for (int i = 2; i < freeList.size(); i += 3) { ArrayList<Integer> tmp = new ArrayList<>(); tmp.add(freeList.get(i)); tmp.add(freeList.get(i-1)); tmp.add(freeList.get(i-2)); teams.add(tmp); } } else canDo = false; } if (canDo) { for (ArrayList<Integer> team: teams) { System.out.println(team.get(0) + " " + team.get(1) + " " + team.get(2)); } } else { System.out.println(-1); } } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
61b9a7325824012ed7b82fff8ffb9d6b
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class Coach { static ArrayList<Integer> adjList[]; static int N; static boolean visited[]; static ArrayList<Integer> team; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); N = sc.nextInt(); int m = sc.nextInt(); adjList = new ArrayList[N]; visited = new boolean[N]; team = new ArrayList<>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < N; i++) adjList[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; adjList[a].add(b); adjList[b].add(a); } boolean flag = true; ArrayList<Integer> twos = new ArrayList<>(); ArrayList<Integer> ones = new ArrayList<>(); for (int i = 0; i < N; i++) { team = new ArrayList<>(); if (!visited[i]) { dfs(i); if (team.size() > 3) { flag = false; break; } else if (team.size() == 3) sb.append(team.get(0) + " " + team.get(1) + " " + team.get(2) + "\n"); else if (team.size() == 2) { twos.add(team.get(0)); twos.add(team.get(1)); } else ones.add(team.get(0)); } } if(ones.size() < twos.size() /2) flag = false; if (flag) { for (int i = 0; i < twos.size() - 1; i++) { int x = ones.remove(0); sb.append(twos.get(i) + " " + twos.get(i + 1) + " " + x + "\n"); i++; } while (!ones.isEmpty()) { sb.append(ones.remove(0) + " " + ones.remove(0) + " " + ones.remove(0)+"\n"); } System.out.print(sb.toString()); } else System.out.println(-1); } static void dfs(int u) // O(V + E) adjList, O(V^2) adjMat { visited[u] = true; team.add(u + 1); for (int v : adjList[u]) if (!visited[v]) dfs(v); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream System) { br = new BufferedReader(new InputStreamReader(System)); } 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() { for (long i = 0; i < 3e9; i++) ; } } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
88bbb6d451fc38ce17fb4ab59a9da2b4
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class Coach { static List<List<Integer>> graph = new ArrayList<>(); static boolean[] visited; static List<List<Integer>> twos = new ArrayList<>(); static List<Integer> ones = new ArrayList<>(); static List<Integer> curRes = new ArrayList<>(); static void dfs(int cur) { if (visited[cur]) return; visited[cur] = true; curRes.add(cur); for (int neigh : graph.get(cur)) { if (visited[neigh]) continue; dfs(neigh); } } public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int n = Integer.parseInt(tokenizer.nextToken()); int m = Integer.parseInt(tokenizer.nextToken()); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } for (int i = 0; i < m; i++) { tokenizer = new StringTokenizer(reader.readLine()); int from = Integer.parseInt(tokenizer.nextToken()) - 1; int to = Integer.parseInt(tokenizer.nextToken()) - 1; graph.get(from).add(to); graph.get(to).add(from); } List<List<Integer>> res3 = new ArrayList<>(); visited = new boolean[n]; for (int i = 0; i < n; i++) { if (visited[i]) continue; curRes.clear(); dfs(i); if (curRes.size() > 3) { System.out.println(-1); return; } if (curRes.size() == 3) { res3.add(new ArrayList<>(curRes)); } if (curRes.size() == 1) { ones.add(curRes.get(0)); } if (curRes.size() == 2) { twos.add(new ArrayList<>(curRes)); } } if ((ones.size() - twos.size()) % 3 != 0 || twos.size() > ones.size()) { System.out.println(-1); return; } for (int i = 0; i < res3.size(); i++) { for (int j = 0; j < res3.get(i).size(); j++) { System.out.print((res3.get(i).get(j)+1) + " "); } System.out.println(); } while (!ones.isEmpty() || !twos.isEmpty()) { if (!twos.isEmpty()) { System.out.print((1+ones.get(ones.size() - 1)) + " "); System.out.println((twos.get(twos.size() - 1).get(0)+1) + " "); System.out.println((twos.get(twos.size() - 1).get(1)+1) + " "); ones.remove(ones.size() - 1); twos.remove(twos.size() - 1); } else { for (int i = 0; i < 3; i++) { System.out.print(ones.get(ones.size() - 1)+1+" "); ones.remove(ones.size() - 1); } } } } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
6f84f129e7c6e19596317737a6e62fda
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.SSLContext; public class Main { static long mod=(long)(1e+9) + 7; static int[] sieve;static int ans=0; static ArrayList<Integer> primes; static int visited[]; static ArrayList<Integer> cur; public static void dfs(int start,ArrayList<Integer>[] graph) { if(visited[start]==1) return ; visited[start]=1; cur.add(start); for(int i=0;i<graph[start].size();i++) dfs(graph[start].get(i),graph); } public static void main(String[] args) throws java.lang.Exception { fast s = new fast(); PrintWriter out=new PrintWriter(System.out); Scanner sc=new Scanner(System.in); StringBuilder fans = new StringBuilder(); int n=s.nextInt(); int m=s.nextInt(); ArrayList<Integer>[] graph=new ArrayList[n+1]; ArrayList<ArrayList<Integer>>[] size=new ArrayList[n+1]; cur=new ArrayList<Integer>(); for(int i=0;i<=n;i++) graph[i]=new ArrayList<Integer>(); for(int i=0;i<=n;i++) size[i]=new ArrayList<ArrayList<Integer>>(); for(int i=0;i<m;i++) { int x=s.nextInt(); int y=s.nextInt(); graph[x].add(y);graph[y].add(x); } visited=new int[n+1]; for(int i=1;i<=n;i++) { if(visited[i]==0) { dfs(i,graph); size[cur.size()].add(cur); cur=new ArrayList<Integer>(); } } for(int i=4;i<=n;i++) if(size[i].size()>0) {System.out.println("-1"); return;} if(size[2].size()>size[1].size()) {System.out.println("-1"); return;} for(int i=0;i<size[3].size();i++) { ArrayList<Integer> a=size[3].get(i); fans.append(a.get(0)+" "+a.get(1)+" "+a.get(2)); fans.append("\n"); } if(size[2].size()==size[1].size()) { for(int i=0;i<size[2].size();i++) { ArrayList<Integer> a=size[2].get(i); ArrayList<Integer> b=size[1].get(i); fans.append((a.get(0)+" "+a.get(1)+" "+b.get(0))); fans.append("\n"); } } else { int diff=size[2].size()-size[1].size(); if(diff%3!=0) {System.out.println("-1"); return;} int ind=-1; for(int i=0;i<size[2].size();i++) { ArrayList<Integer> a=size[2].get(i); ArrayList<Integer> b=size[1].get(i); fans.append((a.get(0)+" "+a.get(1)+" "+b.get(0))); fans.append("\n"); ind=i; } for(int i=ind+1;i<=size[1].size()-3;i+=3) { fans.append((size[1].get(i).get(0)+" "+size[1].get(i+1).get(0)+" "+size[1].get(i+2).get(0))); fans.append("\n"); } } fans.deleteCharAt(fans.length()-1); System.out.println(fans); } static class fast { private InputStream i; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public static boolean next_permutation(int a[]) { int i=0,j=0;int index=-1; int n=a.length; for(i=0;i<n-1;i++) if(a[i]<a[i+1]) index=i; if(index==-1) return false; i=index; for(j=i+1;j<n && a[i]<a[j];j++); int temp=a[i]; a[i]=a[j-1]; a[j-1]=temp; for(int p=i+1,q=n-1;p<q;p++,q--) { temp=a[p]; a[p]=a[q]; a[q]=temp; } return true; } public static void division(char ch[],int divisor) { int div=Character.getNumericValue(ch[0]); int mul=10;int remainder=0; StringBuilder quotient=new StringBuilder(""); for(int i=1;i<ch.length;i++) { div=div*mul+Character.getNumericValue(ch[i]); if(div<divisor) {quotient.append("0");continue;} quotient.append(div/divisor); div=div%divisor;mul=10; } remainder=div; while(quotient.charAt(0)=='0')quotient.deleteCharAt(0); System.out.println(quotient+" "+remainder); } public static void sieve(int size) { sieve=new int[size+1]; primes=new ArrayList<Integer>(); sieve[1]=1; for(int i=2;i<=Math.sqrt(size);i++) { if(sieve[i]==0) { for(int j=i*i;j<size;j+=i) sieve[j]=1; } } for(int i=2;i<=size;i++) { if(sieve[i]==0) primes.add(i); } } public static long pow(long n, long b, long MOD) { long x=1;long y=n; while(b > 0) { if(b%2 == 1) { x=x*y; if(x>MOD) x=x%(MOD); } y = y*y; if(y>MOD) y=y%(MOD); b >>= 1; } return x; } public static int lower(Integer[] a,int start,int end,int key) { int mid=(start+end)>>1; if(start==end && a[mid]<key) {return -1;} if(start>end) return -1; if(a[mid]>=key && (((mid-1)>=0 && a[mid-1]<key) || (mid-1)==0)) return mid; else if(a[mid]== key && (mid-1)>=0 && a[mid-1]==key) return lower(a,start,mid-1,key); else if(key>a[mid]) return lower(a,mid+1,end,key); else return lower(a,start,mid-1,key); } public static int upper(Integer a[],int start,int end,int key) { int mid=(start+end)>>1; if(start==end && a[mid]>key) {return -1;} if(start>end) return -1; if(a[mid]<=key && (((mid+1)<a.length && a[mid+1]>key) || (mid+1)==a.length)) return mid; else if(a[mid]== key && (mid+1)<a.length && a[mid+1]==key) return upper(a,mid+1,end,key); else if(key>=a[mid]) return upper(a,mid+1,end,key); else return upper(a,start,mid-1,key); } public int gcd(int a,int b) { if(a==0) return b; return gcd(b%a,a); } public fast() { this(System.in); } public fast(InputStream is) { i = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = i.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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; } } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
c0db9b351b6a0a033a0aed235dea1d2e
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.util.*; import java.io.*; public class Main { static int N, M; static int[] g = new int[50]; static int[] one = new int[50]; static int[] two = new int[50]; static int[] cnt = new int[50]; public static void main(String[] args) { FastScanner in = new FastScanner(System.in); N = in.nextInt(); M = in.nextInt(); for (int i = 1; i <= N; i++) g[i] = i; for (int i = 1; i <= M; i++) g[f(in.nextInt())]=f(in.nextInt()); for (int i = 1; i <= N; i++) cnt[f(i)]++; for (int i = 1; i <= N; i++) { if (cnt[i]==1) one[++one[0]]=i; if (cnt[i]==2) two[++two[0]]=i; if (cnt[i]>=4) { System.out.println(-1); return;} } if (one[0] < two[0]) { System.out.println(-1); return;} for (int i = 1; i <= two[0]; i++) g[one[i]] = f(two[i]); for (int i = two[0]+1; i <= one[0]; i+=3) g[one[i]]=g[one[i+1]]=g[one[i+2]]; for (int i = 1; i <= N; i++) if (i == f(i)) { System.out.print(i); for (int j = 1; j <= N; j++) if (j != i && f(j) == i) System.out.print(" " + j); System.out.println(); } } static int f(int x) { if (g[x] != x) g[x] = f(g[x]); return g[x]; } } class FastScanner { BufferedReader reader; StringTokenizer tokenizer; FastScanner (InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } String nextToken() { while (tokenizer == null || ! tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e){} } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
1c8274a518b782cae5f24893aee81a29
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; /** * Created by Egor on 06/10/14. */ public class Task300B { BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws IOException { new Task300B().run(); } public ArrayList<Integer>[] graph; public ArrayList<Integer> currentAnswer = new ArrayList<Integer>(); public boolean[] visited; public void solve() throws IOException { int n = nextInt(); int m = nextInt(); graph = new ArrayList[n]; for (int i = 0; i < n; i++) { graph[i] = new ArrayList<Integer>(); } for (int i = 0; i < m; i++) { int from = nextInt() - 1; int to = nextInt() - 1; graph[from].add(to); graph[to].add(from); } visited = new boolean[n]; ArrayList<ArrayList<Integer>> t1 = new ArrayList<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> t2 = new ArrayList<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> t3 = new ArrayList<ArrayList<Integer>>(); for (int i = 0; i < n; i++) { if (!visited[i]) { currentAnswer = new ArrayList<Integer>(); dfs(i); switch (currentAnswer.size()) { case 2: t2.add((ArrayList<Integer>) currentAnswer.clone()); break; case 1: t1.add((ArrayList<Integer>) currentAnswer.clone()); break; case 3: t3.add((ArrayList<Integer>) currentAnswer.clone()); break; default: writer.println(-1); return; } // if (teams.get(teams.size() - 1).size() == 1) { // if (lastIndex2 != -1) { // teams.get(lastIndex2).add(teams.get(teams.size() - 1).get(0)); // teams.remove(teams.size() - 1); // lastIndex2 = -1; // } else { // lastIndex1 = teams.size() - 1; // } // } else if (teams.get(teams.size() - 1).size() == 2) { // if (lastIndex1 != -1) { // teams.get(lastIndex1).add(teams.get(teams.size() - 1).get(0)); // teams.get(lastIndex1).add(teams.get(teams.size() - 1).get(1)); // teams.remove(teams.size() - 1); // lastIndex1 = -1; // } else { // lastIndex2 = teams.size() - 1; // } // } } } if (t2.size() > t1.size() || (t2.size() - t1.size()) % 3 != 0) { writer.println(-1); return; } StringBuilder builder = new StringBuilder(); for (ArrayList<Integer> team : t3) { for (int item : team) { builder.append(item + 1).append(" "); } builder.append("\n"); } int i = 0; for (i = 0; i < t2.size(); i++) { builder.append(t2.get(i).get(0) + 1).append(" "); builder.append(t2.get(i).get(1) + 1).append(" "); builder.append(t1.get(i).get(0) + 1).append(" "); builder.append("\n"); } for (int j = i; j < t1.size(); j += 3) { builder.append(t1.get(j).get(0) + 1).append(" "); builder.append(t1.get(j + 1).get(0) + 1).append(" "); builder.append(t1.get(j + 2).get(0) + 1).append(" "); builder.append("\n"); } writer.println(builder.toString()); } public void dfs(int start) { currentAnswer.add(start); visited[start] = true; for (int i = 0; i < graph[start].size(); i++) { if (!visited[graph[start].get(i)]) { dfs(graph[start].get(i)); } } } public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); solve(); writer.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
8aa52237f1300dee92f6a9b0b7c2eba7
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Scanner; public class Coach { private static ArrayList<Integer> dfs(int[][] graph, int n, int sv, ArrayList<Integer> list,boolean visited[]) { list.add(sv); visited[sv]=true; for(int i=0;i<n;i++){ if(i==sv) continue; if(!visited[i] && graph[sv][i]==1) dfs(graph, n, i, list, visited); } return list; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int graph[][]=new int[n][n]; for(int i=0;i<m;i++){ int f=sc.nextInt()-1; int s=sc.nextInt()-1; graph[f][s]=1; } boolean visited[]=new boolean[n]; ArrayList<ArrayList<Integer>> components=new ArrayList<>(); for(int i=0;i<n;i++){ if(!visited[i]){ ArrayList<Integer> list=new ArrayList<>(); list= dfs(graph,n,i,list,visited); components.add(list); } } /* for(int i=0;i<components.size();i++){ for(int j=0;j<components.get(i).size();j++){ System.out.print((components.get(i).get(j)+1)+" "); } System.out.println(); }*/ int i=0; int countOne=0,countTwo=0; for(i=0;i<components.size();i++){ if(components.get(i).size()==1 || components.get(i).size()==2 || components.get(i).size()==3){ if(components.get(i).size()==1) countOne++; else if(components.get(i).size()==2) countTwo++; }else { System.out.println("-1"); break; } } boolean check[]=new boolean[components.size()]; if(i==components.size()){ if( countOne>=countTwo && (countOne-countTwo)%3==0){ for(int j=0;j<components.size();j++){ if(components.get(j).size()==3){ for(int k=0;k<components.get(j).size();k++){ System.out.print(components.get(j).get(k)+1+" "); } System.out.println(); } if(components.get(j).size()==2){ int z=0; for(z=0;z<components.size();z++){ if(components.get(z).size()==1 && !check[z]){ check[z]=true; break; } } System.out.print(components.get(j).get(0)+1+" "); System.out.print(components.get(j).get(1)+1+" "); System.out.print(components.get(z).get(0)+1); System.out.println(); } } int counter=0; for(int a=0;a<components.size();a++){ if(components.get(a).size()==1 && !check[a]){ if(counter==3){ System.out.println(); counter=0; } System.out.print(components.get(a).get(0)+1+" "); counter++; } } } else System.out.println("-1"); } } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
11820be720b19864d7c9000f4ea43538
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.stream.Stream; import java.util.Vector; import static java.lang.Math.*; public class icpc { static ArrayList<Long> A = new ArrayList<>(); public static void main(String[] args)throws IOException { Reader in = new Reader(); int n = in.nextInt(); int m = in.nextInt(); ArrayList<Integer>[] adj = (ArrayList<Integer>[])new ArrayList[n]; for(int i=0;i<n;i++) adj[i] = new ArrayList<>(); for(int i=0;i<m;i++) { int a = in.nextInt(); int b = in.nextInt(); adj[a-1].add(b-1); adj[b-1].add(a-1); } ArrayList<Integer> ones = new ArrayList<>(); boolean[] visited1 = new boolean[n]; for(int i=0;i<n;i++) { if(!visited1[i]) { ArrayList<Integer> nodes = new ArrayList<>(); int count = explore(adj,i,visited1,nodes); if(count == 1) { ones.add(i); } } } boolean[] visited = new boolean[n]; boolean flag = true; StringBuilder stringBuilder = new StringBuilder(); for(int i=0;i<n;i++) { if(!visited[i]) { ArrayList<Integer> nodes = new ArrayList<>(); int count = explore(adj,i,visited,nodes); if(count > 3) { flag = false; break; } else if(count > 1) { for(int j=0;j<nodes.size();j++) stringBuilder.append(nodes.get(j)+1).append(" "); for(int j=0;j<(3- count);j++) { if(ones.size() == 0) { flag = false; break; } stringBuilder.append(ones.get(0)+1).append(" "); ones.remove(0); } stringBuilder.append("\n"); } } } int x = ones.size(); for(int i=0;i<x/3;i++) { stringBuilder.append(ones.get(0)+1).append(" "); ones.remove(0); stringBuilder.append(ones.get(0)+1).append(" "); ones.remove(0); stringBuilder.append(ones.get(0)+1).append(" "); ones.remove(0); stringBuilder.append("\n"); } if(flag) System.out.println(stringBuilder); else System.out.println("-1"); } public static int explore(ArrayList<Integer>[] adj,int v,boolean[] visited,ArrayList<Integer> nodes) { visited[v] = true; nodes.add(v); int count = 0; for(int i=0;i<adj[v].size();i++) { if(!visited[adj[v].get(i)]) count += explore(adj,adj[v].get(i),visited,nodes); } return (count + 1); } } class Solver { public String solve(int[] A) { int n = A.length; Point[] arr = new Point[n-1]; for(int i=0;i<n-1;i++) { arr[i] = new Point(A[i],A[i+1]); } for(int i=0;i<arr.length;i++) { for(int j=0;j<arr.length;j++) { if(i!=j) { if(checkCrossIntersection(Math.min(arr[i].x,arr[i].y) ,Math.max(arr[i].y,arr[i].x),Math.min(arr[j].x,arr[j].y) ,Math.max(arr[j].y,arr[j].x))) return "yes"; else continue; } } } return "no"; } public boolean checkCrossIntersection(int x1,int x2,int x3,int x4) { if((x1 < x3 && x3 < x2 && x2 < x4) || (x3 < x1 && x1 < x4 && x4 < x2)) return true; return false; } } class Point implements Comparable<Point> { int x; int y; Point(int a ,int b) { this.x = a; this.y = b; } public int compareTo(Point ob) { if(ob.x < this.x) return 1; else if(ob.x > this.x) return -1; else return 0; } } class MergeSort { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int [n1]; int R[] = new int [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class Node { int x; Node(int a) { this.x = a; } @Override public boolean equals(Object ob) { if(ob == null) return false; if(!(ob instanceof Node)) return false; if(ob == this) return true; Node obj = (Node)ob; if(obj.x == this.x) return true; return false; } @Override public int hashCode() { return (int)this.x; } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
455185406feee2468fe40f209d245579
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.util.*; public class Codeforces_round_181_div_2_Coach { public static void main(String args[]) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int m = input.nextInt(); int positions[] = new int[n + 1]; ArrayList<ArrayList<Integer>> teamList = new ArrayList<>(); boolean validTeam = true; for(int i = 1; i < n + 1; i++) positions[i] = -1; for(int i = 0; i < m && validTeam; i++) { int x = input.nextInt(); int y = input.nextInt(); if (positions[x] == -1 && positions[y] == -1) { if (teamList.size() < n / 3) { teamList.add(new ArrayList<Integer>()); int l = teamList.size() - 1; teamList.get(l).add(x); teamList.get(l).add(y); positions[x] = l; positions[y] = l; } else validTeam = false; } else { if (positions[x] != -1 && positions[y] != -1) { if (positions[x] != positions[y]) validTeam = false; } else { if (positions[x] == -1) { if (teamList.get(positions[y]).size() < 3) { teamList.get(positions[y]).add(x); positions[x] = positions[y]; } else validTeam = false; } else { if (teamList.get(positions[x]).size() < 3) { teamList.get(positions[x]).add(y); positions[y] = positions[x]; } else validTeam = false; } } } } if(validTeam) { int l = teamList.size(); for (int i = l; i < n / 3; i++) teamList.add(new ArrayList<Integer>()); l = 0; for (int i = 1; i <= n; i++) { if (positions[i] == -1) { while (teamList.get(l).size() >= 3) l++; positions[i] = l; teamList.get(l).add(i); } } for (int i = 0; i < teamList.size(); i++) { for (int j = 0; j < teamList.get(i).size(); j++) { if (j == teamList.get(i).size() - 1) System.out.println(teamList.get(i).get(j)); else System.out.print(teamList.get(i).get(j) + " "); } } } else System.out.println("-1"); } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
3985dc7391ce96d0422c2a2da60aa77d
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.regex.*; public class Main { public static ArrayList a[]=new ArrayList[300001]; public static boolean visit[]=new boolean [5000001]; static int parent[]=new int[100001]; static void ini() { for(int i=0;i<100;i++) parent[i]=i; } static int root(int n) { while(parent[n]!=n) { n=parent[n]; } return n; } static void union(int a,int b) { int p1=root(a); int p2=root(b); parent[p1]=parent[p2]; } static boolean find(int a,int b) { if(root(a)==root(b)) return true; else return false; } public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n=in.nextInt(); ini(); Vector<Integer>three=new Vector<>(); Vector<Integer>two=new Vector<>(); Vector<Integer>one=new Vector<>(); for(int i=0;i<=n;i++) a[i]=new ArrayList<Integer>(); int m=in.nextInt(); for(int i=0;i<m;i++) { int x=in.nextInt(); int y=in.nextInt(); union(x,y); } boolean chk[]=new boolean [n+1]; for(int i=1;i<=n;i++) { if(!chk[i]) { a[i].add(i); for(int j=i+1;j<=n;j++) { if(find(i,j)) { a[i].add(j); chk[j]=true; } } chk[i]=true; } } boolean fi=true; for(int i=1;i<=n;i++) { if(a[i].size()==3) three.add(i); if(a[i].size()==2) two.add(i); if(a[i].size()==1) one.add(i); else if(a[i].size()>3) fi=false; } if(two.size()>one.size()) fi=false; if(!fi) { pw.println(-1); pw.flush(); pw.close(); System.exit(0); } Vector<Integer>ans=new Vector<>(); for(int i=0;i<three.size();i++) { for(int j=0;j<a[three.get(i)].size();j++) ans.add((Integer) a[three.get(i)].get(j)); } int i=0; for( i=0;i<two.size();i++) { for(int j=0;j<a[two.get(i)].size();j++) { ans.add((Integer) a[two.get(i)].get(j)); } for(int j=0;j<a[one.get(i)].size();j++) { ans.add((Integer) a[one.get(i)].get(j)); } } for( ;i<one.size();i++) { for(int j=0;j<a[one.get(i)].size();j++) { ans.add((Integer) a[one.get(i)].get(j)); } } if(!fi) pw.println(-1); else for( i=0;i<ans.size();) { for(int j=0;j<3;j++) { pw.print(ans.get(i+j)+" "); } i+=3; } pw.flush(); pw.close(); } private static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class trie{ Integer cnt; trie a[]; trie(){ cnt=0; a=new trie[2]; } } 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; } static class tri implements Comparable<tri> { int p, c, l; tri(int p, int c, int l) { this.p = p; this.c = c; this.l = l; } public int compareTo(tri o) { return Integer.compare(l, o.l); } } 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 long d; public static long p; public static long q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static 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 int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(long d1,long d2) { if(d2==0) { d = d1; p = 1 ; q = 0; } else { extendedEuclid(d2, d1%d2); long temp = p; p = q; q = temp - (d1/d2)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x%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); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } public static pair[] shuffle(pair[] t, Random gen){ for(int i = 0, n = t.length;i < n;i++){ int ind = gen.nextInt(n-i)+i; pair d = t[i]; t[i] = t[ind]; t[ind] = d; } return t; } static class pair implements Comparable<pair> { Long x; Integer y; pair(long a,int w) { this.x=a; this.y=w; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
649f74d5d582d807c22ac9618c76e6ae
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
/* * * Date: 07 September 2019 * Time: 01:03:00 */ import java.io.*; import java.util.*; public class coach { static ArrayList<Integer> arr[]; coach(int v){ arr=new ArrayList[v]; for(int i=0;i<v;i++){ arr[i]=new ArrayList<Integer>(); } } static void addEdge(int u,int v){ arr[u].add(v); arr[v].add(u); } static int DFS(int s,int cnt,boolean visited[],ArrayList<Integer> brr[],int i){ brr[i].add(s); visited[s]=true; Iterator<Integer> itr=arr[s].listIterator(); while(itr.hasNext()){ int n=itr.next(); if(!visited[n]){ return DFS(n,cnt+1,visited,brr,i); } } return cnt; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); coach g=new coach(n); for(int i=0;i<m;i++){ int a=sc.nextInt()-1; int b=sc.nextInt()-1; addEdge(a,b); } boolean visited[]=new boolean[n]; ArrayList<Integer> brr[]=new ArrayList[n/3]; for(int i=0;i<n/3;i++){ brr[i]=new ArrayList<Integer>(); } int k=0; ArrayList<Integer> extra=new ArrayList<Integer>(); int cnt=0; for(int i=0;i<n;i++){ if(!visited[i]){ if(arr[i].size()==0){ continue; }else if(arr[i].size()<3){ cnt=DFS(i,1,visited,brr,k); }else{ System.out.println(-1); return; } //System.out.println("k: "+k); if(cnt>3){ System.out.println(-1); return; } if(k+1<n/3){ k++; }else{ if(brr[k].size()<3){ continue; }else{ k--; } } } } int p=0,s=0; for(int i=0;i<n/3;i++){ if(brr[i].size()>3){ System.out.println(-1); return; } } for(int i=0;i<n/3;i++){ if(brr[i].size()<3){ int x=3-brr[i].size(); s=p; for( p=s;p<n && x>0;p++){ if(!visited[p]){ visited[p]=true; brr[i].add(p); x--; } } } for(int j=0;j<brr[i].size();j++){ System.out.print(brr[i].get(j)+1+" "); } System.out.println(); } } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
0d4ab7f097c5b08427e61eb20252dfb7
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Throwable { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); UnionFind uf = new UnionFind(n); while(m-->0) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken())-1; int b = Integer.parseInt(st.nextToken())-1; uf.unionSet(a, b); } boolean flag = false; while(!flag) { flag = true; for (int i = 0; i < n; i++) { int set1 = uf.findSet(i); if(uf.setSize[set1]>3) { System.out.println(-1); return; } if(uf.setSize[set1]<3) { flag = false; int maxSize = 0; int set = uf.findSet(i); for (int j = 0; j < n && uf.setSize[set1]<3; j++) { set1 = uf.findSet(set1); int set2 = uf.findSet(j); if(set1!=set2 && uf.setSize[set2]+uf.setSize[set1]<=3) { if(uf.setSize[set2]>maxSize) { maxSize = uf.setSize[set2]; set = set2; } } } if(set == uf.findSet(i)) { System.out.println(-1); return; } uf.unionSet(set1, set); } } } ArrayList<Integer>[] arr = new ArrayList[n/3]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int ind = 0; for (int i = 0; i < arr.length; i++) { arr[i] = new ArrayList<Integer>(); } for (int i = 0; i < n; i++) { if(ind>arr.length) { System.out.println(-1); return; } int set = uf.findSet(i); if(map.containsKey(set)) arr[map.get(set)].add(i+1); else { map.put(set, ind); arr[ind++].add(i+1); } } for (int i = 0; i < arr.length; i++) { for(int j:arr[i]) System.out.print(j+" "); System.out.println(); } } static class UnionFind { int[] p, rank, setSize; int numSets; public UnionFind(int N) { p = new int[numSets = N]; rank = new int[N]; setSize = new int[N]; for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; } } public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); } public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } public void unionSet(int i, int j) { if (isSameSet(i, j)) return; numSets--; int x = findSet(i), y = findSet(j); if(rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } else { p[x] = y; setSize[y] += setSize[x]; if(rank[x] == rank[y]) rank[y]++; } } public int numDisjointSets() { return numSets; } public int sizeOfSet(int i) { return setSize[findSet(i)]; } } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
0a5cde5bd56c0dea28e70f691c804761
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.StringTokenizer; public class bfs_dfs { public static ArrayList<Integer>[] a; public static ArrayList<ArrayList<Integer>> rec; public static boolean[] vis; public static void main(String[] args) { mYScanner in = new mYScanner(); int n = in.nextInt(); int m = in.nextInt(); a = new ArrayList[n+1]; for(int i = 1;i<=n;i++) a[i] = new ArrayList<Integer>(); for(int i = 0;i<m;i++) { int src = in.nextInt(); int dest = in.nextInt(); a[src].add(dest); a[dest].add(src); } vis = new boolean[n+1]; rec = new ArrayList<ArrayList<Integer>>(); int one = 0; int two = 0; for(int i = 1;i<=n;i++) { if(!vis[i]) { rec.add(new ArrayList<Integer>()); vis[i] = true; rec.get(rec.size()-1).add(i); dfs(i); if(rec.get(rec.size()-1).size()==1) one++; if(rec.get(rec.size()-1).size()==2) two++; } } //System.out.println(one+" "+two); com c = new com(); Collections.sort(rec,c); if(rec.get(0).size()>3) System.out.println(-1); else { int rem = one-two; if(rem>=0 && rem%3==0) { while(!rec.isEmpty()) { for(int i = 0;i<rec.get(0).size();i++) System.out.print(rec.get(0).get(i)+" "); if(rec.get(0).size()==2) { System.out.print(rec.get(rec.size()-1).get(0)+" "); rec.remove(rec.size()-1); } if(rec.get(0).size()==1) { System.out.print(rec.get(rec.size()-1).get(0)+" "); rec.remove(rec.size()-1); System.out.print(rec.get(rec.size()-1).get(0)+" "); rec.remove(rec.size()-1); } System.out.println(); rec.remove(0); } } else System.out.println(-1); } } public static void dfs(int m) { for(int i = 0;i<a[m].size();i++) { if(!vis[a[m].get(i)]) { vis[a[m].get(i)] = true; rec.get(rec.size()-1).add(a[m].get(i)); dfs(a[m].get(i)); } } } } class com implements Comparator<ArrayList<Integer>> { @Override public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) { return o2.size()-o1.size(); } } class mYScanner { BufferedReader br ; StringTokenizer st; public mYScanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = null; } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
9691a1eed69987e1d13e92c47b34af9c
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.util.*; public class Solution { public static void addEdge(ArrayList<ArrayList<Integer>> adj,int u,int v) { adj.get(u).add(v); adj.get(v).add(u); } public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int m=in.nextInt(); /*if(m==0) { for(int i=1;i<=n;i++) { System.out.print(i+" "); if(i%3==0) System.out.println(); } return; }*/ ArrayList<ArrayList<Integer>> adj=new ArrayList<ArrayList<Integer>>(); for(int i=1;i<=n+1;i++) adj.add(new ArrayList<Integer>()); for(int i=0;i<m;i++) addEdge(adj, in.nextInt(), in.nextInt()); ArrayList<Integer> list[]=new ArrayList[n]; for(int i=0;i<n;i++) list[i]=new ArrayList<Integer>(); int j=0; boolean visited[]=new boolean[n+1]; Arrays.fill(visited, false); for(int i=1;i<=n;i++) { if(!visited[i]) { if(adj.get(i).size()==0) continue; Queue<Integer> Q=new LinkedList<Integer>(); Q.add(i); list[j].add(i); visited[i]=true; while(!Q.isEmpty()) { int p=Q.poll(); for(int k=0;k<adj.get(p).size();k++) { int child=adj.get(p).get(k); if(!visited[child]) { Q.add(child); list[j].add(child); visited[child]=true; } } } if(list[j].size()>3) { System.out.println(-1); return; } j++; } } int count=0; for(int i=0;i<j;i++) { if(list[i].size()==2) count++; } Stack<Integer> S=new Stack<Integer>(); for(int i=1;i<=n;i++) { if(!visited[i]) S.push(i); } if(S.size()>=count && ((S.size()-count)%3==0)) { for(int i=0;i<j;i++) { if(list[i].size()==3) { System.out.print(list[i].get(2)+" "+list[i].get(1)+" "+list[i].get(0)); System.out.println(); } else { System.out.print(list[i].get(1)+" "+list[i].get(0)+" "+S.peek()); S.pop(); System.out.println(); } } while(!S.empty()) { System.out.print(S.peek()+" "); S.pop(); System.out.print(S.peek()+" "); S.pop(); System.out.print(S.peek()+" "); S.pop(); System.out.println(); } } else System.out.println(-1); } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
3a0d4fe6dd320744cd74643e34a1d0db
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; public class Main { static int[] sz; static int[] p; static int[] e; public static void main(String[] args) throws IOException { //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //(new FileReader("input.in")); StringBuilder out = new StringBuilder(); //// StringTokenizer tk; // Scanner Reader = new Scanner(System.in); Reader.init(System.in); int n = Reader.nextInt(), m = Reader.nextInt(); p = new int[n]; sz = new int[n]; e = new int[n]; for (int i = 0; i < n; i++) { p[i] = i; sz[i] = 1; } while (m-- > 0) { int a = Reader.nextInt() - 1, b = Reader.nextInt() - 1; a = find(a); b = find(b); if (a != b) { p[a] = b; sz[b] += sz[a]; e[b] += e[a] + 1; } else { e[a]++; } } for (int i = 0; i < n; i++) { p[i]=find(i); sz[i]=sz[find(i)]; } List[]a=new ArrayList[n]; for (int i = 0; i < n; i++) a[i]=new ArrayList<Integer>(); LinkedList<Integer>h=new LinkedList<>(); for (int i = 0; i < n; i++) { if(sz[i]==3){ a[p[i]].add(i+1); } if(sz[i]>3){ System.out.println("-1"); return; } if(sz[i]==2){ a[p[i]].add(i+1); } if(sz[i]==1) h.add(i); } for (int i = 0; i < n; i++) { if(a[i].size()==2){ if(h.size()>0){ a[i].add(h.get(0)+1); h.remove(0); } else { System.out.println("-1"); return; } } } if(h.size()%3==0){ for (int i = 0; i < a.length; i++) { boolean f=false; if(a[i].size()==3) for (int j = 0; j < a[i].size(); j++) { out.append(a[i].get(j)).append(" "); f=true; } if(f) out.append("\n"); } for (int i = 0,j=1; i < h.size(); i++,j++) { out.append(h.get(i)+1).append(" "); if(j==3){out.append("\n");j=0;} } System.out.print(out); }else System.out.println("-1"); } static int find(int u) {//to find the root if (u == p[u]) { return u; } return p[u] = find(p[u]); } } class Reader { static StringTokenizer tokenizer; static BufferedReader reader; public static void init(InputStream input) throws UnsupportedEncodingException { reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); tokenizer = new StringTokenizer(""); } public static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static String nextLine() throws IOException { return reader.readLine(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
cc00da7028c9fdc366a2b46f88647c07
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.*; import java.util.*; public class Main { static FastScanner in; static ArrayList<ArrayList<Integer>> lis = new ArrayList<ArrayList<Integer>>(); static boolean[] check; public static void main(String[] args) throws IOException { // System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("nocross.out")), true)); in = new FastScanner(System.in); // in = new FastScanner("nocross.in"); // in = new FastScanner("input.txt"); int n = in.nextInt(); int m = in.nextInt(); ArrayList<Integer> g[] = new ArrayList[n + 1]; for (int i = 1; i <= n; i++) { g[i] = new ArrayList<Integer>(); } for (int i = 0; i < m; i++) { int a = in.nextInt(); int b = in.nextInt(); g[a].add(b); g[b].add(a); } check = new boolean[n + 1]; boolean ok = dfsCheck(g); if (ok) { for (ArrayList<Integer> li : lis) { if (li.size() == 3) { System.out.println(li.get(0) + " " + li.get(1) + " " + li.get(2)); } else if (li.size() == 2) { for (int i = 1; i <= n; i++) { if (check[i]) { check[i] = false; System.out.println(li.get(0) + " " + li.get(1) + " " + i); break; } } } } ArrayList<Integer> li = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { if (check[i]) { check[i] = false; li.add(i); } if (li.size() == 3) { System.out.println(li.get(0) + " " + li.get(1) + " " + li.get(2)); li.clear(); } } } else { System.out.println(-1); } } static boolean dfsCheck(ArrayList<Integer> g[]) { int n = g.length - 1; boolean isVisited[] = new boolean[n + 1]; Stack<Integer> st = new Stack<Integer>(); int num = 0; for (int i = 1; i <= n; i++) { int count = 0; if (!isVisited[i]) { num++; ArrayList<Integer> li = new ArrayList<Integer>(); isVisited[i] = true; st.push(i); while (!st.isEmpty()) { count++; int u = st.pop(); li.add(u); for (int v : g[u]) { if (!isVisited[v]) { isVisited[v] = true; st.push(v); } } } if (li.size() == 1) { check[li.get(0)] = true; num--; } lis.add(li); } if (count > 3) return false; } if (num > n / 3) return false; return true; } } class FastScanner { BufferedReader br; StringTokenizer tokenizer; FastScanner(String fileName) throws FileNotFoundException { this(new FileInputStream(new File(fileName))); } FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String nextLine() throws IOException { tokenizer = null; return br.readLine(); } String next() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } char nextChar() throws IOException { return next().charAt(0); } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
34ff5a6ba22b12251ed67074ed60dc58
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.List; import java.io.Writer; import java.io.OutputStreamWriter; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Tahsin Rashad */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); Task solver = new Task(); solver.solve(1, in, out); out.close(); } static class Task { List<Integer>[] list; List<Integer>[] group; boolean[] visited; int r; public void solve(int testNumber, InputReader in, OutputWriter out) { list = new List[500]; group = new List[500]; visited = new boolean[500]; Arrays.fill(visited, false); int n = in.nextInt(); int m = in.nextInt(); for (int i = 0; i < m; i++) { int x, y; x = in.nextInt(); y = in.nextInt(); if (list[x] == null) { list[x] = new ArrayList<>(); } if (list[y] == null) { list[y] = new ArrayList<>(); } list[x].add(y); list[y].add(x); } r = 0; for (int i = 1; i <= n; i++) { if (list[i] != null) { if (list[i].size() != 0 && !visited[i]) { dfs(i); r++; } } } if (r > n / 3) { out.println(-1); return; } for (int i = 0; i < n / 3; i++) { if (group[i] != null) { if (group[i].size() > 3) { out.println(-1); return; } } } r = 0; for (int i = 1; i <= n; i++) { if (!visited[i]) { if (group[r] != null) { while (group[r].size() == 3) { r++; if (group[r] == null) { group[r] = new ArrayList<>(); } } } if (group[r] == null) { group[r] = new ArrayList<>(); } group[r].add(i); } } r = n / 3; for (int i = 0; i < r; i++) { for (int j = 0; j < group[i].size(); j++) { if (group[i] != null) { out.print(group[i].get(j) + " "); } } out.println(); } } private void dfs(int x) { if (group[r] == null) { group[r] = new ArrayList<>(); } group[r].add(x); visited[x] = true; for (int i = 0; i < list[x].size(); i++) { int y = list[x].get(i); if (!visited[y]) { dfs(y); } } } } 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() { writer.println(); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } 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 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
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
6817443b6778e8e596a2cc702cac22de
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ public static class pair{ int x; int y; } public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line=br.readLine(); String[] strs=line.trim().split(" "); int n=Integer.parseInt(strs[0]); int t=Integer.parseInt(strs[1]); int[] arr=new int[n]; for(int i=0;i<arr.length;i++){ arr[i]=i+1; } HashMap<Integer,ArrayList<Integer>> map=new HashMap<>(); while(t-->0){ line=br.readLine(); strs=line.trim().split(" "); int a=Integer.parseInt(strs[0]); int b=Integer.parseInt(strs[1]); int val=arr[a-1]; for(int i=0;i<arr.length;i++){ if(arr[i]==arr[b-1]){ arr[i]=val; } } } for(int i=0;i<arr.length;i++){ if(map.containsKey(arr[i])){ ArrayList<Integer> list=map.get(arr[i]); list.add(i+1); map.put(arr[i],list); }else{ ArrayList<Integer> list=new ArrayList<>(); list.add(i+1); map.put(arr[i],list); } } HashMap<Integer,ArrayList<Integer>> mapi=new HashMap<>(); for(int key:map.keySet()){ if(mapi.containsKey(map.get(key).size())){ ArrayList<Integer> list=mapi.get(map.get(key).size()); list.add(key); mapi.put(map.get(key).size(),list); }else{ ArrayList<Integer> list=new ArrayList<>(); list.add(key); mapi.put(map.get(key).size(),list); } } for(int i=4;i<=n;i++){ if(mapi.containsKey(i)){ System.out.println("-1"); return; } } ArrayList<ArrayList<Integer>> list1=new ArrayList<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> list2=new ArrayList<ArrayList<Integer>>(); for(int key:mapi.keySet()){ if(key==2){ ArrayList<Integer> list=mapi.get(key); int m=list.size(); for(int i=0;i<m;i++){ int v=list.get(i); ArrayList<Integer> li=map.get(v); list2.add(li); map.remove(v); } } if(key==1){ ArrayList<Integer> list=mapi.get(key); int m=list.size(); for(int i=0;i<m;i++){ int v=list.get(i); ArrayList<Integer> li=map.get(v); list1.add(li); map.remove(v); } } } if(list1.size()<list2.size()||(list1.size()-list2.size())%3!=0){ System.out.println("-1"); return; } int k=0; for(int i=0;i<list2.size();i++){ System.out.println(list2.get(i).get(0)+" "+list2.get(i).get(1)+" "+list1.get(k).get(0)); k++; } for(int i=k;i<list1.size();i=i+3){ System.out.println(list1.get(i).get(0)+" "+list1.get(i+1).get(0)+" "+list1.get(i+2).get(0)); } for(int key:mapi.keySet()){ if(key==3){ ArrayList<Integer> list=mapi.get(key); int m=list.size(); for(int i=0;i<m;i++){ int v=list.get(i); ArrayList<Integer> li=map.get(v); System.out.println(li.get(0)+" "+li.get(1)+" "+li.get(2)); map.remove(v); } } } } public static class Comp implements Comparator<pair>{ @Override public int compare(pair a,pair b){ return a.x-b.x; } } public static void pr(int v1,int v2){ int v3=v1; int v4=v2; // System.out.println(v1+" "+v2); for(int i=2;i<=Math.min(v3,v4);i++){ while(v1%i==0&&v2%i==0){ v1/=i; v2/=i; } } System.out.println(v1+"/"+v2); } public static int lcm(int a,int b){ int x=Math.max(a,b); int y=Math.min(a,b); long ans=x; while(ans%y!=0){ ans+=x; } return (int)ans; } public static long fact(int n){ long ans=1; for(int i=1;i<=n;i++){ ans*=i; } return ans; } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
29bab9e9e5ce81319d0deb8d627303ae
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.util.*;import java.io.*;import java.math.*; public class temp { public static class CustomSort implements Comparator<ArrayList<Integer>>{ public int compare(ArrayList<Integer> a,ArrayList<Integer> b){ return (a.size()-b.size()); } } public static void process()throws IOException { int n=ni(); int m=ni(); int dsu[]=new int[n+1]; for(int i=1;i<=n;i++) dsu[i]=i; // TreeSet<Integer> set = new TreeSet<Integer>(); // for(int i=1;i<=n;i++) // set.add(i); for(int i=0;i<m;i++) { int x=ni(); int y=ni(); dsu=union(dsu,x,y); // set.remove(x); // set.remove(y); } // pn(Arrays.toString(dsu)); ArrayList<Integer>[]g=new ArrayList[n+1]; for(int i=0;i<=n;i++) g[i]=new ArrayList<>(); for(int i=1;i<=n;i++) g[dsu[i]].add(i); int c1=0,c2=0,c3=0,c4=0; for(int i=0;i<=n;i++) { int x=g[i].size(); if(x==1) c1++; if(x==2) c2++; if(x>3) c4++; } Arrays.sort(g,new CustomSort()); if(c2>c1 || (c2-c1)%3!=0 || c4>0) { pn("-1"); return; } for(int i=0;i<=n;i++) { if(g[i].size()==3) { for(int j=0;j<g[i].size();j++) p(g[i].get(j)+" "); g[i].clear(); pn(""); } if(g[i].size()==2) { for(int j=0;j<g[i].size();j++) p(g[i].get(j)+" "); g[i].clear(); for(int j=0;j<n;j++) { if(g[j].size()==1) { for(int k=0;k<g[j].size();k++) p(g[j].get(k)+" "); g[j].clear(); break; } } pn(""); } int flag=0; if(g[i].size()==1) { p(g[i].get(0)+" "); g[i].clear(); for(int j=0;j<n;j++) { if(g[j].size()==2) { for(int k=0;k<g[j].size();k++) p(g[j].get(k)+" "); g[j].clear(); flag=1; break; } } if(flag==0) { for(int j=0;j<n;j++) { if(g[j].size()==1) { p(g[j].get(0)+" "); g[j].clear(); for(int k=0;k<n;k++) { if(g[k].size()==1) { pn(g[k].get(0)); g[k].clear(); break; } } break; } } } } } // int c=0; // for(Integer x:set) // { // p(x+" "); // c++; // if(c==3) // { // c=0; // pn(""); // } // } } static int[] union(int[]dsu ,int x,int y) { int temp=dsu[x]; for(int i=0;i<dsu.length;i++) if(dsu[i]==temp) dsu[i]=dsu[y]; return dsu; } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} int t=1; // t=ni(); while(t-->0) {process();} out.flush();out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;} static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
4d966f9db492948cd257557296baa954
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Coach { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); Graph[] graph = new Graph[n+1]; for (int i = 0 ; i < n+1 ; i++) { graph[i] = new Graph(); graph[i].i = i; } int r = scan.nextInt(); for (int i = 0 ; i < r ; i++) { int f = scan.nextInt(); int s = scan.nextInt(); graph[f].connected.add(s); graph[s].connected.add(f); } solve(graph); } static boolean[] visited; static void solve(Graph[] graph) { int twos = 0; int ones = 0; visited = new boolean[graph.length]; ArrayList<String> ans = new ArrayList<>(); for (int i = 1 ; i < graph.length ; i++) { if (!visited[i]) { int size = graphSize(graph[i], graph); // System.out.println(size); if (size > 3) { System.out.println(-1); return ; } else if (size == 1) ones++; else if (size == 2) twos++; else { ans.add(getStream(graph[i], graph,i)); } } } if (ones < twos) { System.out.println(-1); return ; } else { visited = new boolean[graph.length]; ArrayList<String> oneNode = new ArrayList<>(); ArrayList<String> twoNodes = new ArrayList<>(); for (int i = 1 ; i < graph.length ; i++) { if (!visited[i]) { int size = graphSize(graph[i], graph); if (size == 1) { oneNode.add(i + " "); } else if (size == 2) { twoNodes.add(getStream(graph[i], graph,i)); } } } for (int i = 0 ; i < twos ; i++) { ans.add(oneNode.get(i) + twoNodes.get(i)); } ones -= twos; if (ones != 0 && ones % 3 == 0) { for (int i = 0 ; i < ones ; i+= 3) { ans.add(oneNode.get(twos+i) + oneNode.get(twos+i+1) + oneNode.get(twos+i+2)); } } else if (ones != 0 && ones % 3 != 0) { System.out.println(-1); return ; } for (int i = 0 ; i < ans.size() ; i++) { System.out.println(ans.get(i)); } } } static int graphSize(Graph g, Graph[] graph) { int count = dfs(g, graph); return count; } static void print(boolean []v) { for (int i = 1 ; i < v.length ; i++) { System.out.print(v[i] + " "); } System.out.println(); } static int dfs(Graph g, Graph[] graph) { int count = 1; if (visited[g.i]) count = 0; visited[g.i] = true; for (int i = 0 ; i < g.connected.size() ; i++) { if (!visited[g.connected.get(i)]) { visited[g.connected.get(i)] = true; // System.out.println(g.i + " " + count + " " + g.connected.get(i)); count += 1 + dfs(graph[g.connected.get(i)],graph); } } return count; } static boolean[] visited2; static String getStream(Graph g , Graph[] graph, int ind) { visited2 = new boolean[graph.length]; return dfs2(g,graph); } static String dfs2(Graph g, Graph[] graph) { String ans = ""; for (int i = 0 ; i < g.connected.size() ; i++) { if (!visited2[g.connected.get(i)]) { visited2[g.connected.get(i)] = true; ans += g.connected.get(i) + " "+ dfs2(graph[g.connected.get(i)],graph); } } return ans; } } class Graph { int i; ArrayList<Integer> connected = new ArrayList<>(); }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
5ed88170ebfb299aef8d88531dca7795
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.awt.image.AreaAveragingScaleFilter; import java.util.*; import java.io.*; public class Coach { InputStream is; PrintWriter out; String INPUT = ""; void solve() throws IOException { int n= ni(), m= ni(); ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>(); for(int i=0;i<=n;i++) arrayLists.add(new ArrayList<>()); for(int i=0;i<m;i++) { int a= ni() , b= ni(); arrayLists.get(a).add(b); arrayLists.get(b).add(a); } boolean[] visited= new boolean[n+1]; HashMap<Integer, ArrayList<ArrayList<Integer>>> map = new HashMap<>(); map.put(1, new ArrayList<>()); map.put(2, new ArrayList<>()); StringBuilder br= new StringBuilder(); for(int i=1;i<=n;i++) { if(visited[i]) continue; ArrayList<Integer> len= new ArrayList<Integer>(); DFSREC(arrayLists, visited, i, len); if(len.size()> 3) { out.println("-1"); return; } else if(len.size()== 3) { br.append(len.get(0)+" "+len.get(1)+" "+len.get(2)+"\n"); } else { if(map.containsKey(len.size())) map.get(len.size()).add(len); else { ArrayList<ArrayList<Integer>> temp= new ArrayList<>(); temp.add(len); map.put(len.size(), temp); } } } if(map.getOrDefault(1, new ArrayList<>()).size()< map.getOrDefault(2, new ArrayList<>()).size()) out.println("-1"); else { ArrayList<ArrayList<Integer>> one= map.get(1); ArrayList<ArrayList<Integer>> two= map.get(2); out.print(br); int i; for(i=0;i<two.size();i++) { out.println(one.get(i).get(0)+" "+two.get(i).get(0)+" "+two.get(i).get(1)); } int count=1; for(;i<one.size();i++) { if(count%3==0) out.println(one.get(i).get(0)); else out.print(one.get(i).get(0)+" "); count++; } } } private void DFSREC(ArrayList<ArrayList<Integer>> arrayLists, boolean[] visited, int curr, ArrayList<Integer> len) { visited[curr]= true; len.add(curr); for(Integer integer: arrayLists.get(curr)) { if(visited[integer]) continue; DFSREC(arrayLists, visited, integer, len); } } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new Coach().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 void tr(Object... o) { if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o)); } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
6af426db8653ad0ee542e95ecf1ce55d
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.util.*; public class Ladder { static Vector<Integer>[] graph; static boolean vis[]; static int root; static ArrayList<Integer> temp = new ArrayList<>(); public static int dfs(int node) { vis[node] = true; temp.add(node); int ret = 0; for (int i = 0; i < graph[node].size(); i++) { int chiled = graph[node].get(i); if (!vis[chiled]) { ret += 1 + dfs(chiled); } } return ret; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); graph = new Vector[n + 1]; vis = new boolean[n + 1]; for (int i = 0; i < n + 1; i++) { graph[i] = new Vector<>(); } for (int i = 0; i < m; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); graph[a].add(b); graph[b].add(a); } int r = 0; StringBuilder sb = new StringBuilder(); for (int i = 1; i < n + 1; i++) { temp.clear(); if (!vis[i] && !graph[i].isEmpty()) { r = dfs(i); if (r == 2) { sb.append(temp.get(0) + " " + temp.get(1) + " " + temp.get(2) + "\n"); } else if (r == 1) { for (int j = 1; j < graph.length; j++) { if (graph[j].isEmpty() && !vis[j]) { vis[j] = true; sb.append(temp.get(0) + " " + temp.get(1) + " "); sb.append(j + "\n"); break; } } } else { System.out.println("-1"); return; } } } int cnt=0; for (int i = 1; i <graph.length; i++) { if(!vis[i]){ cnt++; if(cnt==3){ sb.append(i+"\n"); cnt=0; }else{ sb.append(i+" "); } } } String arr[] = sb.toString().split("\n"); System.out.println(((arr.length!=(n/3))?-1:sb)); } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
a145326f82f2095b946c1041aba0f286
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.*; public class CF300B { static void dfs(int node,boolean[] visited, ArrayList<Integer> component,LinkedList<Integer>[] list){ component.add(node); visited[node] = true; for(int j : list[node]){ if(!visited[j]){ dfs(j,visited,component,list); } } } public static void main(String[] args) { FastReader input = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int n = input.nextInt(); LinkedList<Integer>[] list = new LinkedList[n+1]; for(int i = 1;i <= n;i++) list[i] = new LinkedList<>(); int m = input.nextInt(); for(int i = 0;i < m;i++){ int u = input.nextInt(); int v = input.nextInt(); list[u].add(v); list[v].add(u); } boolean[] visited = new boolean[n+1]; LinkedList<ArrayList<Integer>> one = new LinkedList<>(); LinkedList<ArrayList<Integer>> two = new LinkedList<>(); LinkedList<ArrayList<Integer>> three = new LinkedList<>(); boolean con = true; for(int i = 1;i <= n;i++){ if(!visited[i]){ ArrayList<Integer> component = new ArrayList<>(); dfs(i,visited,component,list); if(component.size() > 3){ con = false; break; } else{ if(component.size() == 1){ one.add(component); } else if(component.size() == 2){ two.add(component); } else if(component.size() == 3){ three.add(component); } } } } if(!con){ pw.println(-1); } else{ if(one.size() < two.size()){ pw.println(-1); } else{ int left = one.size() - two.size(); if(left % 3 != 0){ pw.println(-1); } else{ while (!two.isEmpty()){ ArrayList<Integer> p = two.pop(); ArrayList<Integer> q = one.pop(); pw.println(p.get(0) + " " + p.get(1) + " " + q.get(0)); } while (!one.isEmpty()){ pw.println(one.pop().get(0) + " " + one.pop().get(0) + " " + one.pop().get(0)); } while (!three.isEmpty()){ ArrayList<Integer> r = three.pop(); pw.println(r.get(0) + " " + r.get(1) + " " + r.get(2)); } } } } // ****If sorting is required, use ArrayList pw.flush(); pw.close(); } static void sort(int[] arr){ ArrayList<Integer> list = new ArrayList<Integer>(); for(int i : arr) list.add(i); Collections.sort(list); for(int i = 0;i < list.size();i++){ arr[i] = list.get(i); } return; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
9529d5b14ad5599a72b367bd51791384
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Coach { static ArrayList<Integer>[] adjList; static ArrayList<ArrayList<Integer>> teams = new ArrayList<ArrayList<Integer>>(); static boolean vis[]; static int nodes,l=0; public static void dfs(int node) { vis[node] = true; teams.get(l).add(node+1); for (int i=0;i<adjList[node].size();i++) { int to = adjList[node].get(i); if (!vis[to]) dfs(to); } } public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); adjList = new ArrayList[n]; vis = new boolean[n]; for (int i=0;i<n;i++) adjList[i] = new ArrayList<Integer>(); for (int i=0;i<m;i++) { int a = sc.nextInt()-1; int b = sc.nextInt()-1; adjList[a].add(b); adjList[b].add(a); } ArrayList<Integer> ones = new ArrayList<Integer>(); ArrayList<Integer> twos = new ArrayList<Integer>(); ArrayList<Integer> threes = new ArrayList<Integer>(); for (int i=0;i<n;i++) { if (!vis[i]) { teams.add(new ArrayList<Integer>()); dfs(i); int s = teams.get(l).size(); switch (s) { case 1: ones.add(l); break; case 2: twos.add(l); break; case 3: threes.add(l); break; default: System.out.println(-1); return; } l++; } } if (ones.size()<twos.size() || (ones.size()-twos.size())%3>0) { System.out.println(-1); return; } StringBuilder sb = new StringBuilder(); for (int i=0;i<threes.size();i++) { int index = threes.get(i); for (int j=0;j<3;j++) sb.append(teams.get(index).get(j)+" "); sb.append("\n"); } for (int i=0;i<twos.size();i++) { int index = ones.get(i); sb.append(teams.get(index).get(0)); index = twos.get(i); sb.append(" "+teams.get(index).get(0)+" "+teams.get(index).get(1)+"\n"); } for (int i=twos.size();i<ones.size();i++) { int index = ones.get(i++); sb.append(teams.get(index).get(0)+" "); index = ones.get(i++); sb.append(teams.get(index).get(0)+" "); index = ones.get(i); sb.append(teams.get(index).get(0)+"\n"); } System.out.println(sb); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
c6084f1f1276cd0be48a431444cab0b8
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; public class practiceQuestions1 { static class Reader { final private int BUFFER_SIZE = 1 << 12; boolean consume = false; private byte[] buffer; private int bufferPointer, bytesRead; private boolean reachedEnd = false; public Reader() { buffer = new byte[BUFFER_SIZE]; bufferPointer = 0; bytesRead = 0; } public boolean hasNext() { return !reachedEnd; } private void fillBuffer() throws IOException { bytesRead = System.in.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) { buffer[0] = -1; reachedEnd = true; } } private void consumeSpaces() throws IOException { while (read() <= ' ' && reachedEnd == false) ; bufferPointer--; } private byte read() throws IOException { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } public String next() throws IOException { StringBuilder sb = new StringBuilder(); consumeSpaces(); byte c = read(); do { sb.append((char) c); } while ((c = read()) > ' '); if (consume) { consumeSpaces(); } ; if (sb.length() == 0) { return null; } return sb.toString(); } public String nextLine() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); return str; } public int nextInt() throws IOException { consumeSpaces(); int ret = 0; byte c = read(); boolean neg = (c == '-'); if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (consume) { consumeSpaces(); } if (neg) { return -ret; } return ret; } public long nextLong() throws IOException { consumeSpaces(); long ret = 0; byte c = read(); boolean neg = (c == '-'); if (neg) { c = read(); } do { ret = ret * 10L + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (consume) { consumeSpaces(); } if (neg) { return -ret; } return ret; } public double nextDouble() throws IOException { consumeSpaces(); double ret = 0; double div = 1; byte 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 (consume) { consumeSpaces(); } if (neg) { return -ret; } return ret; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public int[][] nextIntMatrix(int n, int m) throws IOException { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { grid[i] = nextIntArray(m); } return grid; } public char[][] nextCharacterMatrix(int n) throws IOException { char[][] a = new char[n][]; for (int i = 0; i < n; i++) { a[i] = next().toCharArray(); } return a; } public void close() throws IOException { if (System.in == null) { return; } else { System.in.close(); } } } static Reader r = new Reader(); static PrintWriter out = new PrintWriter(System.out); private static void solve1() throws IOException { int n = r.nextInt(); int k = r.nextInt(); int arr[] = r.nextIntArray(n); Arrays.sort(arr); int cnt = 0, max = 5 - k; for (int i = 0; i < n; i++) { if (arr[i] > max) { break; } cnt++; } int ans = (cnt / 3); out.print(ans); out.close(); } private static boolean checker(String s) { for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '1' && (i + 2) < s.length() && s.substring(i, i + 3) == "111") { return false; } else if (s.charAt(i) == '0' && (i + 1) < s.length() && s.substring(i, i + 2) == "00") { return false; } } return true; } private static void solve2() throws IOException { int n = r.nextInt(); int m = r.nextInt(); String ans = ""; StringBuilder temp = new StringBuilder(); while (n + m > 2 && n != 0 && m != 0) { if (m >= 2 * n) { temp.append("110"); m -= 2; n -= 1; } else { temp.append("10"); m -= 1; n -= 1; } } ans = temp.toString(); if (n == 1 && m == 0) { temp.insert(0, '0'); ans = temp.toString(); } else if (m == 2 && n == 0 || m == 1 && n == 0) { for (int i = 1; i <= m; i++) { temp.append("1"); } ans = temp.toString(); } else if (n == 1 && m == 1) { temp.append("10"); ans = temp.toString(); } else if (m != 0 || n != 0) { ans = "-1"; } // System.out.println(checker(ans)); out.print(ans); out.close(); } private static void solve3() throws IOException { String a = r.next(); String b = r.next(); boolean flag = false; if (a.length() == b.length()) { if (a.equals(b)) { flag = true; } else { flag = ((a.contains("1") && b.contains("1")) || ((!a.contains("1") && !b.contains("1")))) ? true : false; } } out.print(flag ? "YES" : "NO"); out.close(); } private static void solve4() throws IOException { int n = r.nextInt(); StringBuilder res = new StringBuilder(); int A = 0, G = 0; boolean flag = true; while (n-- > 0) { int a = r.nextInt(); int g = r.nextInt(); int temp_a = A + a; int temp_g = G + g; if (flag) { if (Math.abs(temp_a - G) > 500) { if (Math.abs(temp_g - A) > 500) { flag = false; } else { G = temp_g; res.append("G"); } } else { A = temp_a; res.append("A"); } } } out.print(flag ? res : -1); out.close(); } static class sortedArr { int idx; long freq; public sortedArr(int id, long val) { idx = id; freq = val; } } static class Query { int lt, rt; public Query(int l, int r) { lt = l; rt = r; } } private static void solve5() throws IOException { int n = r.nextInt(); int q = r.nextInt(); long arr[] = new long[n + 1]; for (int i = 1; i <= n; i++) { arr[i] = r.nextLong(); } Arrays.sort(arr); long freq[] = new long[n + 2]; sortedArr array[] = new sortedArr[n + 2]; Query qu[] = new Query[q]; for (int i = 0; i < array.length; i++) { array[i] = new sortedArr(0, 0); } for (int i = 0; i < q; i++) { int lt = r.nextInt(); int rt = r.nextInt(); qu[i] = new Query(lt, rt); freq[lt]++; freq[rt + 1]--; } for (int i = 1; i <= n; i++) { freq[i] += freq[i - 1]; array[i].idx = i; array[i].freq = freq[i]; } Arrays.sort(array, new Comparator<sortedArr>() { @Override public int compare(sortedArr o1, sortedArr o2) { return Integer.compare((int) o2.freq, (int) o1.freq); } }); long fin_arr[] = new long[n + 1]; int idx = n; for (int i = 0; i < n; i++) { fin_arr[array[i].idx] = arr[idx--]; } for (int i = 1; i <= n; i++) { fin_arr[i] += fin_arr[i - 1]; } // System.out.println(Arrays.toString(fin_arr)); long ans = 0; for (int i = 0; i < q; i++) { ans += (fin_arr[qu[i].rt] - fin_arr[qu[i].lt - 1]); } out.print(ans); out.close(); } static long time[]; private static long binarySearch(long t, int endI) { int i = 0, j = endI; long ans = 0, val = time[j]; while (i <= j) { int mid = (i + j) / 2; if (val - time[mid] <= t) { ans = Math.max(ans, endI - mid); j = mid - 1; } else { i = mid + 1; } } return ans; } private static void solve6() throws IOException { int n = r.nextInt(); long t = r.nextLong(); time = new long[n]; for (int i = 0; i < n; i++) { time[i] = r.nextLong(); if (i > 0) { time[i] += time[i - 1]; } } // System.out.println(Arrays.toString(time)); long ans = Long.MIN_VALUE; for (int i = n - 1; i >= 0; i--) { if (i == n - 1 && time[i] <= t) { ans = n; break; } ans = Math.max(ans, binarySearch(t, i)); } out.print(ans); out.close(); } static boolean seive[] = new boolean[1000001]; public static void primeSeive() { Arrays.fill(seive, true); seive[0] = seive[1] = false; for (int i = 2; i * i <= 1000000; i++) { if (seive[i]) { for (int j = i * i; j <= 1000000; j += i) { if (seive[j]) { seive[j] = false; } } } } } private static void solve7() throws IOException { int n = r.nextInt(); int m = r.nextInt(); primeSeive(); int mat[][] = r.nextIntMatrix(n, m); int rowMin = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int cnt = 0; for (int j = 0; j < m; j++) { if (!seive[mat[i][j]]) { int num = mat[i][j]; while (!seive[num]) { num++; cnt++; } } } rowMin = Math.min(rowMin, cnt); } int colMin = Integer.MAX_VALUE; for (int i = 0; i < m; i++) { int cnt = 0; for (int j = 0; j < n; j++) { if (!seive[mat[j][i]]) { int num = mat[j][i]; while (!seive[num]) { num++; cnt++; } } } colMin = Math.min(colMin, cnt); } int ans = Math.min(rowMin, colMin); out.print(ans); out.close(); } private static void solve8() throws IOException { int n = r.nextInt(); int freq[] = new int[(int) 1e5 + 1]; for (int i = 0; i < n; i++) { freq[r.nextInt()]++; } long dp[] = new long[(int) 1e5 + 1]; dp[1] = freq[1]; for (int i = 2; i < dp.length; i++) { dp[i] = Math.max(dp[i - 1], (dp[i - 2] + (long) freq[i] * i)); } out.print(dp[100000]); out.close(); } private static void solve9() throws IOException { String s = r.next(); StringBuilder ans = new StringBuilder(); for (int i = 0; i < s.length(); i++) { if (i >= 2 && s.charAt(i) == s.charAt(i - 1) && s.charAt(i - 1) == s.charAt(i - 2) || ans.length() >= 3 && s.charAt(i) == ans.charAt(ans.length() - 1) && ans.charAt(ans.length() - 2) == ans.charAt(ans.length() - 3)) { continue; } ans.append(s.charAt(i)); } out.print(ans); out.close(); } private static void solve10() throws IOException { long ans1 = 0, ans2 = 0; long red = r.nextLong(); long green = r.nextLong(); long blue = r.nextLong(); ans1 = (red / 3) + (green / 3) + (blue / 3); ans1 += Math.min((red % 3), Math.min((green % 3), (blue % 3))); long a = 0, b = 0, c = 0; if (red % 3 != 0) { ans2 += (red / 3); a = red % 3; } else { if (red >= 1) { ans2 += (red - 1) / 3; a = 3; } } if (green % 3 != 0) { ans2 += (green / 3); b = green % 3; } else { if (green >= 1) { ans2 += (green - 1) / 3; b = 3; } } if (blue % 3 != 0) { ans2 += (blue / 3); c = blue % 3; } else { if (blue >= 1) { ans2 += (blue - 1) / 3; c = 3; } } ans2 += Math.min(a, Math.min(b, c)); out.print(Math.max(ans2, ans1)); out.close(); } static ArrayList<Integer> graph[]; static boolean visited[]; private static ArrayList<Integer> DFS(int node, ArrayList<Integer> cc) { cc.add(node); visited[node] = true; for (int child : graph[node]) { if (!visited[child]) { DFS(child, cc); } } return cc; } private static void solve11() throws IOException { int n = r.nextInt(); int m = r.nextInt(); graph = new ArrayList[n + 1]; visited = new boolean[n + 1]; for (int i = 0; i <= n; i++) { graph[i] = new ArrayList<Integer>(); } for (int i = 1; i <= m; i++) { int u = r.nextInt(); int v = r.nextInt(); graph[u].add(v); graph[v].add(u); } ArrayList<ArrayList<Integer>> three = new ArrayList(); ArrayList<ArrayList<Integer>> two = new ArrayList(); ArrayList<ArrayList<Integer>> one = new ArrayList(); StringBuilder res = new StringBuilder(); for (int i = 1; i <= n; i++) { if (!visited[i]) { ArrayList<Integer> cc = DFS(i, new ArrayList<Integer>()); if (cc.size() > 3) { out.print(-1); out.close(); return; } else { if (cc.size() == 3) { three.add(cc); } else if (cc.size() == 2) { two.add(cc); } else { one.add(cc); } } } } for (int i = 0; i < three.size(); i++) { int a = three.get(i).get(0); int b = three.get(i).get(1); int c = three.get(i).get(2); res.append(a).append(" ").append(b).append(" ").append(c).append("\n"); } // System.out.println(one); // System.out.println(two); // System.out.println(three); if (one.size() > 0 || two.size() > 0) { if (two.size() == 0) { if (one.size() % 3 == 0) { for (int i = 0; i < one.size(); i += 3) { int a = one.get(i).get(0); int b = one.get(i + 1).get(0); int c = one.get(i + 2).get(0); res.append(a).append(" ").append(b).append(" ").append(c).append("\n"); } } else { out.print(-1); out.close(); return; } } else if (one.size() == 0) { out.print(-1); out.close(); return; } else if (one.size() > 0 && two.size() > 0) { if (one.size() >= two.size() && ((one.size() - two.size()) % 3) == 0) { for (int i = 0; i < two.size(); i++) { int a = one.get(i).get(0); int b = two.get(i).get(0); int c = two.get(i).get(1); res.append(a).append(" ").append(b).append(" ").append(c).append("\n"); } for (int i = two.size(); i < one.size(); i += 3) { int a = one.get(i).get(0); int b = one.get(i + 1).get(0); int c = one.get(i + 2).get(0); res.append(a).append(" ").append(b).append(" ").append(c).append("\n"); } } else { out.print(-1); out.close(); return; } } } out.print(res); out.close(); } private static void solve12() throws IOException { out.print(0); out.close(); } private static void solve13() throws IOException { out.print(0); out.close(); } public static void main(String[] args) throws IOException { // solve1(); // solve2(); // solve3(); // solve4(); // solve5(); // solve6(); // solve7(); // solve8(); // solve9(); // solve10(); solve11(); // solve12(); // solve13(); } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
d7303869d8c6332aefa56eb8618db2fd
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.Arrays; import java.util.InputMismatchException; import java.util.*; import java.io.*; import java.math.*; public class Main5{ static class Pair { long x; int y; public Pair(long x, int y) { this.x = x; this.y = y; } } static class Compare { static void compare(Pair arr[], int n) { // Comparator to sort the pair according to second element Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if(p1.x>p2.x) { return 1; } else if(p2.x>p1.x) { return -1; } else { if(p1.y>p2.y) { return 1; } else if(p1.y<p2.y) { return -1; } else return 0; } } }); } } public static long pow(long a, long b) { long result=1; while(b>0) { if (b % 2 != 0) { result=(result*a); b--; } a=(a*a); b /= 2; } return result; } public static long fact(long num) { long value=1; int i=0; for(i=2;i<num;i++) { value=((value%mod)*i%mod)%mod; } return value; } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } public static long lcm(int a,int b) { return a * (b / gcd(a, b)); } public static long sum(int h) { return (h*(h+1)/2); } public static void dfs(int parent,boolean[] visited) { ArrayList<Integer> arr=new ArrayList<Integer>(); arr=graph.get(parent); visited[parent]=true; for(int i=0;i<arr.size();i++) { int num=arr.get(i); if(visited[num]==false) { dfs(num,visited); } } ar3.add(parent); count++; } static int count=0; static ArrayList<Integer> ar3; static long mod=1000000007L; static ArrayList<ArrayList<Integer>> graph; public static void bfs(int num,boolean[] visited) { Queue<Integer> q=new LinkedList<>(); q.add(num); visited[num]=true; while(!q.isEmpty()) { int x=q.poll(); ArrayList<Integer> al=graph.get(x); for(int i=0;i<al.size();i++) { int y=al.get(i); if(visited[y]==false) { q.add(y); visited[y]=true; } } } } public static void main(String args[])throws IOException { // InputReader in=new InputReader(System.in); // OutputWriter out=new OutputWriter(System.out); // long a=pow(26,1000000005); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); ArrayList<Integer> ar=new ArrayList<>(); ArrayList<Integer> ar1=new ArrayList<>(); ArrayList<Integer> ar2=new ArrayList<>(); // ArrayList<Integer> ar3=new ArrayList<>(); ArrayList<Integer> ar4=new ArrayList<>(); TreeSet<Integer> ts1=new TreeSet<>(); TreeSet<String> pre=new TreeSet<>(); HashMap<Long,Long> hash=new HashMap<>(); //HashMap<Long,Integer> hash1=new HashMap<Long,Integer>(); HashMap<Long,Integer> hash2=new HashMap<Long,Integer>(); /* boolean[] prime=new boolean[10001]; for(int i=2;i*i<=10000;i++) { if(prime[i]==false) { for(int j=2*i;j<=10000;j+=i) { prime[j]=true; } } }*/ int n=i(); int m=i(); int[] a=new int[m]; int[] b=new int[m]; graph=new ArrayList<>(); for(int i=0;i<=n;i++) { graph.add(new ArrayList<>()); } for(int i=0;i<m;i++) { a[i]=i()-1; b[i]=i()-1; graph.get(a[i]).add(b[i]); graph.get(b[i]).add(a[i]); } boolean[] visited=new boolean[n]; int flag=0; for(int i=0;i<n;i++) { if(visited[i]==false) { ar3=new ArrayList<>(); count=0; dfs(i,visited); if(count>3) { flag=1; break; } if(count==1) { ar.add(ar3.get(0)); } if(count==2) { ar1.add(ar3.get(1)); ar1.add(ar3.get(0)); } else if(count==3) { ar2.add(ar3.get(0)); ar2.add(ar3.get(2)); ar2.add(ar3.get(1)); } } } if(flag==1 || (ar.size()<ar1.size()/2 && ar1.size()>0)) { pln("-1"); } else { // pln(ar1+""); // pln(ar2+""); // pln(ar+""); for(int i=0;i<ar2.size();i+=3) { pln((ar2.get(i)+1)+" "+(ar2.get(i+1)+1)+" "+(ar2.get(i+2)+1)); } int k=0; for(int i=0;i<ar1.size();i+=2) { pln((ar1.get(i)+1)+" "+(ar1.get(i+1)+1)+" "+(ar.get(k)+1)); k++; } for(int i=k;i<ar.size();i+=3) { pln((ar.get(i)+1)+" "+(ar.get(i+1)+1)+" "+(ar.get(i+2)+1)); } } } /**/ static InputReader in=new InputReader(System.in); static OutputWriter out=new OutputWriter(System.out); public static long l() { String s=in.String(); return Long.parseLong(s); } public static void pln(String value) { System.out.println(value); } public static int i() { return in.Int(); } public static String s() { return in.String(); } } 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 Int() { 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 String() { 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 String(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.Int(); return array; } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
147533e4bee8292844367fc745cb98bd
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static 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 double d() throws IOException {return Double.parseDouble(s()) ;} 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; } } /////////////////////////////////////////////////////////////////////////////////////////// // RRRRRRRRR AAA HHH HHH IIIIIIIIIIIII LLL // // RR RRR AAAAA HHH HHH IIIIIIIIIII LLL // // RR RRR AAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHHHHHHHHHH III LLL // // RRRRRR AAA AAA HHHHHHHHHHH III LLL // // RR RRR AAAAAAAAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIII LLLLLLLLLLLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIIIII LLLLLLLLLLLL // /////////////////////////////////////////////////////////////////////////////////////////// static int n; static int m; static int arr[]; static int mark[]; static int ans=0; static LinkedList<Integer> adj[]; static ArrayList<Integer> al=new ArrayList<Integer>(); public static void dfs(int pos) { if(mark[pos]==1) return ; ans++; mark[pos]=1; for(int i:adj[pos]) dfs(i); } public static void dfs1(int pos) { if(mark[pos]==1) return ; mark[pos]=1; al.add(pos); for(int i:adj[pos]) dfs1(i); } public static void main(String[] args)throws IOException { PrintWriter out= new PrintWriter(System.out); Reader sc=new Reader(); n=sc.i(); int m=sc.i(); adj = new LinkedList[n]; int store[]=new int[n]; int counter=0; int counter1=0; mark=new int[n]; int special[]=new int[n]; for (int i=0; i<n; ++i) adj[i] = new LinkedList(); while(m-->0) { int a=sc.i()-1;int b=sc.i()-1; adj[a].add(b); adj[b].add(a); } for(int i=0;i<n;i++) { if(mark[i]==0) { dfs(i); if(ans>3) { System.out.println("-1"); System.exit(0); } special[i]=ans; if(ans==1) store[counter++]=i+1; ans=0; } } StringBuilder s=new StringBuilder(""); Arrays.fill(mark,0); for(int i=0;i<n;i++) { if(special[i]==3) { dfs1(i); for(int j:al) s=s.append((j+1)+" "); s=s.append("\n"); al.clear(); ans=0; } if(special[i]==2) { int val=adj[i].get(0); s=s.append((i+1)+" "+(val+1)+" "); if(counter==counter1) { System.out.println(-1); System.exit(0); } s=s.append(store[counter1++]+"\n"); } } if((counter-counter1)%3!=0) { System.out.println(-1); System.exit(0); } for(int i=counter1;i<counter;i+=3) { s=s.append(store[i]+" "+store[i+1]+" "+store[i+2]+"\n"); } out.println(s); out.flush(); } }
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
544d4b278d155cda842aedb94c159edc
train_003.jsonl
1366903800
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.
256 megabytes
import java.util.*; public class Coach { public static void main (String [] args) { Scanner input = new Scanner (System.in); int n = input.nextInt(); int m = input.nextInt(); Map<Integer, List<Integer>> adjList = new HashMap<Integer, List<Integer>>(); int[] array = new int[m*2]; for (int i = 1; i <= n; i++) { adjList.put(i, new ArrayList<Integer>()); } for (int i = 0; i < m; i++) { int a = input.nextInt(); List<Integer> a_children = adjList.get(a); int b = input.nextInt(); a_children.add(b); adjList.put(a, a_children); List<Integer> b_children = adjList.get(b); b_children.add(a); adjList.put(b, b_children); } Set<Set<Integer>> threes = new HashSet<Set<Integer>>(); Set<Set<Integer>> hashTwos = new HashSet<Set<Integer>>(); List<Set<Integer>> twos = new ArrayList<Set<Integer>>(); Set<Integer> hashOnes = new HashSet<Integer>(); List<Integer> ones = new ArrayList<Integer>(); for (int key : adjList.keySet()) { Set<Integer> visited = new HashSet<Integer>(); dfs(visited, adjList, key); if (visited.size() > 3) { //System.out.println("visited size > 3"); System.out.println(-1); return; } if (visited.size() == 3) { threes.add(visited); } else if (visited.size() == 2) { if (!hashTwos.contains(visited)) { hashTwos.add(visited); twos.add(visited); } } else if (visited.size() == 1) { for (int i : visited) { if (!hashOnes.contains(i)) { hashOnes.add(i); ones.add(i); } } } } // rearrange if (twos.size() > ones.size()) { //System.out.println("twos size > ones size"); //System.out.println(twos.size() + " > " + ones.size()); System.out.println(-1); return; } int i = 0; while (i < twos.size()) { Set<Integer> newThree = new HashSet<Integer>(); Set<Integer> set = twos.get(i); for (int num : set) { newThree.add(num); } newThree.add(ones.get(i)); threes.add(newThree); i++; } if (i < ones.size() && (ones.size() - i) % 3 != 0) { //System.out.println("# of ones not divisible by 3"); // System.out.println("i = " + i + ", sizeofOnes = " + ones.size()); System.out.println(-1); return; } while (i + 2 < ones.size() && (ones.size() - i) % 3 == 0) { Set<Integer> newThree = new HashSet<Integer>(); // System.out.println("adding i = "+ i + ", " + ones.get(i)); newThree.add(ones.get(i)); // System.out.println("adding " + ones.get(i+1)); newThree.add(ones.get(i+1)); // System.out.println("adding " + ones.get(i+2)); newThree.add(ones.get(i+2)); threes.add(newThree); i+=3; // System.out.println("Now i = " + i); } printOutput(threes); } public static void printOutput (Set<Set<Integer>> threes) { for (Set<Integer> set : threes) { List<Integer> fuck = new ArrayList<Integer>(); for (int n : set) { fuck.add(n); } Collections.sort(fuck); for (int i = fuck.size() - 1; i >= 0; i--) { System.out.print(fuck.get(i) + " "); } System.out.println(); } } public static void dfs (Set<Integer> visited, Map<Integer, List<Integer>> adjList, int n) { if (visited.contains(n)) return; visited.add(n); List<Integer> connections = adjList.get(n); for (int i : connections) { dfs(visited, adjList, i); } } } /* public static List<List<Integer>> rearrange (List<List<Integer>> twos, List<Integer> ones) { assert (twos != null && ones != null); List<List<Integer>> newThrees = new ArrayList<List<Integer>>(); int i = 0; while (i < twos.size()) { List<Integer> newThree = new ArrayList<Integer>(); if (ones.get(i) != null) { newThree.add(twos.get(i).get(0)); newThree.add(twos.get(i).get(1)); newThree.add(ones.get(i)); } newThrees.add(newThree); i++; } if (ones.size() > i && (ones.size() - i - 1) % 3 != 0) { System.out.println(-1); return null; } while (ones.size() > i && (ones.size() - i - 1) % 3 == 0) { List<Integer> newThree = new ArrayList<Integer>(); newThree.add(ones.get(i)); newThree.add(ones.get(i+1)); newThree.add(ones.get(i+2)); newThrees.add(newThree); i+=2; } return newThrees; }*/
Java
["3 0", "6 4\n1 2\n2 3\n3 4\n5 6", "3 3\n1 2\n2 3\n1 3"]
2 seconds
["3 2 1", "-1", "3 2 1"]
null
Java 8
standard input
[ "dfs and similar", "brute force", "graphs" ]
46e7cd6723553d2c6d6c6d0999a5b5fc
The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai &lt; bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.
1,500
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team. If there are multiple answers, you are allowed to print any of them.
standard output
PASSED
0a1cdecfdb73dfe7831f7e58b9a56733
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.*; public class Solution { private static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int n = sc.nextInt(), k = sc.nextInt(); int res = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { int f = sc.nextInt(), t = sc.nextInt(); if (t <= k) { res = Math.max(res, f); } else { res = Math.max(res, f - (t - k)); } } System.out.println(res); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
c50c220d427f933bb4756ab00f33795c
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.ArrayList; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); ArrayList<Integer> main = new ArrayList<>(); int a = Integer.valueOf(scan.nextInt()); int b = Integer.valueOf(scan.nextInt()); for (int i = 0; i <a; i++) { int c = Integer.valueOf(scan.nextInt()); int d = Integer.valueOf(scan.nextInt()); if (d > b) { main.add(c - (d - b)); } else { main.add(c); } } System.out.println(Collections.max(main)); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
9a44205c78791d00405531c8ceb86529
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.*; public class Main { private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int n = scanner.nextInt(), k = scanner.nextInt(); int[] fmax = new int[n]; int a = 0; for (int i = 0; i < n; i++) { int f = scanner.nextInt(), t = scanner.nextInt(); if (t > k) { fmax[a] = f - (t - k); } else { fmax[a] = f; } a++; } int r = fmax[0]; for (int value : fmax) { if (r < value) { r = value; } } System.out.println(r); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
346138dd9c626986284e64b4dbecf3e1
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.Scanner; public class mainClass { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); int n , k, max=0, f ,t; n=input.nextInt(); k=input.nextInt(); for(int i =0 ; i<n ; i++) { f=input.nextInt(); t=input.nextInt(); if(i==0&&t<=k) max=f; else if(i==0) max=f-(t-k); if(f>max) { if(t>k && max<(f-(t-k))) max=f-(t-k); else if(t<=k) max=f; } } System.out.println(max); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
ea029cff69654e2ffe659893659a06a1
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.io.*; import java.util.*; /* * To execute Java, please define "static void main" on a class * named Solution. * * If you need more classes, simply define them inline. */ public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int maxAllowedTime = sc.nextInt(); int maxJoy = Integer.MIN_VALUE; for(int i=0;i<n;i++){ int currentJoy = sc.nextInt(); int currentTime = sc.nextInt(); if(currentTime > maxAllowedTime) currentJoy = currentJoy - (currentTime-maxAllowedTime); maxJoy = Math.max(maxJoy,currentJoy); } System.out.println(maxJoy); } } /* Your previous Plain Text content is preserved below: Idea for each place calculate joy factor calculate max joy factor 4 6 5 8 3 6 2 3 2 2 */
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
618bb60ec709b8bb111c17109a840984
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.*; public class CD276A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int max = Integer.MIN_VALUE ; for(int i = 0 ; i < n ; i++) { int fi = sc.nextInt(), ti = sc.nextInt(); if(ti > k) max = Math.max(max, fi -ti + k); else max = Math.max(max, fi); } System.out.println(max); sc.close(); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
2c16f6428a5e0230f7a7307fcea4ea07
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.*; public class dreamonandstairs { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int k=s.nextInt(); int max=Integer.MIN_VALUE,max1=Integer.MIN_VALUE,max2=Integer.MIN_VALUE; for(int i=0;i<n;i++) { int f=s.nextInt(); int t=s.nextInt(); if(t<=k) { max1=f; max=Integer.max(max, max1); } else { max2=f-t+k; max=Integer.max(max, max2); } max1=0; max2=0; } System.out.println(max); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
7766b621053016d7d048a405fa39796b
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.*; public class solution { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); int[][] a= new int[n][2]; for(int i=0;i<n;i++) { a[i][0]=sc.nextInt(); a[i][1]=sc.nextInt(); } int max=Integer.MIN_VALUE; for(int i=0;i<n;i++) { if(a[i][1]<=k) { if(max<a[i][0]) { max=a[i][0]; } } else { if(max<a[i][0]-(a[i][1]-k)) { max=a[i][0]-(a[i][1]-k); } } } System.out.print(max); sc.close(); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
ac431a60d734a2d413257220fb6aa1e4
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt() ; int k = sc.nextInt() ; int max = Integer.MIN_VALUE ; int Fi = 0 ; int Ti = 0 ; for (int i = 0 ; i<n ; i++){ Fi = sc.nextInt() ; Ti = sc.nextInt() ; int curr = Fi ; if (Ti>k) curr -= (Ti- k) ; max = Math.max(max , curr) ; } System.out.print( max); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
dacbab1eae2ce295784f065d1d9d98f1
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.lang.reflect.Array; import java.util.* ; public class solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt() ; int k = sc.nextInt() ; int joy = 0 ; int max = Integer.MIN_VALUE ; for (int i = 0 ; i<n ; i++){ int f = sc.nextInt() ; int t = sc.nextInt() ; if (t > k) joy = f - (t - k); else joy = f ; if (joy > max) max = joy ; } System.out.print(max); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
28db909eb247ce24021b69a0112ac139
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.Scanner; public class Lunch_Rush { public static void main(String args[]) { Scanner reader = new Scanner(System.in); int n = reader.nextInt(); int k = reader.nextInt(); int maxJoy = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { int f = reader.nextInt(); int t = reader.nextInt(); if (t > k) f -= t - k; if (f > maxJoy) maxJoy = f; } reader.close(); System.out.print(maxJoy); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
5e6485667374936076f3810ea9972084
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.*; import java.lang.*; public class LunchRush{ public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int[] joy = new int[n]; for(int i = 0 ; i < n ; i++) { int fi = in.nextInt(); int ti = in.nextInt(); if(ti <= k) joy[i] = fi; else joy[i] = fi -(ti - k); } int max = joy[0]; for(int i = 1 ; i < n ; i++){ if(max < joy[i]) max = joy[i]; } System.out.println(max); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
8b9ca0dcb632a8d266363eb0b9c6e348
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.*; public class Pair { public static void main(String[] args) throws Exception { try { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long k = sc.nextLong(); long value=Integer.MIN_VALUE; while(n!=0){ long a = sc.nextLong(); long b = sc.nextLong(); long ans = b>k?a-(b-k):a; if(ans>value){ value = ans; } --n; } System.out.println(value); } catch (Exception e) { } } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
0dda74bce0b26c83ced742d9df0faa46
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; private FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair<U, V> { private final U first; // first field of a Pair private final V second; // second field of a Pair // Constructs a new Pair with specified values private Pair(U first, V second) { this.first = first; this.second = second; } @Override // Checks specified object is "equal to" current object or not public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; // call equals() method of the underlying objects if (!first.equals(pair.first)) return false; return second.equals(pair.second); } @Override // Computes hash code for an object to support hash tables public int hashCode() { // use hash codes of the underlying objects return 31 * first.hashCode() + second.hashCode(); } @Override public String toString() { return "(" + first + ", " + second + ")"; } // Factory method for creating a Typed Pair immutable instance public static <U, V> Pair <U, V> of(U a, V b) { // calls private constructor return new Pair<>(a, b); } } public static void main(String[] args) throws IOException { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int n=in.nextInt(); int k=in.nextInt(); int ans=Integer.MIN_VALUE; for(int i=0; i<n;i++){ int f=in.nextInt(); int t=in.nextInt(); int temp=0; if(t>k){ temp= f-(t-k); } else{ temp= f; } ans= Math.max(ans,temp); } out.println(ans); out.flush(); out.close(); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
8686451b210f0f5f488015297da5de39
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.Scanner; public class LunchRush { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int k= scan.nextInt(); int arr[]=new int[n]; int f,t,max; for(int i=0;i<n;i++) { f=scan.nextInt(); t=scan.nextInt(); if(k>=t) { arr[i]=f; } else { arr[i]=f-(t-k); } } max=arr[0]; for(int i=1;i<n;i++) { if(arr[i]>max) { max=arr[i]; } } System.out.println(max); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
7a5a85354388fca1b6c6b9137a7d9bfd
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class LunchRush { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int resturents = scanner.nextInt(); int timeLimit = scanner.nextInt(); int[] values = new int[resturents]; for (int i = 0; i < resturents; i++) { int f = scanner.nextInt(); int k = scanner.nextInt(); if (k > timeLimit) values[i] = f - (k - timeLimit); else values[i] = f; } Arrays.sort(values); System.out.println(values[resturents-1]); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
ca77983bba84145bbebe0860bb114cc0
train_003.jsonl
1361719800
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int k = scanner.nextInt(); ArrayList<Integer>good = new ArrayList<>(); ArrayList<Integer>bad = new ArrayList<>(); for(int i = 0; i<n;i++){ int f = scanner.nextInt(); int t = scanner.nextInt(); if(k>=t){ good.add(f); }else{ good.add(f-(t-k)); } } System.out.println(Collections.max(good)); } }
Java
["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"]
2 seconds
["4", "3", "-1"]
null
Java 11
standard input
[ "implementation" ]
1bb5b64657e16fb518d49d3c799d4823
The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.
900
In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.
standard output
PASSED
e73b1e65235134a1077da68cab737776
train_003.jsonl
1557671700
Vasya has written some permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, so for all $$$1 \leq i \leq n$$$ it is true that $$$1 \leq p_i \leq n$$$ and all $$$p_1, p_2, \ldots, p_n$$$ are different. After that he wrote $$$n$$$ numbers $$$next_1, next_2, \ldots, next_n$$$. The number $$$next_i$$$ is equal to the minimal index $$$i &lt; j \leq n$$$, such that $$$p_j &gt; p_i$$$. If there is no such $$$j$$$ let's let's define as $$$next_i = n + 1$$$.In the evening Vasya went home from school and due to rain, his notebook got wet. Now it is impossible to read some written numbers. Permutation and some values $$$next_i$$$ are completely lost! If for some $$$i$$$ the value $$$next_i$$$ is lost, let's say that $$$next_i = -1$$$.You are given numbers $$$next_1, next_2, \ldots, next_n$$$ (maybe some of them are equal to $$$-1$$$). Help Vasya to find such permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, that he can write it to the notebook and all numbers $$$next_i$$$, which are not equal to $$$-1$$$, will be correct.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static LinkedList<Integer>[]children; static int[]ans; static int timer; static void dfs(int i) { ans[i]=timer--; while(!children[i].isEmpty()) { dfs(children[i].pollFirst()); } } static void main() throws Exception{ int n=sc.nextInt(); int[]next=new int[n]; children=new LinkedList[n+1]; for(int i=0;i<=n;i++) { children[i]=new LinkedList<>(); } for(int i=0;i<n;i++) { next[i]=sc.nextInt()-1; if(next[i]==-2) { next[i]=i+1; } } for(int i=0;i<n;i++) { children[next[i]].addLast(i); } ans=new int[n+1]; timer=n; dfs(n); Stack<Integer>stack=new Stack<>(); stack.add(n-1); for(int i=n-2;i>=0;i--) { while(!stack.isEmpty() && ans[i]>ans[stack.peek()]) { stack.pop(); } int nxt; if(stack.isEmpty()) { nxt=n; } else { nxt=stack.peek(); } if(nxt!=next[i]) { pw.println(-1); return; } stack.add(i); } for(int i=0;i<n;i++) { pw.print(ans[i]+1+" "); } pw.println(); } public static void main(String[] args) throws Exception{ pw=new PrintWriter(System.out); sc = new MScanner(System.in); int tc=sc.nextInt(); while(tc-->0) main(); pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } }
Java
["6\n3\n2 3 4\n2\n3 3\n3\n-1 -1 -1\n3\n3 4 -1\n1\n2\n4\n4 -1 4 5"]
1 second
["1 2 3\n2 1\n2 1 3\n-1\n1\n3 2 1 4"]
NoteIn the first test case for permutation $$$p = [1, 2, 3]$$$ Vasya should write $$$next = [2, 3, 4]$$$, because each number in permutation is less than next. It's easy to see, that it is the only satisfying permutation.In the third test case, any permutation can be the answer because all numbers $$$next_i$$$ are lost.In the fourth test case, there is no satisfying permutation, so the answer is $$$-1$$$.
Java 11
standard input
[ "greedy", "graphs", "constructive algorithms", "math", "sortings", "data structures", "dfs and similar" ]
667c5af27db369257039d0832258600d
The first line contains one integer $$$t$$$ — the number of test cases ($$$1 \leq t \leq 100\,000$$$). Next $$$2 \cdot t$$$ lines contains the description of test cases,two lines for each. The first line contains one integer $$$n$$$ — the length of the permutation, written by Vasya ($$$1 \leq n \leq 500\,000$$$). The second line contains $$$n$$$ integers $$$next_1, next_2, \ldots, next_n$$$, separated by spaces ($$$next_i = -1$$$ or $$$i &lt; next_i \leq n + 1$$$). It is guaranteed, that the sum of $$$n$$$ in all test cases doesn't exceed $$$500\,000$$$. In hacks you can only use one test case, so $$$T = 1$$$.
2,100
Print $$$T$$$ lines, in $$$i$$$-th of them answer to the $$$i$$$-th test case. If there is no such permutations $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, that Vasya could write, print the only number $$$-1$$$. In the other case print $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$, separated by spaces ($$$1 \leq p_i \leq n$$$). All defined values of $$$next_i$$$ which are not equal to $$$-1$$$ should be computed correctly $$$p_1, p_2, \ldots, p_n$$$ using defenition given in the statement of the problem. If there exists more than one solution you can find any of them.
standard output
PASSED
3cf12a54fde9775f1896062a1795e42a
train_003.jsonl
1481726100
Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took n prizes for the contestants and wrote on each of them a unique id (integer from 1 to n). A gift i is characterized by integer ai — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with n vertices.The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Random; import java.util.StringTokenizer; public class Solution{ static final long inf = (long)1e17; static int[] a; static long[] d; static ArrayList<Integer>[] adjlist; static long ans = -inf; public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int tt = 1; while(tt-->0) { int n = fs.nextInt(); a = fs.readArray(n); d = new long[n]; adjlist = new ArrayList[n]; for(int i=0;i<n;i++) { adjlist[i] = new ArrayList<Integer>(); } for(int i=0;i<n-1;i++) { int u = fs.nextInt()-1, v = fs.nextInt()-1; adjlist[u].add(v); adjlist[v].add(u); } dfs(0, -1); if(ans==-inf) out.println("Impossible"); else out.println(ans); } out.close(); } static long dfs(int v, int p) { d[v] = a[v]; long max = -inf; for(int u: adjlist[v]) { if(u!=p) { long k = dfs(u, v); d[v] += d[u]; if(max!=-inf) ans = Math.max(ans, max+k); max = Math.max(max, k); } } return Math.max(d[v], max); } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); int temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().toCharArray()[0]; } } }
Java
["8\n0 5 -1 4 3 2 6 5\n1 2\n2 4\n2 5\n1 3\n3 6\n6 7\n6 8", "4\n1 -5 1 1\n1 2\n1 4\n2 3", "1\n-1"]
2 seconds
["25", "2", "Impossible"]
null
Java 11
standard input
[ "dp", "dfs and similar", "trees", "graphs" ]
14b65af01caf1f3971a2f671589b86a8
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of gifts. The next line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the pleasantness of the gifts. The next (n - 1) lines contain two numbers each. The i-th of these lines contains integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the description of the tree's edges. It means that gifts with numbers ui and vi are connected to each other with a rope. The gifts' ids in the description of the ropes can be given in arbirtary order: vi hangs on ui or ui hangs on vi. It is guaranteed that all the gifts hang on the first gift, possibly with a sequence of ropes and another gifts.
1,800
If it is possible for Chloe and Vladik to choose prizes without fighting, print single integer — the maximum possible sum of pleasantness they can get together. Otherwise print Impossible.
standard output
PASSED
463f9b579113cc2b83e1133bd9bab237
train_003.jsonl
1481726100
Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took n prizes for the contestants and wrote on each of them a unique id (integer from 1 to n). A gift i is characterized by integer ai — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with n vertices.The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.
256 megabytes
//package com.company; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) throws IOException { // write your code here // Scanner s = new Scanner(System.in); BufferedReader s=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); String[] str=s.readLine().trim().split("\\s+"); int n=Integer.parseInt(str[0]); a=new Long[n+1]; String[] str1=s.readLine().trim().split("\\s+");ArrayList<Integer> [] adj=new ArrayList[n+1]; for(int i=1;i<=n;i++){ a[i]=Long.parseLong(str1[i-1]); }for(int i=0;i<n-1;i++){ String[] str2=s.readLine().trim().split("\\s+"); Integer x=Integer.parseInt(str2[0]);Integer y=Integer.parseInt(str2[1]); if(adj[(int)x]==null) adj[(int)x]=new ArrayList<Integer>(); if(adj[(int)y]==null) adj[(int)y]=new ArrayList<Integer>(); adj[(int)x].add(y); adj[(int)y].add(x); }sum=new Long[n+1]; for(int i=1;i<n+1;i++) sum[i]=0L; dfs(1,adj,new int[n+1]); // dfs1(1,adj,new int[n+1]); dfs2(1,adj,new int[n+1]); if(fans!=Long.MIN_VALUE) System.out.println(fans); else System.out.println("Impossible"); } 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; } static int m; static int n; static int path = Integer.MAX_VALUE; static int got = 0; static Long[] sum;static Long[] a; public static long dfs(int i, ArrayList<Integer>[] h, int[] vis) { vis[i] = 1; sum[i]+=a[i];if(h[i]==null) return sum[i]; for (Integer j : h[i]) { if (vis[j] == 0) { sum[i]+=dfs(j, h, vis); } }return sum[i]; }static long max=Long.MIN_VALUE;static long max1=Long.MIN_VALUE; public static void dfs1(int i, ArrayList<Integer>[] h, int[] vis) { vis[i] = 1;//sum[i]+=a[i]; if(h[i]==null) return ; for (Integer j : h[i]) { if (vis[ j] == 0) { if(sum[j]>max) {max1=max;max=sum[j];} else if(sum[j]>max1) max1=sum[j]; dfs1(j, h, vis); } }return ; }static long fans=Long.MIN_VALUE; public static long dfs2(int i, ArrayList<Integer>[] h, int[] vis) { long max2=Long.MIN_VALUE;long max3=Long.MIN_VALUE; vis[i] = 1;if(h[i]==null) return a[i]; for (Integer j : h[i]) { if (vis[ j] == 0) { long k= dfs2(j, h, vis); if(k>max2) { max3=max2;max2=k;} else if(k>max3) max3=k; } } // System.out.println(i+" "+max2+" "+max3+" "+sum[i]); if(max2!=Long.MIN_VALUE&&max3!=Long.MIN_VALUE&&max2+max3> fans) fans=max2+max3; // if(i==1) return max2; return Math.max(sum[i],max2); } 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+"); } } class Student { int t,l,r; // String name, address; // Constructor public Student(int t,int r) {this.t=t; this.r=r; } // Used to print student details in main() public String toString() { return this.t + " " +this.l+" "+this.r; } } class Sortbyroll implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student a, Student b) { return a.t-b.t; } }
Java
["8\n0 5 -1 4 3 2 6 5\n1 2\n2 4\n2 5\n1 3\n3 6\n6 7\n6 8", "4\n1 -5 1 1\n1 2\n1 4\n2 3", "1\n-1"]
2 seconds
["25", "2", "Impossible"]
null
Java 11
standard input
[ "dp", "dfs and similar", "trees", "graphs" ]
14b65af01caf1f3971a2f671589b86a8
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of gifts. The next line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the pleasantness of the gifts. The next (n - 1) lines contain two numbers each. The i-th of these lines contains integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the description of the tree's edges. It means that gifts with numbers ui and vi are connected to each other with a rope. The gifts' ids in the description of the ropes can be given in arbirtary order: vi hangs on ui or ui hangs on vi. It is guaranteed that all the gifts hang on the first gift, possibly with a sequence of ropes and another gifts.
1,800
If it is possible for Chloe and Vladik to choose prizes without fighting, print single integer — the maximum possible sum of pleasantness they can get together. Otherwise print Impossible.
standard output
PASSED
2dc7e07c0e132e778267859327673549
train_003.jsonl
1481726100
Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took n prizes for the contestants and wrote on each of them a unique id (integer from 1 to n). A gift i is characterized by integer ai — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with n vertices.The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; //import java.util.stream.Collectors; public final class ProblemD { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static Reader sc = new Reader(); // public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // public static Scanner sc = new Scanner(System.in); public static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); // public static OutputStream out2 = new BufferedOutputStream (System.out); public static int n, m, i, j, k, u, v; public static long inf = -(long)1e16; public static ArrayList<Integer>[] graph = new ArrayList[200001]; public static long[][] dp = new long[200001][2]; public static long[] arr = new long[200001]; public static long answer = inf; public static void main(String[] args) throws IOException { n = sc.nextInt(); for(i = 0; i < n; i++) { arr[i] = sc.nextInt(); graph[i] = new ArrayList<>(); } for(i = 0; i < n-1; i++) { u = sc.nextInt(); v = sc.nextInt(); u--; v--; graph[u].add(v); graph[v].add(u); } dfs(0, -1); dfs2(0, -1, inf); if(answer == inf) { out.write("Impossible"); out.flush(); return; } out.write(answer+""); out.flush(); } public static void dfs(int source, int parent) { dp[source][0] = arr[source]; dp[source][1] = inf; for(int child: graph[source]) { if(child != parent) { dfs(child, source); dp[source][0] += dp[child][0]; dp[source][1] = Math.max(dp[source][1], dp[child][1]); } } dp[source][1] = Math.max(dp[source][1], dp[source][0]); } public static void dfs2(int source, int parent, long sum) { if(sum != inf) answer = Math.max(answer, dp[source][0] + sum); LinkedList<Pair> l = new LinkedList<>(); for(int child: graph[source]) { if(child != parent) { l.addLast(new Pair(dp[child][1], child)); l.sort(new NewComp()); if(l.size() > 2) l.removeLast(); } } l.addLast(new Pair(inf, -1)); for(int child: graph[source]) { if(child != parent) { long result = l.get(0).ss == child? l.get(1).ff: l.get(0).ff; dfs2(child, source, Math.max(sum, result)); } } } static class Pair { long ff, ss; public Pair(long ff, long ss) { this.ff = ff; this.ss = ss; } } static class NewComp implements Comparator<Pair> { public int compare(Pair a, Pair b) { if(a.ff - b.ff > 0) return -1; if(a.ff == b.ff) return 0; return 1; } } }
Java
["8\n0 5 -1 4 3 2 6 5\n1 2\n2 4\n2 5\n1 3\n3 6\n6 7\n6 8", "4\n1 -5 1 1\n1 2\n1 4\n2 3", "1\n-1"]
2 seconds
["25", "2", "Impossible"]
null
Java 11
standard input
[ "dp", "dfs and similar", "trees", "graphs" ]
14b65af01caf1f3971a2f671589b86a8
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of gifts. The next line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the pleasantness of the gifts. The next (n - 1) lines contain two numbers each. The i-th of these lines contains integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the description of the tree's edges. It means that gifts with numbers ui and vi are connected to each other with a rope. The gifts' ids in the description of the ropes can be given in arbirtary order: vi hangs on ui or ui hangs on vi. It is guaranteed that all the gifts hang on the first gift, possibly with a sequence of ropes and another gifts.
1,800
If it is possible for Chloe and Vladik to choose prizes without fighting, print single integer — the maximum possible sum of pleasantness they can get together. Otherwise print Impossible.
standard output
PASSED
4a9b7aee5eedf1bd2d73d23a8f6e867f
train_003.jsonl
1481726100
Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took n prizes for the contestants and wrote on each of them a unique id (integer from 1 to n). A gift i is characterized by integer ai — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with n vertices.The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.
256 megabytes
import java.io.*; import java.util.*; public class Main { int n,a[]; long maxSub[],maxComp[],subSum[],ans; TreeSet<Long> set; ArrayList<Integer> list[]; final long inf=(long)(1e18+1); private void solve()throws IOException { n=nextInt(); a=new int[n+1]; for(int i=1;i<=n;i++) a[i]=nextInt(); list=new ArrayList[n+1]; for(int i=1;i<=n;i++) list[i]=new ArrayList<>(); for(int i=1;i<n;i++) { int u=nextInt(); int v=nextInt(); list[u].add(v); list[v].add(u); } subSum=new long[n+1]; maxSub=new long[n+1]; maxComp=new long[n+1]; set=new TreeSet<>(); for(int i=1;i<=n;i++) { maxSub[i]=-inf; maxComp[i]=-inf; } ans=-inf; dfs(1,0); dfs2(1,0); if(ans==-inf) out.println("Impossible"); else out.println(ans); } void dfs(int v,int p) { subSum[v]=a[v]; for(int vv:list[v]) if(vv!=p) { dfs(vv,v); maxSub[v]=Math.max(maxSub[v],maxSub[vv]); subSum[v]+=subSum[vv]; } maxSub[v]=Math.max(maxSub[v],subSum[v]); // System.out.println(v+" "+subSum[v]+" "+maxSub[v]); } void dfs2(int v,int p) { if(maxComp[v]!=-inf) ans=Math.max(ans,maxSub[v]+maxComp[v]); long maxTillnow=-inf; // set=new TreeSet<>(); for(int i=0;i<list[v].size();i++) if(list[v].get(i)!=p) { set.add(maxSub[list[v].get(i)]); // System.out.println("add "+maxSub[list[v].get(i)]); } for(int i=0;i<list[v].size();i++) { if(list[v].get(i)==p) continue; // System.out.println("remove"+maxSub[list[v].get(i)]); set.remove(new Long(maxSub[list[v].get(i)])); maxComp[list[v].get(i)]=Math.max(maxComp[v],Math.max(set.isEmpty()?-inf:set.last(),maxTillnow)); maxTillnow=Math.max(maxTillnow,maxSub[list[v].get(i)]); } for(int vv:list[v]) if(vv!=p) dfs2(vv,v); } /////////////////////////////////////////////////////////// public void run()throws IOException { br=new BufferedReader(new InputStreamReader(System.in)); st=null; out=new PrintWriter(System.out); solve(); br.close(); out.close(); } public static void main(String args[])throws IOException{ new Main().run(); } BufferedReader br; StringTokenizer st; PrintWriter out; String nextToken()throws IOException{ while(st==null || !st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine()throws IOException{ return br.readLine(); } int nextInt()throws IOException{ return Integer.parseInt(nextToken()); } long nextLong()throws IOException{ return Long.parseLong(nextToken()); } double nextDouble()throws IOException{ return Double.parseDouble(nextToken()); } }
Java
["8\n0 5 -1 4 3 2 6 5\n1 2\n2 4\n2 5\n1 3\n3 6\n6 7\n6 8", "4\n1 -5 1 1\n1 2\n1 4\n2 3", "1\n-1"]
2 seconds
["25", "2", "Impossible"]
null
Java 11
standard input
[ "dp", "dfs and similar", "trees", "graphs" ]
14b65af01caf1f3971a2f671589b86a8
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of gifts. The next line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the pleasantness of the gifts. The next (n - 1) lines contain two numbers each. The i-th of these lines contains integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the description of the tree's edges. It means that gifts with numbers ui and vi are connected to each other with a rope. The gifts' ids in the description of the ropes can be given in arbirtary order: vi hangs on ui or ui hangs on vi. It is guaranteed that all the gifts hang on the first gift, possibly with a sequence of ropes and another gifts.
1,800
If it is possible for Chloe and Vladik to choose prizes without fighting, print single integer — the maximum possible sum of pleasantness they can get together. Otherwise print Impossible.
standard output
PASSED
4bc14fc38f910cc601550ab4c7f890e9
train_003.jsonl
1481726100
Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took n prizes for the contestants and wrote on each of them a unique id (integer from 1 to n). A gift i is characterized by integer ai — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with n vertices.The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.
256 megabytes
import java.util.*; import java.io.*; public class File { 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 sc = new FastScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); long[] p = new long[n+1]; for (int i = 1; i <= n; i++) { p[i] = sc.nextLong(); } Map<Integer, List<Integer>> graph = new HashMap<>(); for (int i = 0; i < n - 1; i++) { int x = sc.nextInt(); int y = sc.nextInt(); if (!graph.containsKey(x)) { graph.put(x, new ArrayList<>()); } if (!graph.containsKey(y)) { graph.put(y, new ArrayList<>()); } graph.get(x).add(y); graph.get(y).add(x); } // Stores the total sum of nodes for tree rooted at each node. long[] treeSums = new long[n+1]; getSums(1, -1, graph, p, treeSums); // Traverse the tree. // For each node: // Get the max p of the left subtree, if any. If none, do not consider. // Get the max p of the right subtree, if any. If none, do not consider. long[] max = new long[] {Long.MIN_VALUE}; traverse(1, -1, p, graph, treeSums, max); if (max[0] == Long.MIN_VALUE) { out.println("Impossible"); } else { out.println(max[0]); } out.close(); } public static long getSums(int node, int parent, Map<Integer, List<Integer>> graph, long[] p, long[] treeSums) { treeSums[node] += p[node]; for (int child : graph.getOrDefault(node, new ArrayList<>())) { if (child == parent) continue; treeSums[node] += getSums(child, node, graph, p, treeSums); } return treeSums[node]; } public static long traverse(int node, int parent, long[] p, Map<Integer, List<Integer>> graph, long[] treeSums, long[] max) { long max1 = Long.MIN_VALUE; long max2 = Long.MIN_VALUE; for (int child : graph.getOrDefault(node, new ArrayList<>())) { if (child == parent) continue; long maxHere = traverse(child, node, p, graph, treeSums, max); if (max1 == Long.MIN_VALUE) { max1 = maxHere; } else if (max2 == Long.MIN_VALUE) { max2 = maxHere; } else { if (max1 > max2) { max2 = Math.max(max2, maxHere); } else { max1 = Math.max(max1, maxHere); } } } if (max1 != Long.MIN_VALUE && max2 != Long.MIN_VALUE) { max[0] = Math.max(max[0], max1 + max2); } // Return the max of this node's sum, or one of the children's sum. return Math.max(treeSums[node], Math.max(max1, max2)); } }
Java
["8\n0 5 -1 4 3 2 6 5\n1 2\n2 4\n2 5\n1 3\n3 6\n6 7\n6 8", "4\n1 -5 1 1\n1 2\n1 4\n2 3", "1\n-1"]
2 seconds
["25", "2", "Impossible"]
null
Java 11
standard input
[ "dp", "dfs and similar", "trees", "graphs" ]
14b65af01caf1f3971a2f671589b86a8
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of gifts. The next line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the pleasantness of the gifts. The next (n - 1) lines contain two numbers each. The i-th of these lines contains integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the description of the tree's edges. It means that gifts with numbers ui and vi are connected to each other with a rope. The gifts' ids in the description of the ropes can be given in arbirtary order: vi hangs on ui or ui hangs on vi. It is guaranteed that all the gifts hang on the first gift, possibly with a sequence of ropes and another gifts.
1,800
If it is possible for Chloe and Vladik to choose prizes without fighting, print single integer — the maximum possible sum of pleasantness they can get together. Otherwise print Impossible.
standard output
PASSED
9665184966d8a25eb9d82a52c503e772
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
// Imports import java.util.*; import java.io.*; public class G1213 { static int[] parent; static int[] size; static long res; public static int find(int a) { if(parent[a] != a) { parent[a] = find(parent[a]); } return parent[a]; } public static void union(int a, int b) { int x = find(a); int y = find(b); if(x == y) return; if(size[x] < size[y]) { int temp = x; x = y; y = temp; } res -= size[x]*1L*(size[x] - 1)/2; res -= size[y]*1L*(size[y] - 1)/2; parent[y] = x; size[x] += size[y]; res += size[x]*1L*(size[x] - 1)/2; } public static class Pair { public int first; public int second; public Pair(int f, int s) { first = f; second = s; } @Override public String toString() { return "{" + this.first + ", " + this.second + "}"; } } /** * @param args the command line arguments * @throws IOException, FileNotFoundException * @throws java.io.FileNotFoundException */ public static void main(String[] args) throws IOException, FileNotFoundException { // TODO UNCOMMENT WHEN ALGORITHM CORRECT BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); /* BufferedReader f = new BufferedReader(new StringReader("7 5\n" + "1 2 1\n" + "3 2 3\n" + "2 4 1\n" + "4 5 2\n" + "5 7 4\n" + "3 6 2\n" + "5 2 3 4 1")); */ res = 0; // TODO code application logic here StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); parent = new int[n]; size = new int[n]; long[] a = new long[k]; TreeMap<Integer, List<Pair>> insert = new TreeMap<>(); for(int i = 0; i < n - 1; i++) { StringTokenizer edge = new StringTokenizer(f.readLine()); int start = Integer.parseInt(edge.nextToken()) - 1; int end = Integer.parseInt(edge.nextToken()) - 1; int weight = Integer.parseInt(edge.nextToken()); if(insert.containsKey(weight)) { insert.get(weight).add(new Pair(start, end)); } else { ArrayList<Pair> temp = new ArrayList<>(); temp.add(new Pair(start, end)); insert.put(weight, temp); } } for(int j = 0; j < n; j++) { parent[j] = j; size[j] = 1; } int[][] queries = new int[k][2]; StringTokenizer q = new StringTokenizer(f.readLine()); for(int i = 0; i < k; i++) { queries[i][0] = Integer.parseInt(q.nextToken()); queries[i][1] = i; } Arrays.sort(queries, (int[] o1, int[] o2) -> { if(o1[0] > o2[0]) { return 1; } else if(o2[0] > o1[0]) { return -1; } else { return 0; } }); int current = 0; for(int num : insert.keySet()) { while(num > queries[current][0]) { // run the query a[queries[current][1]] = res; current++; if(current == k) { break; } } if(current == k) { break; } insert.get(num).forEach((i) -> { union(i.first, i.second); }); } for(int i = current; i < k; i++) { a[queries[i][1]] = res; } // System.out.println(Arrays.deepToString(queries)); StringBuilder ans = new StringBuilder(); for(int i = 0; i < k; i++) { ans.append(a[i]); ans.append(" "); } System.out.println(ans.substring(0, ans.length() - 1)); } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
0fdbc289910b4b8962bb5cfe2f6137da
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Random; import java.util.StringTokenizer; public class Solution{ static int[] par; static int[] rank; public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int tt = 1; while(tt-->0) { int n = fs.nextInt(); int m = fs.nextInt(); par = new int[n]; for(int i=0;i<n;i++) par[i] = i; rank = new int[n]; Arrays.fill(rank, 1); Edge[] edges = new Edge[n-1]; for(int i=0;i<n-1;i++) { int u = fs.nextInt()-1, v = fs.nextInt()-1, w = fs.nextInt(); edges[i] = new Edge(u, v, w); } int[][] q = new int[m][2]; for(int i=0;i<m;i++) { q[i][0] = fs.nextInt(); q[i][1] = i; } Arrays.sort(edges); Arrays.sort(q, (x,y)-> (x[0]-y[0])); long[] ans = new long[m]; long res = 0; int cur = 0; for(int i=0;i<m;i++) { while(cur<n-1 && edges[cur].cost<=q[i][0]) { int u = edges[cur].u; int v = edges[cur].v; res += (long)rank[find(u)]*rank[find(v)]; union(u, v); cur++; } ans[q[i][1]] = res; } for(int i=0;i<m;i++) out.print(ans[i]+" "); out.println(); } out.close(); } static int find(int v) { if(par[v]==v) return v; return par[v] = find(par[v]); } static void union(int u, int v) { u = find(u); v = find(v); if(u==v ) return; if(rank[v]<rank[u]) {int temp = u; u = v; v = temp;} par[u] = v; rank[v] += rank[u]; } static class Edge implements Comparable<Edge>{ int u; int v; int cost; Edge(int a, int b, int c){ u = a; v = b; cost = c; } @Override public int compareTo(Edge o) { // TODO Auto-generated method stub return Integer.compare(this.cost, o.cost); } } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); int temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().toCharArray()[0]; } } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
fcc0e1cf02a42ab859e635c0a0d61dbc
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); GPathQueries solver = new GPathQueries(); solver.solve(1, in, out); out.close(); } static class GPathQueries { public void solve(int testNumber, Scanner sc, PrintWriter pw) { int n = sc.nextInt(); int q = sc.nextInt(); edge[] arr = new edge[n - 1]; for (int i = 0; i < n - 1; i++) arr[i] = new edge(sc.nextInt(), sc.nextInt(), sc.nextInt()); query[] queries = new query[q]; for (int i = 0; i < q; i++) queries[i] = new query(sc.nextInt(), i); Arrays.sort(arr, (a, b) -> a.weight - b.weight); Arrays.sort(queries, (a, b) -> a.weight - b.weight); UnionFind dsu = new UnionFind(n + 1); long ans = 0; int j = 0; for (int i = 0; i < q; i++) { while (j < arr.length && arr[j].weight <= queries[i].weight) { int temp = dsu.sizeOfSet(arr[j].u); ans -= 1l * temp * (temp - 1) / 2; temp = dsu.sizeOfSet(arr[j].v); ans -= 1l * temp * (temp - 1) / 2; dsu.unionSet(arr[j].u, arr[j].v); temp = dsu.sizeOfSet(arr[j].u); ans += 1l * temp * (temp - 1) / 2; j++; } queries[i].ans = ans; } Arrays.sort(queries, (a, b) -> a.idx - b.idx); for (int i = 0; i < q; i++) { pw.print(queries[i].ans + " "); } } public class UnionFind { int[] p; int[] rank; int[] setSize; int numSets; public UnionFind(int N) { p = new int[numSets = N]; rank = new int[N]; setSize = new int[N]; for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; } } public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); } public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } public void unionSet(int i, int j) { if (isSameSet(i, j)) return; numSets--; int x = findSet(i), y = findSet(j); if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; } } public int sizeOfSet(int i) { return setSize[findSet(i)]; } } public class edge { int u; int v; int weight; public edge(int u, int v, int weight) { this.u = u; this.v = v; this.weight = weight; } public String toString() { return "edge{" + "u=" + u + ", v=" + v + ", weight=" + weight + '}'; } } public class query { int weight; int idx; long ans; public query(int weight, int idx) { this.weight = weight; this.idx = idx; this.ans = -1; } public String toString() { return "query{" + "weight=" + weight + ", idx=" + idx + '}'; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
6e00c13f473526c11107dc012434ef04
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.lang.*; import java.util.*; import java.io.*; public class CF1213C { public static void main(String[] args) throws IOException { Reader.init(System.in); int n = Reader.nextInt(), q = Reader.nextInt(); // read input tree UFDS yeeter = new UFDS(n); Edge[] treeEdges = new Edge[n - 1]; for (int i = 0; i < n - 1; ++i) { int u = Reader.nextInt(), v = Reader.nextInt(), w = Reader.nextInt(); --u; --v; treeEdges[i] = new Edge(u, v, w); } Arrays.sort(treeEdges); TreeMap<Integer, Long> precomp = new TreeMap<Integer, Long>(); // precompute queries for n - 1 edges for (int i = 0; i < n - 1; ++i) { yeeter.join(treeEdges[i].x, treeEdges[i].y); precomp.put(treeEdges[i].w, yeeter.countConnPairs()); } // answer queries for (int qta = 0; qta < q; ++qta) { int w = Reader.nextInt(); Map.Entry<Integer, Long> bestWeight = precomp.floorEntry(w); if (bestWeight == null) { System.out.printf("0"); } else { System.out.printf("%d", bestWeight.getValue()); } if (qta < q - 1) System.out.printf(" "); } System.out.printf("\n"); } }; interface UFDSer { public long countConnPairs(); public int find(int i); public void join(int i, int j); }; class UFDS implements UFDSer { public long connPairs; public long countConnPairs() { return connPairs; } private int[] par; public UFDS(int n) { par = new int[n]; for (int i = 0; i < n; ++i) par[i] = -1; connPairs = 0; } public int find(int i) { if (par[i] < 0) return i; int ans = find(par[i]); par[i] = ans; return ans; } public void join(int i, int j) { i = find(i); j = find(j); if (i == j) return; int head = i, tail = j; if (par[head] > par[tail]) { head = j; tail = i; } connPairs += (long)par[head] * par[tail]; par[head] += par[tail]; par[tail] = head; } }; class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } } class Edge implements Comparable<Edge> { public int x; public int y; public int w; public Edge(int x, int y, int w) { this.x = x; this.y = y; this.w = w; } public int compareTo(Edge other) { if (w != other.w) return w < other.w ? -1 : 1; else return 0; } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
73fe643d6b67e66ee6b484bd42c9f1f0
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1, in, out); out.close(); } static class Task { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); Edge[] edges = new Edge[n - 1]; for (int i = 0; i < n - 1; i++) { edges[i] = new Edge(); edges[i].u = in.nextInt(); edges[i].v = in.nextInt(); edges[i].w = in.nextInt(); } Query[] queries = new Query[m]; for (int i = 0; i < m; i++) { queries[i] = new Query(); queries[i].ind = i; queries[i].w = in.nextInt(); } Arrays.sort(edges, Comparator.comparingInt((Edge f) -> f.w)); Arrays.sort(queries, Comparator.comparingInt((Query f) -> f.w)); long wQty = 0; DSU s = new DSU(n + 1); for (int i = 0, edgeInd = 0; i < m; i++) { while (edgeInd < edges.length && edges[edgeInd].w <= queries[i].w) { wQty += s.getSize(edges[edgeInd].v) * s.getSize(edges[edgeInd].u); s.union(edges[edgeInd].v, edges[edgeInd].u); edgeInd++; } queries[i].ans = wQty; } Arrays.sort(queries, Comparator.comparingInt((Query f) -> f.ind)); for (Query cur : queries) { out.print(cur.ans); out.print(' '); } } } static class DSU { private int[] parent; private int[] size; DSU(int n) { parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } int find(int n) { if (parent[n] == n) return n; return parent[n] = find(parent[n]); } void union(int a, int b) { a = find(a); b = find(b); if (a != b) { parent[a] = b; size[b] += size[a]; } } long getSize(int a) { return size[find(a)]; } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class Edge { int u; int v; int w; } static class Query { int ind; int w; long ans; } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
58343ea8b989d8503ac511c1c7b20002
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1213g { static BufferedReader __in; static PrintWriter __out; static StringTokenizer input; static int par[], sz[]; static long num = 0; static int find(int i) { return i == par[i] ? i : (par[i] = find(par[i])); } static void union(int i, int j) { int a = find(i), b = find(j); if(a != b) { if(sz[b] > sz[a]) { int swap = a; a = b; b = swap; } par[b] = a; num -= (long)sz[a] * (sz[a] - 1) / 2; num -= (long)sz[b] * (sz[b] - 1) / 2; sz[a] += sz[b]; num += (long)sz[a] * (sz[a] - 1) / 2; } } public static void main(String[] args) throws IOException { __in = new BufferedReader(new InputStreamReader(System.in)); __out = new PrintWriter(new OutputStreamWriter(System.out)); int n = rni(), m = ni(); List<int[]> e = new ArrayList<>(); for(int i = 0; i < n - 1; ++i) { e.add(new int[]{rni() - 1, ni() - 1, ni()}); } Collections.sort(e, (a, b) -> a[2] - b[2]); List<int[]> q = new ArrayList<>(); r(); for(int i = 0; i < m; ++i) { q.add(new int[]{ni(), i}); } Collections.sort(q, (a, b) -> a[0] - b[0]); par = new int[n]; sz = new int[n]; for(int i = 0; i < n; ++i) { par[i] = i; sz[i] = 1; } long[] ans = new long[m]; long last = 0; int ind = 0; for(int i = 0; i < m; ++i) { while(ind < n - 1 && e.get(ind)[2] <= q.get(i)[0]) { union(e.get(ind)[0], e.get(ind++)[1]); } /* for(int j = 0; j < n; ++j) { if(j == find(j)) { num += sz[j] * (sz[j] - 1) / 2; } } */ ans[q.get(i)[1]] = num; } prln(ans); close(); } // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); __out.println(iter.next());} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
8c544b0b6a5e1f9242bfb4e9581e87b6
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.InputMismatchException; import java.io.BufferedOutputStream; import java.util.StringTokenizer; import java.io.Flushable; import java.io.OutputStream; import java.io.PrintStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Closeable; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); Output out = new Output(outputStream); GPathQueries solver = new GPathQueries(); solver.solve(1, in, out); out.close(); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29); thread.start(); thread.join(); } static class GPathQueries { public GPathQueries() { } public long choose(int x) { if(x==1) { return 0; } return (long) x*(x-1) >> 1L; } public void solve(int kase, Input in, Output pw) { int n = in.nextInt(), m = in.nextInt(); int[][] edges = new int[n-1][3]; for(int i = 0; i<n-1; i++) { edges[i] = new int[] {in.nextInt()-1, in.nextInt()-1, in.nextInt()}; } int[][] queries = new int[m][2]; for(int i = 0; i<m; i++) { queries[i] = new int[] {i, in.nextInt()}; } Arrays.sort(edges, Comparator.comparingInt(o -> o[2])); Arrays.sort(queries, Comparator.comparingInt(o -> o[1])); DSU dsu = new DSU(n); int j = 0; long ans = 0; long[] arr = new long[m]; Utilities.Debug.dbg("queries", queries, "edges", edges); for(int i = 0; i<m; i++) { int cur = queries[i][1]; for(; j<n-1&&edges[j][2]<=cur; j++) { int u = edges[j][0], v = edges[j][1]; if(!dsu.connected(u, v)) { int us = dsu.size(u), vs = dsu.size(v); ans += choose(us+vs)-choose(us)-choose(vs); dsu.union(u, v); } } arr[queries[i][0]] = ans; } pw.println(arr); } } static class Input { BufferedReader br; StringTokenizer st; public Input(InputStream is) { this(is, 1<<20); } public Input(InputStream is, int bs) { br = new BufferedReader(new InputStreamReader(is), bs); st = null; } public boolean hasNext() { try { while(st==null||!st.hasMoreTokens()) { String s = br.readLine(); if(s==null) { return false; } st = new StringTokenizer(s); } return true; }catch(Exception e) { return false; } } public String next() { if(!hasNext()) { throw new InputMismatchException(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class Utilities { public static class Debug { public static final boolean LOCAL = /*System.getProperty("LOCAL")!=null*/false; private static <T> String ts(T t) { if(t==null) { return "null"; } try { return ts((Iterable) t); }catch(ClassCastException e) { if(t instanceof int[]) { String s = Arrays.toString((int[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof long[]) { String s = Arrays.toString((long[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof char[]) { String s = Arrays.toString((char[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof double[]) { String s = Arrays.toString((double[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof boolean[]) { String s = Arrays.toString((boolean[]) t); return "{"+s.substring(1, s.length()-1)+"}"; } try { return ts((Object[]) t); }catch(ClassCastException e1) { return t.toString(); } } } private static <T> String ts(T[] arr) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: arr) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } private static <T> String ts(Iterable<T> iter) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: iter) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } public static void dbg(Object... o) { if(LOCAL) { System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": ["); for(int i = 0; i<o.length; i++) { if(i!=0) { System.err.print(", "); } System.err.print(ts(o[i])); } System.err.println("]"); } } } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public boolean autoFlush; public String LineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); autoFlush = false; LineSeparator = System.lineSeparator(); } public void print(long l) { print(String.valueOf(l)); } public void print(String s) { sb.append(s); if(autoFlush) { flush(); }else if(sb.length()>BUFFER_SIZE >> 1) { flushToBuffer(); } } public void println() { sb.append(LineSeparator); } public void println(long[] arr) { for(int i = 0; i<arr.length; i++) { if(i!=0) { print(" "); } print(arr[i]); } println(); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static class DSU { public int[] rank; public int[] parent; public int[] size; public int n; public DSU(int x) { n = x; rank = new int[n]; parent = new int[n]; size = new int[n]; for(int i = 0; i<n; i++) { parent[i] = i; size[i] = 1; } } public int find(int i) { if(parent[i]==i) { return i; }else { int result = find(parent[i]); parent[i] = result; return result; } } public void union(int i, int j) { int irep = find(i); int jrep = find(j); if(irep==jrep) { return; } int irank = rank[irep]; int jrank = rank[jrep]; if(irank<jrank) { parent[irep] = jrep; size[jrep] += size[irep]; }else if(jrank<irank) { parent[jrep] = irep; size[irep] += size[jrep]; }else { parent[irep] = jrep; rank[jrep]++; size[jrep] += size[irep]; } } public boolean connected(int i, int j) { return find(i)==find(j); } public int size(int i) { return size[find(i)]; } } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output
PASSED
645163a7e1c48c30be73f922e2812b0d
train_003.jsonl
1567175700
You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.InputMismatchException; import java.io.BufferedOutputStream; import java.util.StringTokenizer; import java.io.Flushable; import java.io.OutputStream; import java.io.PrintStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Closeable; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); Output out = new Output(outputStream); GPathQueries solver = new GPathQueries(); solver.solve(1, in, out); out.close(); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29); thread.start(); thread.join(); } static class GPathQueries { public GPathQueries() { } public long choose(int x) { if(x==1) { return 0; } return (long) x*(x-1) >> 1L; } public void solve(int kase, Input in, Output pw) { int n = in.nextInt(), m = in.nextInt(); int[][] edges = new int[n-1][3]; for(int i = 0; i<n-1; i++) { edges[i] = new int[] {in.nextInt()-1, in.nextInt()-1, in.nextInt()}; } int[][] queries = new int[m][2]; for(int i = 0; i<m; i++) { queries[i] = new int[] {i, in.nextInt()}; } Arrays.sort(edges, Comparator.comparingInt(o -> o[2])); Arrays.sort(queries, Comparator.comparingInt(o -> o[1])); DSU dsu = new DSU(n); int j = 0; long ans = 0; long[] arr = new long[m]; Utilities.Debug.dbg("queries", queries, "edges", edges); for(int i = 0; i<m; i++) { int cur = queries[i][1]; for(; j<n-1&&edges[j][2]<=cur; j++) { int u = edges[j][0], v = edges[j][1]; if(!dsu.connected(u, v)) { int us = dsu.size(u), vs = dsu.size(v); ans += choose(us+vs)-choose(us)-choose(vs); dsu.union(u, v); } } arr[queries[i][0]] = ans; } pw.println(arr); } } static class Input { BufferedReader br; StringTokenizer st; public Input(InputStream is) { this(is, 1<<20); } public Input(InputStream is, int bs) { br = new BufferedReader(new InputStreamReader(is), bs); st = null; } public boolean hasNext() { try { while(st==null||!st.hasMoreTokens()) { String s = br.readLine(); if(s==null) { return false; } st = new StringTokenizer(s); } return true; }catch(Exception e) { return false; } } public String next() { if(!hasNext()) { throw new InputMismatchException(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class Utilities { public static class Debug { public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null; private static <T> String ts(T t) { if(t==null) { return "null"; } try { return ts((Iterable) t); }catch(ClassCastException e) { if(t instanceof int[]) { String s = Arrays.toString((int[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof long[]) { String s = Arrays.toString((long[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof char[]) { String s = Arrays.toString((char[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof double[]) { String s = Arrays.toString((double[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof boolean[]) { String s = Arrays.toString((boolean[]) t); return "{"+s.substring(1, s.length()-1)+"}"; } try { return ts((Object[]) t); }catch(ClassCastException e1) { return t.toString(); } } } private static <T> String ts(T[] arr) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: arr) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } private static <T> String ts(Iterable<T> iter) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: iter) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } public static void dbg(Object... o) { if(LOCAL) { System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": ["); for(int i = 0; i<o.length; i++) { if(i!=0) { System.err.print(", "); } System.err.print(ts(o[i])); } System.err.println("]"); } } } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public boolean autoFlush; public String LineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); autoFlush = false; LineSeparator = System.lineSeparator(); } public void print(long l) { print(String.valueOf(l)); } public void print(String s) { sb.append(s); if(autoFlush) { flush(); }else if(sb.length()>BUFFER_SIZE >> 1) { flushToBuffer(); } } public void println() { sb.append(LineSeparator); } public void println(long[] arr) { for(int i = 0; i<arr.length; i++) { if(i!=0) { print(" "); } print(arr[i]); } println(); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static class DSU { public int[] rank; public int[] parent; public int[] size; public int n; public DSU(int x) { n = x; rank = new int[n]; parent = new int[n]; size = new int[n]; for(int i = 0; i<n; i++) { parent[i] = i; size[i] = 1; } } public int find(int i) { if(parent[i]==i) { return i; }else { int result = find(parent[i]); parent[i] = result; return result; } } public void union(int i, int j) { int irep = find(i); int jrep = find(j); if(irep==jrep) { return; } int irank = rank[irep]; int jrank = rank[jrep]; if(irank<jrank) { parent[irep] = jrep; size[jrep] += size[irep]; }else if(jrank<irank) { parent[jrep] = irep; size[irep] += size[jrep]; }else { parent[irep] = jrep; rank[jrep]++; size[jrep] += size[irep]; } } public boolean connected(int i, int j) { return find(i)==find(j); } public int size(int i) { return size[find(i)]; } } }
Java
["7 5\n1 2 1\n3 2 3\n2 4 1\n4 5 2\n5 7 4\n3 6 2\n5 2 3 4 1", "1 2\n1 2", "3 3\n1 2 1\n2 3 2\n1 3 2"]
3 seconds
["21 7 15 21 3", "0 0", "1 3 3"]
NoteThe picture shows the tree from the first example:
Java 11
standard input
[ "graphs", "dsu", "divide and conquer", "sortings", "trees" ]
f94165f37e968442fa7f8be051018ad9
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.
1,800
Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u &lt; v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.
standard output