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
426ff5cb3268c45d2ebbbf77f66ee633
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.lang.*; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.atomic.LongAccumulator; import javax.management.openmbean.ArrayType; public class Main { static PrintWriter out; static int MOD = 1000000007; static FastReader scan; /*-------- I/O usaing short named function ---------*/ public static String ns() { return scan.next(); } public static int ni() { return scan.nextInt(); } public static long nl() { return scan.nextLong(); } public static double nd() { return scan.nextDouble(); } public static String nln() { return scan.nextLine(); } public static void p(Object o) { out.print(o); } public static void ps(Object o) { out.print(o + " "); } public static void pn(Object o) { out.println(o); } /*-------- for output of an array ---------------------*/ static void iPA(int arr[]) { StringBuilder output = new StringBuilder(); for (int i = 0; i < arr.length; i++) output.append(arr[i] + " "); out.println(output); } static void lPA(long arr[]) { StringBuilder output = new StringBuilder(); for (int i = 0; i < arr.length; i++) output.append(arr[i] + " "); out.println(output); } static void sPA(String arr[]) { StringBuilder output = new StringBuilder(); for (int i = 0; i < arr.length; i++) output.append(arr[i] + " "); out.println(output); } static void dPA(double arr[]) { StringBuilder output = new StringBuilder(); for (int i = 0; i < arr.length; i++) output.append(arr[i] + " "); out.println(output); } /*-------------- for input in an array ---------------------*/ static void iIA(int arr[]) { for (int i = 0; i < arr.length; i++) arr[i] = ni(); } static void lIA(long arr[]) { for (int i = 0; i < arr.length; i++) arr[i] = nl(); } static void sIA(String arr[]) { for (int i = 0; i < arr.length; i++) arr[i] = ns(); } static void dIA(double arr[]) { for (int i = 0; i < arr.length; i++) arr[i] = nd(); } /*------------ for taking input faster ----------------*/ 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; } } // Method to check if x is power of 2 static boolean isPowerOfTwo(int x) { return x != 0 && ((x & (x - 1)) == 0); } //Method to return lcm of two numbers static int gcd(int a, int b) { return a == 0 ? b : gcd(b % a, a); } //Method to count digit of a number static int countDigit(long n) { return (int) Math.floor(Math.log10(n) + 1); } //Method for sorting static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } //Method for checking if a number is prime or not 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 void reverse(int a[], int n) { int i, k, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } // printing the reversed array System.out.println("Reversed array is: \n"); for (k = 0; k < n; k++) { System.out.println(a[k]); } } public static int binarysearch(int arr[], int left, int right, int num) { int idx = 0; while (left <= right) { int mid = (left + right) / 2; if (arr[mid] >= num) { idx = mid; // if(arr[mid]==num)break; right = mid - 1; } else { left = mid + 1; } } return idx; } public static int mod = 1000000007; public static int[] rank; public static void main(String[] args) throws java.lang.Exception { OutputStream outputStream = System.out; out = new PrintWriter(outputStream); scan = new FastReader(); int T = ni(); while (T-- > 0) { int n = ni(); ArrayList<Integer>[] al = new ArrayList[n]; for (int i = 0; i < n; i++) { al[i] = new ArrayList<Integer>(); } int arr1[]=new int[n]; int arr2[]=new int[n]; HashMap<Integer,ArrayList> map=new HashMap<>(); HashMap<String,Integer> set=new HashMap<>(); for(int i=0;i<n-1;i++){ int a=ni()-1; int b=ni()-1; al[a].add(b); al[b].add(a); arr1[i]=a; arr2[i]=b; } int chk=0; for(int i=0;i<n;i++){ if(al[i].size()>2){ System.out.println("-1"); chk=-1; break; } } if(chk==0){ int j=0; for(int i=0;i<n;i++){ if(al[i].size()==1){ j=i; break; } } int p=3; // System.out.print(2+" "); set.put(j+"@"+al[j].get(0),2); set.put(al[j].get(0)+"@"+j,2); int last=j; j=al[j].get(0); for(int i=0;i<n-1;i++){ for(int k=0;k<al[j].size();k++){ if(al[j].get(k)!=last){ set.put(j+"@"+al[j].get(k),p); set.put(al[j].get(k)+"@"+j,p); if(p==3)p=2; else p=3; // System.out.println(last+" "+j); last=j; j=al[j].get(k); // System.out.println(last+" aftee "+j+" "+p); } } } // System.out.println(set); // set.put(j+"@"+last,p); // set.put(last+"@"+j,p); for(int i=0;i<n-1;i++){ System.out.print(set.get(arr1[i]+"@"+arr2[i])+" "); } System.out.println(); } } out.flush(); out.close(); } public static long power(int a, long b) { long ans = 1; while (b > 0) { if (b % 2 == 1) { ans = (ans * a) % mod; } a = (a * a) % mod; b /= 2; } return ans; } public static class pair implements Comparable<pair> { int x; int y; pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(pair o) { if (this.x == o.x) { return this.y - o.y; } else { return this.x - o.x; } } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
1faecc4f0d2f6f60962dda8ad747c992
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // import org.w3c.dom.Node; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.*; public class CFC { static CFC.Reader sc = new CFC.Reader(); static BufferedWriter bw; static int team1; static int team2; static int minkicks; public CFC() { } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); process: for (int p = 0; p < t; p++) { int n = sc.nextInt(); // SortedSet<Node> set=new TreeSet<>(); List<List<Node>> lists = new ArrayList<>(); // List<TreeSet<Integer>> list = new ArrayList<>(); for (int i = 0; i <=n; i++) { lists.add(new ArrayList<>()); // list.add(new TreeSet<>()); } // Map<int[],Integer> map=new HashMap<>(); // int[][] weights=new int[n+1][n+1]; int[] indeg = new int[n+1]; boolean flag=false; for (int j = 0; j < n - 1; j++) { int u = sc.nextInt(); int v = sc.nextInt(); int u1 = Math.min(u, v); int v1 = Math.max(u, v); Node n1 = new Node(u1, v1, 0, j); Node n2 = new Node(v1, u1, 0, j); indeg[v1]++; indeg[u1]++; if (indeg[v1] > 2 || indeg[u1] > 2) { flag=true; //continue process; } lists.get(u1).add(n1); lists.get(v1).add(n2); // list.get(u1).add(v1); } if (flag) { System.out.println(-1); continue process; } boolean[] vis=new boolean[n+1]; Map<Integer,Integer> map=new HashMap<>(); int start=2; for(int i=1;i<=n;i++){ if(!vis[i]){ dfs(lists,start,i,vis,map); start=5-start; } } for(int i=0;i<n-1;i++){ System.out.print(map.get(i)+" "); } System.out.println(); /* boolean[] visited=new boolean[n+1]; int[] parent=new int[n+1]; // int[][] weights=new int[n+1][n+1]; Queue<Integer> queue=new LinkedList<>(); queue.add(1); while (!queue.isEmpty()){ int num=queue.poll(); visited[num]=true; //List<Integer> children=lists.get(num); int start=0; if (num==1||parent[num] == 0) { start=2; }else { start=3; } int c=0; for(int j=0;j<=n;j++){ if(weights[num][j]==1){ if(!visited[j]){ parent[j]=num; //parent[children.get(j)]=num; c++; weights[num][j]=start; weights[j][num]=start; if(start==2){ start=3; }else { start=2; } // if(!visited[children.get(j)]) queue.add(j); } } } //if(c>=2) countg++; } *//* weights[1][0]=2; weights[0][1]=2;*//* for(int j=1;j<=n;j++){ Map<Integer,Integer> map=new HashMap<>(); map.put(2,0); map.put(3,0); for(int p=1;p<=n;p++){ if(weights[j][p]>=1){ map.put(weights[j][p],map.get(weights[j][p])+1); if(map.get(2)>1||map.get(3)>1){ System.out.println(-1); continue process; } } } } for(int j=0;j<edges.size();j++){ System.out.println(weights[edges.get(j)[0]][edges.get(j)[1]]); }*/ } bw.flush(); bw.close(); } public static class Node { int u, v, w, index; public Node(int u, int v, int w, int index) { this.u = u; this.v = v; this.w = w; this.index = index; } } public static long getAns(int[][] dp, boolean[] check, int[] coor, int[] limits, int n, int k, int index) { if (index == n - 1) return 0; if (dp[index][k] != -1) return dp[index][k]; long ans = Integer.MAX_VALUE; for (int i = 0; i <= k; i++) { if (index + i + 1 >= n) break; long diff = coor[index + i + 1] - coor[index]; diff *= limits[index]; long x = getAns(dp, check, coor, limits, n, k - i, index + i + 1); ans = Math.min(ans, diff + x); } dp[index][k] = (int) ans; return dp[index][k]; } public static void dfs(List<List<Node>> lists,int start,int i,boolean[] vis,Map<Integer,Integer> map) { vis[i]=true; for (Node node:lists.get(i)){ if(!vis[node.v]){ node.w=start; map.put(node.index,node.w); dfs(lists,5-start,node.v,vis,map); start=5-start; } } } public static int checker(int a) { if (a % 2 == 0) { return 1; } else { byte b; do { b = 2; } while (a + b != (a ^ b)); return b; } } public static boolean checkPrime(int n) { if (n != 0 && n != 1) { for (int j = 2; j * j <= n; ++j) { if (n % j == 0) { return false; } } return true; } else { return false; } } public static int inputInt() throws IOException { return sc.nextInt(); } public static long inputLong() throws IOException { return sc.nextLong(); } public static double inputDouble() throws IOException { return sc.nextDouble(); } public static String inputString() throws IOException { return sc.readLine(); } public static void print(String a) throws IOException { bw.write(a); } public static void printSp(String a) throws IOException { bw.write(a + " "); } public static void println(String a) throws IOException { bw.write(a + "\n"); } public static long power(long a, long b, long c) { long ans; for (ans = 1L; b != 0L; b /= 2L) { if (b % 2L == 1L) { ans *= a; ans %= c; } a *= a; a %= c; } return ans; } public static long power1(long a, long b, long c) { long ans; for (ans = 1L; b != 0L; b /= 2L) { if (b % 2L == 1L) { ans = multiply(ans, a, c); } a = multiply(a, a, c); } return ans; } public static long multiply(long a, long b, long c) { long res = 0L; for (a %= c; b > 0L; b /= 2L) { if (b % 2L == 1L) { res = (res + a) % c; } a = (a + a) % c; } return res % c; } public static long totient(long n) { long result = n; for (long i = 2L; i * i <= n; ++i) { if (n % i == 0L) { while (n % i == 0L) { n /= i; } result -= result / i; } } if (n > 1L) { result -= result / n; } return result; } public static long gcd(long a, long b) { return b == 0L ? a : gcd(b, a % b); } public static boolean[] primes(int n) { boolean[] p = new boolean[n + 1]; p[0] = false; p[1] = false; int i; for (i = 2; i <= n; ++i) { p[i] = true; } for (i = 2; i * i <= n; ++i) { if (p[i]) { for (int j = i * i; j <= n; j += i) { p[j] = false; } } } return p; } public String LargestEven(String S) { int[] count = new int[10]; int num; for (num = 0; num < S.length(); ++num) { ++count[S.charAt(num) - 48]; } num = -1; for (int i = 0; i <= 8; i += 2) { if (count[i] > 0) { num = i; break; } } StringBuilder ans = new StringBuilder(); for (int i = 9; i >= 0; --i) { int j; if (i != num) { for (j = 1; j <= count[i]; ++j) { ans.append(i); } } else { for (j = 1; j <= count[num] - 1; ++j) { ans.append(num); } } } if (num != -1 && count[num] > 0) { ans.append(num); } return ans.toString(); } static { bw = new BufferedWriter(new OutputStreamWriter(System.out)); team1 = 0; team2 = 0; minkicks = 10; } public static class Score { int l; String s; public Score(int l, String s) { this.l = l; this.s = s; } } static class Reader { private final int BUFFER_SIZE = 65536; private DataInputStream din; private byte[] buffer; private int bufferPointer; private int bytesRead; public Reader() { this.din = new DataInputStream(System.in); this.buffer = new byte[65536]; this.bufferPointer = this.bytesRead = 0; } public Reader(String file_name) throws IOException { this.din = new DataInputStream(new FileInputStream(file_name)); this.buffer = new byte[65536]; this.bufferPointer = this.bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; int cnt; byte c; for (cnt = 0; (c = this.read()) != -1 && c != 10; buf[cnt++] = (byte) c) { } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c; for (c = this.read(); c <= 32; c = this.read()) { } boolean neg = c == 45; if (neg) { c = this.read(); } do { ret = ret * 10 + c - 48; } while ((c = this.read()) >= 48 && c <= 57); return neg ? -ret : ret; } public long nextLong() throws IOException { long ret = 0L; byte c; for (c = this.read(); c <= 32; c = this.read()) { } boolean neg = c == 45; if (neg) { c = this.read(); } do { ret = ret * 10L + (long) c - 48L; } while ((c = this.read()) >= 48 && c <= 57); return neg ? -ret : ret; } public double nextDouble() throws IOException { double ret = 0.0D; double div = 1.0D; byte c; for (c = this.read(); c <= 32; c = this.read()) { } boolean neg = c == 45; if (neg) { c = this.read(); } do { ret = ret * 10.0D + (double) c - 48.0D; } while ((c = this.read()) >= 48 && c <= 57); if (c == 46) { while ((c = this.read()) >= 48 && c <= 57) { ret += (double) (c - 48) / (div *= 10.0D); } } return neg ? -ret : ret; } private void fillBuffer() throws IOException { this.bytesRead = this.din.read(this.buffer, this.bufferPointer = 0, 65536); if (this.bytesRead == -1) { this.buffer[0] = -1; } } private byte read() throws IOException { if (this.bufferPointer == this.bytesRead) { this.fillBuffer(); } return this.buffer[this.bufferPointer++]; } public void close() throws IOException { if (this.din != null) { this.din.close(); } } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
2a8015bbfaef561264becde0c74e4e83
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; public class Main { static boolean ans; public static void main (String[] args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t-->0){ int i; int n=Integer.parseInt(br.readLine()); ArrayList<ArrayList<Integer>> arr=new ArrayList<>(); for(i=0;i<=n;i++) arr.add(new ArrayList<>()); //int i; ArrayList<mine> remember=new ArrayList<>(); for(i=0;i<n-1;i++){ String h[]=br.readLine().split(" "); int u=Integer.parseInt(h[0]); int v=Integer.parseInt(h[1]); arr.get(u).add(v); arr.get(v).add(u); remember.add(new mine(u,v)); } int root=-1; ans=true; for(i=1;i<=n;i++){ if(arr.get(i).size()==1){ root=i; } if(arr.get(i).size()>=3){ ans=false; } } if(ans==false||root==-1){ System.out.println("-1"); } else{ HashMap<String,Integer> set=new HashMap<>(); int dp[]=new int[n+1]; Arrays.fill(dp,-1); dp[root]=2; dfs(root,-1,arr,set,dp); // for(Map.Entry<String,Integer> h:set.entrySet()){ // System.out.print(h.getKey()+" "+h.getValue()); // } for(i=0;i<n-1;i++){ //String h[]=(remember.get(i)).split("$"); int u=remember.get(i).u; int v=remember.get(i).v; String t1=u+"$"+v; String t2=v+"$"+u; if(set.containsKey(t1)){ System.out.print(set.get(t1)+" "); } else System.out.print(set.get(t2)+" "); } System.out.println(); } } } public static void dfs(int u,int p,ArrayList<ArrayList<Integer>> arr,HashMap<String,Integer> map,int dp[]){ for(int v:arr.get(u)){ if(v==p) continue; if(dp[v]==-1){ dp[v]=reverse(dp[u]); map.put(u+"$"+v,dp[v]); dfs(v,u,arr,map,dp); } } } public static int reverse(int u){ if(u==2) return 3; return 2; } } class mine{ int u; int v; public mine(int a,int y){ u=a; v=y; } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
75c6aa2ade1b68b64fb198408d9440bc
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class contestc { FastScanner scn; PrintWriter w; PrintStream fs; long MOD = 1000000007; int MAX = 200005; long mul(long x, long y) {long res = x * y; return (res >= MOD ? res % MOD : res);} long power(long x, long y) {if (y < 0) return 1; long res = 1; x %= MOD; while (y!=0) {if ((y & 1)==1)res = mul(res, x); y >>= 1; x = mul(x, x);} return res;} void ruffleSort(int[] a) {int n=a.length;Random r=new Random();for (int i=0; i<a.length; i++) {int oi=r.nextInt(n), temp=a[i];a[i]=a[oi];a[oi]=temp;}Arrays.sort(a);} void reverseSort(int[] arr){List<Integer> list = new ArrayList<>();for (int i=0; i<arr.length; i++){list.add(arr[i]);}Collections.sort(list, Collections.reverseOrder());for (int i = 0; i < arr.length; i++){arr[i] = list.get(i);}} boolean LOCAL; void debug(Object... o){if(LOCAL)System.err.println(Arrays.deepToString(o));} //SUFFICIENT DRY RUN????LOGIC VERIFIED FOR ALL TEST CASES??? void dfs(int src,int par,int valPassed,ArrayList<Integer>[] adj,HashMap<Key,Integer> hm){ if(valPassed==0){ }else if(valPassed!=2){ hm.put(new Key(src,par),2); hm.put(new Key(par,src),2); // matrix[src][par] = 2; // matrix[par][src] = 2; }else{ // matrix[src][par] = 3; // matrix[par][src] = 3; hm.put(new Key(src,par),3); hm.put(new Key(par,src),3); } for(int child:adj[src]){ if(child!=par){ dfs(child,src,hm.get(new Key(src,par)),adj,hm); } } } class Pair{ int ff;int ss; Pair(int ff,int ss){ this.ff=ff; this.ss=ss; } } class Key { private final int x; private final int y; public Key(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Key)) return false; Key key = (Key) o; return x == key.x && y == key.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } } void solve(){ int t=scn.nextInt(); while(t-->0) { int n=scn.nextInt(); ArrayList<Integer>[] adj = new ArrayList[n+1]; for(int i=0;i<=n;i++){ adj[i] = new ArrayList<>(); } // int[][] matrix = new int[n+1][n+1]; HashMap<Key,Integer> hm = new HashMap<>(); Pair[] ar= new Pair[n+1]; for(int nt=1;nt<=n-1;nt++){ int x=scn.nextInt(); int y =scn.nextInt(); adj[x].add(y); adj[y].add(x); ar[nt] = new Pair(x,y); } // int[] parent = new int[n+1]; // dfs(1,0,parent,adj); // debug(parent); // Queue<Integer> que = new ArrayDeque<>(); // que.add(1); // int par = -1; // boolean[] visited = new boolean[n+1]; // visited[1] = true; // boolean hmm = true; // boolean next = false; // while(que.size()>0){ // debug(que); // int src = que.remove(); // int count = 0; // for(int child:adj[src]){ // if(child!=parent[src]){ // que.add(child); // visited[child] = true; // if(!next&&src==1){ // matrix[src][child] = 3; // matrix[child][src] = 3; // next = true; // } // else if(next&&src==1){ // matrix[src][child] = 2; // matrix[child][src] = 2; // next = true; // } // if(src!=1){ // if(matrix[src][parent[src]]!=2){ // matrix[src][child] = 2; // matrix[child][src] = 2; // next = true; // }else{ // matrix[src][child] = 11; // matrix[child][src] = 11; // next = true; // } // } // count++; // debug(count,src); // if(src==1){if(count>2){hmm=false; break;}} // else if(count>1) {hmm=false; break;} // } // } // if(!hmm) break; // } // if(!hmm){ // w.println(-1); // }else{ // for(int i=1;i<=n-1;i++){ // int x = ar[i][0]; // int y = ar[i][1]; // w.print(matrix[x][y]+" "); // } // w.println(); // } if(adj[1].size()>2){ w.println(-1); continue; }else{ boolean check = true; for(int i=2;i<=n;i++){ if(adj[i].size()>2){ check = false; break; } } if(check){ hm.put(new Key(1,0),0); hm.put(new Key(0,1),0); if(adj[1].size()==2){ // matrix[adj[1].get(0)][1] = 2; // matrix[1][adj[1].get(0)] = 2; // matrix[adj[1].get(1)][1] = 3; // matrix[1][adj[1].get(1)] = 3; hm.put(new Key(adj[1].get(0),1),2); hm.put(new Key(1,adj[1].get(0)),2); hm.put(new Key(adj[1].get(1),1),3); hm.put(new Key(1,adj[1].get(1)),3); }else{ hm.put(new Key(adj[1].get(0),1),2); hm.put(new Key(1,adj[1].get(0)),2); } dfs(1,0,0,adj,hm); // debug(hm); for(int i=1;i<=n-1;i++){ Pair p = ar[i]; int x = p.ff; int y = p.ss; w.print(hm.get(new Key(x,y))+" "); } w.println(); }else{ w.println(-1); continue; } } } } void run() { try { long ct = System.currentTimeMillis(); scn = new FastScanner(new File("input.txt")); w = new PrintWriter(new File("output.txt")); fs=new PrintStream("error.txt"); System.setErr(fs); LOCAL=true; solve(); w.close(); System.err.println(System.currentTimeMillis() - ct); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { scn = new FastScanner(System.in); w = new PrintWriter(System.out); LOCAL=false; solve(); w.close(); } 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()); } int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } int lowerBound(int[] arr, int x){int n = arr.length, si = 0, ei = n - 1;while(si <= ei){int mid = si + (ei - si)/2;if(arr[mid] == x){if(mid-1 >= 0 && arr[mid-1] == arr[mid]){ei = mid-1;}else{return mid;}}else if(arr[mid] > x){ei = mid - 1; }else{si = mid+1;}}return si; } int upperBound(int[] arr, int x){int n = arr.length, si = 0, ei = n - 1;while(si <= ei){int mid = si + (ei - si)/2;if(arr[mid] == x){if(mid+1 < n && arr[mid+1] == arr[mid]){si = mid+1;}else{return mid + 1;}}else if(arr[mid] > x){ei = mid - 1; }else{si = mid+1;}}return si; } int upperBound(ArrayList<Integer> list, int x){int n = list.size(), si = 0, ei = n - 1;while(si <= ei){int mid = si + (ei - si)/2;if(list.get(mid) == x){if(mid+1 < n && list.get(mid+1) == list.get(mid)){si = mid+1;}else{return mid + 1;}}else if(list.get(mid) > x){ei = mid - 1; }else{si = mid+1;}}return si; } void swap(int[] arr, int i, int j){int temp = arr[i];arr[i] = arr[j];arr[j] = temp;} int gcd(int a, int b) {if(a == 0){return b;}return gcd(b%a, a);} // TC- O(logmax(a,b)) boolean nextPermutation(int[] arr) {if(arr == null || arr.length <= 1){return false;}int last = arr.length-2;while(last >= 0){if(arr[last] < arr[last+1]){break;}last--;}if (last < 0){return false;}if(last >= 0){int nextGreater = arr.length-1;for(int i=arr.length-1; i>last; i--){if(arr[i] > arr[last]){nextGreater = i;break;}}swap(arr, last, nextGreater);}int i = last + 1, j = arr.length - 1;while(i < j){swap(arr, i++, j--);}return true;} public static void main(String[] args) { new contestc().runIO(); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
e12bb42d10de6a0b22b406165edb6960
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class NotAssigning { public static PrintWriter out; static ArrayList<ArrayList<Integer>> connections; public static void main(String[] args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(br.readLine()); out=new PrintWriter(System.out); int t=Integer.parseInt(st.nextToken()); while(t-->0) { st=new StringTokenizer(br.readLine()); connections=new ArrayList<>(); int n=Integer.parseInt(st.nextToken()); boolean[] v=new boolean[n]; for(int i=0;i<n;i++) { connections.add(new ArrayList<Integer>()); } int deg[]=new int[n]; HashMap<String, Integer> hm=new HashMap<>(); for(int i=0;i<n-1;i++) { st=new StringTokenizer(br.readLine()); int x=Integer.parseInt(st.nextToken())-1; int y=Integer.parseInt(st.nextToken())-1; connections.get(x).add(y); connections.get(y).add(x); deg[x]++; deg[y]++; hm.put(x+" "+y,i); hm.put(y+" "+x,i); } boolean pos=true; int start=-1; int end=-1; for(int i=0;i<n;i++) { if(deg[i]>=3) { pos=false; break; } if(deg[i]==1) { if(start==-1) { start=i; }else { end=i; } } } if(!pos) { out.println(-1); continue; } int weight=2; int ans[]=new int[n]; ans[start]=weight; ArrayDeque<Integer> q=new ArrayDeque<>(); q.add(start); v[start]=true; while(!q.isEmpty()) { int cur=q.poll(); if(cur==end) { break; } for(int next:connections.get(cur)) { if(!v[next]) { q.add(next); v[next]=true; weight=5-weight; ans[hm.get(cur+" "+next)]=weight; } } } for(int i=0;i<n-1;i++) { out.print(ans[i]+" "); } out.println(); } out.close(); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
7acd63a299013681236d79066b886292
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.text.DecimalFormat; import java.util.*; public class Solution { static BufferedReader bf; static PrintWriter out; static Scanner sc; static StringTokenizer st; static long mod = (long)(1e9+7); static long mod2 = 998244353; static long fact[] ; static long inverse[]; public static void main (String[] args)throws IOException { bf = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new Scanner(System.in); // fact[0] = 1; // inverse[0] = 1; // for(int i = 1;i<fact.length;i++){ // fact[i] = (fact[i-1] * i)%mod; // // inverse[i] = binaryExpo(fact[i], mod-2);a // } int t = nextInt(); while(t-->0){ solve(); } out.flush(); } public static void solve() throws IOException{ int n = nextInt(); List<List<Integer>>list = new ArrayList<>(); for(int i = 0;i<=n;i++){ list.add(new ArrayList<>()); } int[][]edges = new int[n-1][2]; for(int i = 0;i<n-1;i++){ int u = nextInt(); int v = nextInt(); list.get(u).add(v); list.get(v).add(u); edges[i][0] = u; edges[i][1] = v; } for(int i = 1;i<=n;i++){ if(list.get(i).size() >= 3){ out.println(-1); return; } } Map<String,Integer>map = new HashMap<>(); for(int i = 1;i<=n;i++){ if(list.get(i).size() == 1){ assign(list,i,-1,map,true); break; } } for(int i = 0;i<n-1;i++){ String one = edges[i][0] + " " + edges[i][1]; out.print(map.get(one) + " "); } out.println(); } public static void assign(List<List<Integer>>list,int cur,int parent,Map<String,Integer>map,boolean two ){ List<Integer>temp = list.get(cur); for(int i = 0;i<temp.size();i++){ int next = temp.get(i); if(next != parent){ String one = cur + " " + next; String second = next + " " + cur; if(two){ map.put(one,2); map.put(second,2); } else{ map.put(one,11); map.put(second,11); } assign(list,next,cur,map,!two); } } } public static int height(List<List<Integer>>list,int cur,int parent){ List<Integer>temp = list.get(cur); int max = 0; for(int i = 0;i<temp.size();i++){ int next = temp.get(i); if(next != parent){ max = Math.max(max,height(list,next,cur)); } } return max+1; } public static void req(int i,int j){ out.println("? " + i + " " + j); out.flush(); } public static int maxy(int node, int l,int r,int tl,int tr,int[][]tree){ if(l>=tl && r <= tr)return tree[node][0]; if(r < tl || l > tr)return Integer.MIN_VALUE; int mid = (l + r)/2; return Math.max(maxy(node*2,l,mid,tl,tr,tree),maxy(node*2+1,mid+1,r,tl,tr,tree)); } public static int mini(int node,int l,int r,int tl,int tr,int[][]tree){ if(l >= tl && r <= tr)return tree[node][1]; if(r < tl || l > tr)return Integer.MAX_VALUE; int mid = (l + r)/2; return Math.min(mini(node*2 , l , mid ,tl ,tr,tree),mini(node*2 + 1, mid + 1, r, tl, tr, tree)); } public static void fillParent(int[][]parent,List<List<Integer>>list,int cur ,int p,int[]depths){ parent[cur][0] = p; List<Integer>temp = list.get(cur); for(int i = 0;i<temp.size();i++){ int next = temp.get(i); if(next != p){ depths[next] = depths[cur] + 1; fillParent(parent,list,next,cur,depths); } } } public static int lca(int[][]parent , int u, int v){ if(u == v)return u; for(int i = 18;i>=0;i--){ if(parent[u][i] != parent[v][i]){ u = parent[u][i]; v = parent[v][i]; } } return parent[u][0]; } public static int bringSame(int[][]parent,int[]depths,int u, int v){ if(depths[u] < depths[v]){ int temp = u; u = v; v = temp; } int k = depths[u] - depths[v]; for(int i = 0;i<=18;i++){ if((k & (1<<i)) != 0){ u = parent[u][i]; } } return u; } public static long nck(int n,int k){ return fact[n] * inverse[n-k] %mod * inverse[k]%mod; } public static void plus(int node,int low,int high,int tlow,int thigh,int[]tree){ if(low >= tlow && high <= thigh){ tree[node]++; return; } if(high < tlow || low > thigh)return; int mid = (low + high)/2; plus(node*2,low,mid,tlow,thigh,tree); plus(node*2 + 1 , mid + 1, high,tlow, thigh,tree); } public static boolean allEqual(int[]arr,int x){ for(int i = 0;i<arr.length;i++){ if(arr[i] != x)return false; } return true; } public static long helper(StringBuilder sb){ return Long.parseLong(sb.toString()); } public static int min(int node,int low,int high,int tlow,int thigh,int[][]tree){ if(low >= tlow&& high <= thigh)return tree[node][0]; if(high < tlow || low > thigh)return Integer.MAX_VALUE; int mid = (low + high)/2; // println(low+" "+high+" "+tlow+" "+thigh); return Math.min(min(node*2,low,mid,tlow,thigh,tree) ,min(node*2+1,mid+1,high,tlow,thigh,tree)); } public static int max(int node,int low,int high,int tlow,int thigh,int[][]tree){ if(low >= tlow && high <= thigh)return tree[node][1]; if(high < tlow || low > thigh)return Integer.MIN_VALUE; int mid = (low + high)/2; return Math.max(max(node*2,low,mid,tlow,thigh,tree) ,max(node*2+1,mid+1,high,tlow,thigh,tree)); } public static long[] help(List<List<Integer>>list,int[][]range,int cur){ List<Integer>temp = list.get(cur); if(temp.size() == 0)return new long[]{range[cur][1],1}; long sum = 0; long count = 0; for(int i = 0;i<temp.size();i++){ long []arr = help(list,range,temp.get(i)); sum += arr[0]; count += arr[1]; } if(sum < range[cur][0]){ count++; sum = range[cur][1]; } return new long[]{sum,count}; } public static long findSum(int node,int low, int high,int tlow,int thigh,long[]tree,long mod){ if(low >= tlow && high <= thigh)return tree[node]%mod; if(low > thigh || high < tlow)return 0; int mid = (low + high)/2; return((findSum(node*2,low,mid,tlow,thigh,tree,mod) % mod) + (findSum(node*2+1,mid+1,high,tlow,thigh,tree,mod)))%mod; } public static boolean allzero(long[]arr){ for(int i =0 ;i<arr.length;i++){ if(arr[i]!=0)return false; } return true; } public static long count(long[][]dp,int i,int[]arr,int drank,long sum){ if(i == arr.length)return 0; if(dp[i][drank]!=-1 && arr[i]+sum >=0)return dp[i][drank]; if(sum + arr[i] >= 0){ long count1 = 1 + count(dp,i+1,arr,drank+1,sum+arr[i]); long count2 = count(dp,i+1,arr,drank,sum); return dp[i][drank] = Math.max(count1,count2); } return dp[i][drank] = count(dp,i+1,arr,drank,sum); } public static void help(int[]arr,char[]signs,int l,int r){ if( l < r){ int mid = (l+r)/2; help(arr,signs,l,mid); help(arr,signs,mid+1,r); merge(arr,signs,l,mid,r); } } public static void merge(int[]arr,char[]signs,int l,int mid,int r){ int n1 = mid - l + 1; int n2 = r - mid; int[]a = new int[n1]; int []b = new int[n2]; char[]asigns = new char[n1]; char[]bsigns = new char[n2]; for(int i = 0;i<n1;i++){ a[i] = arr[i+l]; asigns[i] = signs[i+l]; } for(int i = 0;i<n2;i++){ b[i] = arr[i+mid+1]; bsigns[i] = signs[i+mid+1]; } int i = 0; int j = 0; int k = l; boolean opp = false; while(i<n1 && j<n2){ if(a[i] <= b[j]){ arr[k] = a[i]; if(opp){ if(asigns[i] == 'R'){ signs[k] = 'L'; } else{ signs[k] = 'R'; } } else{ signs[k] = asigns[i]; } i++; k++; } else{ arr[k] = b[j]; int times = n1 - i; if(times%2 == 1){ if(bsigns[j] == 'R'){ signs[k] = 'L'; } else{ signs[k] = 'R'; } } else{ signs[k] = bsigns[j]; } j++; opp = !opp; k++; } } while(i<n1){ arr[k] = a[i]; if(opp){ if(asigns[i] == 'R'){ signs[k] = 'L'; } else{ signs[k] = 'R'; } } else{ signs[k] = asigns[i]; } i++; k++; } while(j<n2){ arr[k] = b[j]; signs[k] = bsigns[j]; j++; k++; } } public static long binaryExpo(long base,long expo){ if(expo == 0)return 1; long val; if(expo%2 == 1){ val = (binaryExpo(base, expo-1)*base)%mod; } else{ val = binaryExpo(base, expo/2); val = (val*val)%mod; } return (val%mod); } public static boolean isSorted(int[]arr){ for(int i =1;i<arr.length;i++){ if(arr[i] < arr[i-1]){ return false; } } return true; } //function to find the topological sort of the a DAG public static boolean hasCycle(int[]indegree,List<List<Integer>>list,int n,List<Integer>topo){ Queue<Integer>q = new LinkedList<>(); for(int i =1;i<indegree.length;i++){ if(indegree[i] == 0){ q.add(i); topo.add(i); } } while(!q.isEmpty()){ int cur = q.poll(); List<Integer>l = list.get(cur); for(int i = 0;i<l.size();i++){ indegree[l.get(i)]--; if(indegree[l.get(i)] == 0){ q.add(l.get(i)); topo.add(l.get(i)); } } } if(topo.size() == n)return false; return true; } // function to find the parent of any given node with path compression in DSU public static int find(int val,int[]parent){ if(val == parent[val])return val; return parent[val] = find(parent[val],parent); } // function to connect two components public static void union(int[]rank,int[]parent,int u,int v){ int a = find(u,parent); int b= find(v,parent); if(a == b)return; if(rank[a] == rank[b]){ parent[b] = a; rank[a]++; } else{ if(rank[a] > rank[b]){ parent[b] = a; } else{ parent[a] = b; } } } // public static int findN(int n){ int num = 1; while(num < n){ num *=2; } return num; } // code for input public static void print(String s ){ System.out.print(s); } public static void print(int num ){ System.out.print(num); } public static void print(long num ){ System.out.print(num); } public static void println(String s){ System.out.println(s); } public static void println(int num){ System.out.println(num); } public static void println(long num){ System.out.println(num); } public static void println(){ System.out.println(); } public static int Int(String s){ return Integer.parseInt(s); } public static long Long(String s){ return Long.parseLong(s); } public static String[] nextStringArray()throws IOException{ return bf.readLine().split(" "); } public static String nextString()throws IOException{ return bf.readLine(); } public static long[] nextLongArray(int n)throws IOException{ String[]str = bf.readLine().split(" "); long[]arr = new long[n]; for(int i =0;i<n;i++){ arr[i] = Long.parseLong(str[i]); } return arr; } public static int[][] newIntMatrix(int r,int c)throws IOException{ int[][]arr = new int[r][c]; for(int i =0;i<r;i++){ String[]str = bf.readLine().split(" "); for(int j =0;j<c;j++){ arr[i][j] = Integer.parseInt(str[j]); } } return arr; } public static long[][] newLongMatrix(int r,int c)throws IOException{ long[][]arr = new long[r][c]; for(int i =0;i<r;i++){ String[]str = bf.readLine().split(" "); for(int j =0;j<c;j++){ arr[i][j] = Long.parseLong(str[j]); } } return arr; } static class pair{ int one; int two; pair(int one,int two){ this.one = one ; this.two =two; } } public static long gcd(long a,long b){ if(b == 0)return a; return gcd(b,a%b); } public static long lcm(long a,long b){ return (a*b)/(gcd(a,b)); } public static boolean isPalindrome(String s){ int i = 0; int j = s.length()-1; while(i<=j){ if(s.charAt(i) != s.charAt(j)){ return false; } i++; j--; } return true; } // these functions are to calculate the number of smaller elements after self public static void sort(int[]arr,int l,int r){ if(l < r){ int mid = (l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); smallerNumberAfterSelf(arr, l, mid, r); } } public static void smallerNumberAfterSelf(int[]arr,int l,int mid,int r){ int n1 = mid - l +1; int n2 = r - mid; int []a = new int[n1]; int[]b = new int[n2]; for(int i = 0;i<n1;i++){ a[i] = arr[l+i]; } for(int i =0;i<n2;i++){ b[i] = arr[mid+i+1]; } int i = 0; int j =0; int k = l; while(i<n1 && j < n2){ if(a[i] < b[j]){ arr[k++] = a[i++]; } else{ arr[k++] = b[j++]; } } while(i<n1){ arr[k++] = a[i++]; } while(j<n2){ arr[k++] = b[j++]; } } public static String next(){ while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bf.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static String nextLine(){ String str = ""; try { str = bf.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } static String interpolate(int n,List<Integer>items,List<Float>prices){ List<Integer>item = new ArrayList<>(); List<Float>price = new ArrayList<>(); for(int i =0 ;i<items.size();i++){ if(items.get(i)> 0){ item.add(items.get(i)); price.add(prices.get(i)); } } DecimalFormat df = new DecimalFormat("0.00"); if(item.size() == 1){ return df.format(price.get(0))+""; } for(int i = 0;i<item.size();i++){ if(n == item.get(i)){ return df.format(price.get(i))+""; } } for(int i = 0;i<item.size()-1;i++){ if(item.get(i) < n && n < item.get(i+1)){ float x1 = item.get(i); float x2 = item.get(i+1); float y1 = price.get(i); float y2 = price.get(i+1); float m = (y2 - y1)/(x2 - x1); float c = y1 - m * x1; float ans = m * n + c; return df.format(ans)+""; } } if(item.get(0) > n){ float x1 = item.get(0); float x2 = item.get(1); float y1 = price.get(0); float y2 = price.get(1); float m = (y2 - y1)/(x2 - x1); float c = y1 - m * x1; float ans = m * n + c; return df.format(ans)+""; } int size = item.size(); float x1 = item.get(size-2); float x2 = item.get(size-1); float y1 = price.get(size-2); float y2 = price.get(size-1); float m = (y2 - y1)/(x2 - x1); float c = y1 - m * x1; float ans = m * n + c; return df.format(ans)+""; } } // use some math tricks it might help // sometimes just try to think in straightforward plan in A and B problems don't always complecate the questions with thinking too much differently // always use long number to do 10^9+7 modulo // if a problem is related to binary string it could also be related to parenthesis // *****try to use binary search(it is a very beautiful thing it can work in some of the very unexpected problems ) in the question it might work****** // try sorting // try to think in opposite direction of question it might work in your way // if a problem is related to maths try to relate some of the continuous subarray with variables like - > a+b+c+d or a,b,c,d in general // if the question is to much related to left and/or right side of any element in an array then try monotonic stack it could work. // in range query sums try to do binary search it could work // analyse the time complexity of program thoroughly // anylyse the test cases properly // if we divide any number by 2 till it gets 1 then there will be (number - 1) operation required // try to do the opposite operation of what is given in the problem //think about the base cases properly //If a question is related to numbers try prime factorisation or something related to number theory // keep in mind unique strings //you can calculate the number of inversion in O(n log n) // in a matrix you could sometimes think about row and cols indenpendentaly. // Try to think in more constructive(means a way to look through various cases of a problem) way. // observe the problem carefully the answer could be hidden in the given test cases itself. (A, B , C); // when we have equations like (a+b = N) and we have to find the max of (a*b) then the values near to the N/2 must be chosen as (a and b); // give emphasis to the number of occurences of elements it might help. // if a number is even then we can find the pair for each and every number in that range whose bitwise AND is zero. // if a you find a problem related to the graph make a graph
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
4faaa91d52d5158492a6ef851544f115
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; public class q3{ static FastScanner fs = new FastScanner(); static PrintWriter pw = new PrintWriter(System.out); static List<List<Edge>> list; public static void main(String[] args){ int tt = fs.nextInt(); for (int t=0;t<tt;t++){ solve(); } pw.close(); } static void solve(){ int n = fs.nextInt(); list = new ArrayList<>(); for (int i=0;i<n;i++) list.add(new ArrayList<>()); for (int i=0;i<n-1;i++){ int from = fs.nextInt()-1, to = fs.nextInt()-1; list.get(from).add(new Edge(to, i)); list.get(to).add(new Edge(from, i)); } int start = -1; for (int i=0;i<n;i++){ if (list.get(i).size() > 2){ pw.println(-1); return; } else if (list.get(i).size() == 1){ start = i; } } int[] ans = new int[n-1]; int prev = -1; int cur = start; int curWeight = 2; while (true){ Edge now = list.get(cur).get(0); if (now.node == prev){ if (list.get(cur).size() == 1){ break; } now = list.get(cur).get(1); } ans[now.index] = 5 - curWeight; curWeight = ans[now.index]; prev = cur; cur = now.node; } for (int i : ans){ pw.printf("%d ", i); } pw.println(); } static class Edge { int node; int index; public Edge(int node, int index){ this.node = node; this.index = index; } } // ----------input function---------- static void sort(int[] a){ ArrayList<Integer> L = new ArrayList<>(); for (int i : a) L.add(i); Collections.sort(L); for (int i = 0; i < a.length; i++) a[i] = L.get(i); } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next(){ while (!st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } int[] readArray(int n){ int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong(){ return Long.parseLong(next()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
74719fb622c53cff0bce11a4eba0e9d2
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class D { public static class Edge { int u, v, weight; public Edge(int u, int v) { this.u = u; this.v = v; } @Override public String toString() { return "u: " + u + " v: " + v + " weight : " + weight; } } public static void main(String[] args)throws IOException { FastScanner scan = new FastScanner(); PrintWriter output = new PrintWriter(System.out); int t = scan.nextInt(); for(int tt = 0;tt<t;tt++) { int n = scan.nextInt(); ArrayList<Edge> graph[] = new ArrayList[n]; for(int i = 0;i<n;i++) { graph[i] = new ArrayList<>(); } Edge edges[] = new Edge[n-1]; for(int i = 0;i<n-1;i++) { int u = scan.nextInt()-1, v = scan.nextInt()-1; edges[i] = new Edge(u, v); graph[u].add(edges[i]); graph[v].add(edges[i]); } boolean possible = true; int start = 0; for(int i = 0;i<n;i++) { ArrayList<Edge> edge = graph[i]; if(edge.size() == 1) start = i; if(edge.size() > 2) possible = false; } if(!possible) { output.println(-1); continue; } int cur = start; cur^= graph[start].get(0).v; cur^= graph[start].get(0).u; Edge edge = graph[start].get(0); graph[start].get(0).weight = 2; int i = 1; while(true) { if(graph[cur].size() == 1) break; if(edge == graph[cur].get(0)) edge = graph[cur].get(1); else edge = graph[cur].get(0); cur^= edge.v; cur^= edge.u; edge.weight = i%2+2; i++; } for(Edge ed : edges) { output.print(ed.weight + " "); } output.println(); } output.flush(); } public static int[] sort(int arr[]) { List<Integer> list = new ArrayList<>(); for(int i:arr) list.add(i); Collections.sort(list); for(int i = 0;i<list.size();i++) arr[i] = list.get(i); return arr; } public static int gcd(int a, int b) { if(a == 0) return b; return gcd(b%a, a); } public static void printArray(int arr[]) { for(int i:arr) System.out.print(i+" "); System.out.println(); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
2dda6bec5bdd832fed3e967ed8f53fa6
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class D { public static class Edge { int u, v, weight; public Edge(int u, int v) { this.u = u; this.v = v; } @Override public String toString() { return "u: " + u + " v: " + v + " weight : " + weight; } } public static void main(String[] args)throws IOException { FastScanner scan = new FastScanner(); PrintWriter output = new PrintWriter(System.out); int t = scan.nextInt(); for(int tt = 0;tt<t;tt++) { int n = scan.nextInt(); ArrayList<Edge> graph[] = new ArrayList[n]; for(int i = 0;i<n;i++) { graph[i] = new ArrayList<>(); } Edge edges[] = new Edge[n-1]; for(int i = 0;i<n-1;i++) { int u = scan.nextInt()-1, v = scan.nextInt()-1; if(u > v) { int temp = u; u = v; v = temp; } edges[i] = new Edge(u, v); graph[u].add(edges[i]); graph[v].add(edges[i]); } boolean possible = true; int start = 0; for(int i = 0;i<n;i++) { ArrayList<Edge> edge = graph[i]; if(edge.size() == 1) start = i; if(edge.size() > 2) { possible = false; } // System.out.print(edge + ", "); } // System.out.println(); if(!possible) { output.println(-1); continue; } int cur = start; cur^= graph[start].get(0).v; cur^= graph[start].get(0).u; Edge edge = graph[start].get(0); graph[start].get(0).weight = 2; int i = 1; while(true) { if(graph[cur].size() == 1) { // graph[cur].get(0).weight = i%2+2; break; } if(edge == graph[cur].get(0)) { edge = graph[cur].get(1); } else edge = graph[cur].get(0); cur^= edge.v; cur^= edge.u; edge.weight = i%2+2; i++; } for(Edge ed : edges) { output.print(ed.weight + " "); } output.println(); } output.flush(); } public static int[] sort(int arr[]) { List<Integer> list = new ArrayList<>(); for(int i:arr) list.add(i); Collections.sort(list); for(int i = 0;i<list.size();i++) arr[i] = list.get(i); return arr; } public static int gcd(int a, int b) { if(a == 0) return b; return gcd(b%a, a); } public static void printArray(int arr[]) { for(int i:arr) System.out.print(i+" "); System.out.println(); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
6a1cc370b6785c1792b8aa4c86adcba6
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static int N = 100010, M = 2 * N; static int MOD = (int)1e9 + 7; static double EPS = 1e-7; static int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1}; static int h[] = new int[N], to[] = new int[M], ne[] = new int[M], w[] = new int[M], idx; static boolean st[] = new boolean[N]; static int a[] = new int[N], res[] = new int[N]; static int n; static void add(int a, int b) { to[idx] = b; ne[idx] = h[a]; h[a] = idx ++ ; } static void dfs(int u, int c) { for(int i = h[u]; i != -1; i = ne[i]) { int j = to[i]; if(!st[j]) { st[j] = true; res[i / 2] = c; // System.out.println(i / 2 + " " + c); dfs(j, 5 - c); } } } public static void main(String[] args) throws IOException { InputReader sc = new InputReader(); int T = sc.nextInt(); while(T -- > 0) { int n = sc.nextInt(); int d[] = new int[n + 1]; // Arrays.fill(h, -1); for(int i = 0; i <= n; i ++ ) h[i] = -1; // Arrays.fill(st, false); for(int i = 0; i <= n; i ++ ) st[i] = false; idx = 0; for(int i = 0; i < n - 1; i ++ ) { int a = sc.nextInt(); int b = sc.nextInt(); d[a] ++ ; d[b] ++ ; add(a, b); add(b, a); } boolean is = true; for(int i = 1; i <= n; i ++ ) if(d[i] >= 3) is = false; if(is) { int root = -1; for(int i = 1; i <= n; i ++ ) { // System.out.println(d[i]); if(d[i] == 1) { root = i; // System.out.println(i); break; } } // System.out.println(root); st[root] = true; dfs(root, 2); for(int i = 0; i < n - 1; i ++ ) System.out.print(res[i] + " "); System.out.println(); } else System.out.println(-1); } } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static int lcm(int a, int b) { return (a * b) / gcd(a, b); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
5da00a9ca344b1daf6086be88599ddab
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
// package CodeForces.RoadMap.Diff1400; import java.util.*; import java.io.*; /** * @author SyedAli * @createdAt 29-04-2022, Friday, 10:53 */ public class NotAssigning { static List<Integer> adj[]; static Map<String, Integer> prime; static boolean vis[]; static void dfs(int u, int val) { vis[u] = true; for (int v : adj[u]) { if (vis[v]) continue; prime.put(u + ":" + v, val); prime.put(v + ":" + u, val); dfs(v, val == 2 ? 3 : 2); } } static String solve(int n, List<int[]> edges) { prime = new HashMap<>(); adj = new ArrayList[n]; vis = new boolean[n]; Arrays.setAll(adj, idx -> new ArrayList<>()); boolean isPossible = true; List<Integer> start = new ArrayList<>(); for (int edge[] : edges) { int u = edge[0], v = edge[1]; adj[u].add(v); adj[v].add(u); } for (int i = 0; i < n; i++) { int size = adj[i].size(); if (size == 1) start.add(i); if (size > 2) isPossible = false; } if (!isPossible) return "-1"; for (int u : start) { if (vis[u]) continue; dfs(u, 3); } StringBuilder sb = new StringBuilder(); for (int edge[] : edges) { int u = edge[0], v = edge[1]; sb.append(prime.getOrDefault(u + ":" + v, 2) + " "); } return sb.toString(); } public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); int tests = sc.nextInt(); StringBuilder sb = new StringBuilder(); while (tests-- > 0) { int n = sc.nextInt(); List<int[]> edges = new ArrayList<>(); for (int i = 1; i < n; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; edges.add(new int[]{u, v}); } String res = solve(n, edges); sb.append(res + "\n"); } System.out.println(sb.toString()); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
8cc6572a53db59d92ba59663f004d93d
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.StringTokenizer; public class CodeForces { static ArrayList<ArrayList<Integer>> graph=new ArrayList<>(); static HashMap<Pair,Integer> map = new HashMap<>(); static int [] visited; static int lowest(int i){ visited[i]++; if(graph.get(i).size()==1){ return i; } if(visited[graph.get(i).get(0)]==0){ return lowest(graph.get(i).get(0)); } else { return lowest(graph.get(i).get(1)); } } static void solve (int low,int k){ visited[low]++; // if(graph.get(low).size()==1) return; if(visited[graph.get(low).get(0)]==0){ map.put(new Pair(Math.min(low,graph.get(low).get(0)),Math.max(low,graph.get(low).get(0))),2+k%2); solve(graph.get(low).get(0),k+1); } else if(graph.get(low).size()>1&& visited[graph.get(low).get(1)]==0){ map.put(new Pair(Math.min(low,graph.get(low).get(1)),Math.max(low,graph.get(low).get(1))),2+k%2); solve(graph.get(low).get(1),k+1); } } public static void main(String[] args) { // StringBuilder sbd = new StringBuilder(); // PrintWriter out = new PrintWriter("output.txt"); // File input = new File("input.txt"); // FastScanner fs = new FastScanner(input); // FastScanner fs = new FastScanner(); // Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int testNumber =fs.nextInt(); // ArrayList<Integer> arr = new ArrayList<>(); for (int T =0;T<testNumber;T++){ // StringBuffer sbf = new StringBuffer(); int n= fs.nextInt(); boolean res=true; Pair [] arr = new Pair[n-1]; visited=new int[n+2]; graph.clear(); map.clear(); for (int i=0;i<n;i++)graph.add(new ArrayList<>()); for (int i=0;i<n-1;i++){ int u =fs.nextInt()-1; int v=fs.nextInt()-1; arr[i]=new Pair(Math.min(u, v),Math.max(u,v)); graph.get(u).add(v); graph.get(v).add(u); if(graph.get(u).size()>2||graph.get(v).size()>2)res=false; } if(!res){ out.print("-1\n"); } else { int low = lowest(0); visited=new int[n+2]; solve(low,0); for (Pair p:arr){ out.print(map.get(p)+" "); } out.print("\n"); } } out.flush(); } static int FastPower(int x,int p){ if(p==0)return 1; int ans =FastPower(x, p/2); ans*=ans; if(p%2==1)ans*=x; return ans; } static ArrayList<Vertex> vertices = new ArrayList<>(); static class Vertex { public ArrayList<Integer>edges = new ArrayList<>(); public boolean isEnd=false; public Vertex (){ for(int i=0;i<26;i++){ edges.set(i, -1); } } } static class Trie { private int root=0; public Trie(){ vertices.add(new Vertex()); } public void InsertWord(String s){ int current = root; for(char c:s.toCharArray()){ int pos = c-'a'; if(vertices.get(current).edges.get(pos)==-1){ vertices.add(new Vertex()); Vertex x = vertices.get(current); x.edges.set(pos,vertices.size()-1); vertices.set(current, x); } current=vertices.get(current).edges.get(pos); } } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(){ br=new BufferedReader(new InputStreamReader(System.in)); st=new StringTokenizer(""); } public FastScanner(File f){ try { br=new BufferedReader(new FileReader(f)); st=new StringTokenizer(""); } catch(FileNotFoundException e){ br=new BufferedReader(new InputStreamReader(System.in)); st=new StringTokenizer(""); } } String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readLongArray(int n) { long[] a =new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } public static long factorial(int n){ if(n==0)return 1; return (long)n*factorial(n-1); } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } static void sort (int[]a){ ArrayList<Integer> b = new ArrayList<>(); for(int i:a)b.add(i); Collections.sort(b); for(int i=0;i<b.size();i++){ a[i]=b.get(i); } } static void sortReversed (int[]a){ ArrayList<Integer> b = new ArrayList<>(); for(int i:a)b.add(i); Collections.sort(b,new Comparator<Integer>(){ @Override public int compare(Integer o1, Integer o2) { return o2-o1; } }); for(int i=0;i<b.size();i++){ a[i]=b.get(i); } } static void sort (long[]a){ ArrayList<Long> b = new ArrayList<>(); for(long i:a)b.add(i); Collections.sort(b); for(int i=0;i<b.size();i++){ a[i]=b.get(i); } } static ArrayList<Integer> sieveOfEratosthenes(int n) { boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } ArrayList<Integer> ans = new ArrayList<>(); for (int i = 2; i <= n; i++) { if (prime[i] == true) ans.add(i); } return ans; } static int binarySearchSmallerOrEqual(int arr[], int key) { int n = arr.length; int left = 0, right = n; int mid = 0; while (left < right) { mid = (right + left) >> 1; if (arr[mid] == key) { while (mid + 1 < n && arr[mid + 1] == key) mid++; break; } else if (arr[mid] > key) right = mid; else left = mid + 1; } while (mid > -1 && arr[mid] > key) mid--; return mid; } static int binarySearchSmallerOrEqual(long arr[], long key) { int n = arr.length; int left = 0, right = n; int mid = 0; while (left < right) { mid = (right + left) >> 1; if (arr[mid] == key) { while (mid + 1 < n && arr[mid + 1] == key) mid++; break; } else if (arr[mid] > key) right = mid; else left = mid + 1; } while (mid > -1 && arr[mid] > key) mid--; return mid; } public static int binarySearchStrictlySmaller(int[] arr, int target) { int start = 0, end = arr.length-1; if(end == 0) return -1; if (target > arr[end]) return end; int ans = -1; while (start <= end) { int mid = (start + end) / 2; if (arr[mid] >= target) { end = mid - 1; } else { ans = mid; start = mid + 1; } } return ans; } public static int binarySearchStrictlySmaller(long[] arr, long target) { int start = 0, end = arr.length-1; if(end == 0) return -1; if (target > arr[end]) return end; int ans = -1; while (start <= end) { int mid = (start + end) / 2; if (arr[mid] >= target) { end = mid - 1; } else { ans = mid; start = mid + 1; } } return ans; } static int binarySearch(int arr[], int x) { int l = 0, r = arr.length - 1; while (l <= r) { int m = l + (r - l) / 2; if (arr[m] == x) return m; if (arr[m] < x) l = m + 1; else r = m - 1; } return -1; } static int binarySearch(long arr[], long x) { int l = 0, r = arr.length - 1; while (l <= r) { int m = l + (r - l) / 2; if (arr[m] == x) return m; if (arr[m] < x) l = m + 1; else r = m - 1; } return -1; } static void init(int[]arr,int val){ for(int i=0;i<arr.length;i++){ arr[i]=val; } } static void init(int[][]arr,int val){ for(int i=0;i<arr.length;i++){ for(int j=0;j<arr[i].length;j++){ arr[i][j]=val; } } } static void init(long[]arr,long val){ for(int i=0;i<arr.length;i++){ arr[i]=val; } } static<T> void init(ArrayList<ArrayList<T>>arr,int n){ for(int i=0;i<n;i++){ arr.add(new ArrayList()); } } static int binarySearchStrictlySmaller(ArrayList<Pair> arr, int target) { int start = 0, end = arr.size()-1; if(end == 0) return -1; if (target > arr.get(end).y) return end; int ans = -1; while (start <= end) { int mid = (start + end) / 2; if (arr.get(mid).y >= target) { end = mid - 1; } else { ans = mid; start = mid + 1; } } return ans; } static int binarySearchStrictlyGreater(int[] arr, int target) { int start = 0, end = arr.length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; if (arr[mid] <= target) { start = mid + 1; } else { ans = mid; end = mid - 1; } } return ans; } public static long pow(long n, long pow) { if (pow == 0) { return 1; } long retval = n; for (long i = 2; i <= pow; i++) { retval *= n; } return retval; } static String reverse(String s){ StringBuffer b = new StringBuffer(s); b.reverse(); return b.toString(); } static String charToString (char[] arr){ String t=""; for(char c :arr){ t+=c; } return t; } int[] copy (int [] arr , int start){ int[] res = new int[arr.length-start]; for (int i=start;i<arr.length;i++)res[i-start]=arr[i]; return res; } static int[] swap(int [] A,int l,int r){ int[] B=new int[A.length]; for (int i=0;i<l;i++){ B[i]=A[i]; } int k=0; for (int i=r;i>=l;i--){ B[l+k]=A[i]; k++; } for (int i=r+1;i<A.length;i++){ B[i]=A[i]; } return B; } static int mex (int[] d){ int [] a = Arrays.copyOf(d, d.length); sort(a); if(a[0]!=0)return 0; int ans=1; for(int i=1;i<a.length;i++){ if(a[i]==a[i-1])continue; if(a[i]==a[i-1]+1)ans++; else break; } return ans; } static int[] mexes(int[] arr){ int[] freq = new int [100000+7]; for (int i:arr)freq[i]++; int maxMex =0; for (int i=0;i<=100000+7;i++){ if(freq[i]!=0)maxMex++; else break; } int []ans = new int[arr.length]; ans[arr.length-1] = maxMex; for (int i=arr.length-2;i>=0;i--){ freq[arr[i+1]]--; if(freq[arr[i+1]]<=0){ if(arr[i+1]<maxMex) maxMex=arr[i+1]; ans[i]=maxMex; } else { ans[i]=ans[i+1]; } } return ans; } static int [] freq (int[]arr,int max){ int []b = new int[max]; for (int i:arr)b[i]++; return b; } static int[] prefixSum(int[] arr){ int [] a = new int[arr.length]; a[0]=arr[0]; for (int i=1;i<arr.length;i++)a[i]=a[i-1]+arr[i]; return a; } static class Pair { int x; int y; public int extra; public Pair(int x,int y){ this.x=x; this.y=y; } public Pair(int x,int y,int extra){ this.x=x; this.y=y; this.extra=extra; } @Override public boolean equals(Object o) { if(o instanceof Pair){ if(o.hashCode()!=hashCode()){ return false; } else { return x==((Pair)o).x&&y==((Pair)o).y; } } return false; } @Override public int hashCode() { return x+2*y; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
7191fb6461c3a9008df7d29a981338ce
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.awt.Container; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class Main { static ArrayList<ArrayList<Integer>> a ; static HashMap<String,Integer> ans; static boolean visited[]; public static boolean check() { for (ArrayList<Integer> arrayList : a) { if(arrayList.size()>2) { return true; } } return false; } static int set = 3; public static void DFS(int value ) { visited[value] = true; for (Integer integer : a.get(value)) { if(!visited[integer]) { int left = value+1; int right = integer+1; String s = left+" "+right; ans.put(s, set); if(set==2) { set = 3; } else set = 2; DFS(integer); } } } public static void main(String[] args) { FastScanner input = new FastScanner(); int tc = input.nextInt(); work: while (tc-- > 0) { set= 3; int n = input.nextInt(); a = new ArrayList<>(); visited = new boolean[n]; for (int i = 0; i <n; i++) { a.add(new ArrayList<>()); } ans = new HashMap<>(); int u[] = new int[n-1]; int v[] = new int[n-1]; TreeSet<Integer> set = new TreeSet<>(); int count[] = new int[n+1]; for (int i = 0; i <n; i++) { set.add(i); } for (int i = 0; i <n-1; i++) { u[i] = input.nextInt()-1; v[i] = input.nextInt()-1; a.get(u[i]).add(v[i]); a.get(v[i]).add(u[i]); count[u[i]]++; count[v[i]]++; if(count[u[i]]>=2&&set.contains(u[i])) { set.remove(u[i]); } if(count[v[i]]>=2&&set.contains(v[i])) { set.remove(v[i]); } } // System.out.println(set); if(check()) { System.out.println("-1"); } else { // System.out.println(ans); DFS(set.pollFirst()); StringBuilder result = new StringBuilder(); for (int i = 0; i < n-1; i++) { if(ans.containsKey((u[i]+1)+" "+(v[i]+1))) { result.append(ans.get((u[i]+1)+" "+(v[i]+1))+" "); } else { result.append(ans.get((v[i]+1)+" "+(u[i]+1))+" "); } } System.out.println(result); } } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
5841912208c0d12c8f18e2cf0151f229
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class NotAssigning{ static long mod = 1000000007L; static MyScanner sc = new MyScanner(); static void solve() { int n = sc.nextInt(); Edge edge[][] = new Edge[n+1][2]; boolean flag = false; for(int i = 1;i<=n-1;i++){ int u = sc.nextInt(); int v = sc.nextInt(); if(edge[u][0]==null){ edge[u][0] = new Edge(v,i); }else if(edge[u][1]==null){ edge[u][1] = new Edge(v,i); }else{ flag = true; } if(edge[v][0]==null){ edge[v][0] = new Edge(u,i); }else if(edge[v][1]==null){ edge[v][1] = new Edge(u,i); }else{ flag = true; } } if(flag){ out.println(-1); return; } int start = -1; for(int i = 1;i<=n;i++){ if(edge[i][0]!=null && edge[i][1]==null){ start = i; } } int wt[] = new int[n]; boolean visited[] = new boolean[n+1]; ArrayDeque<Integer> ar = new ArrayDeque<>(); ar.add(start); visited[start] = true; int num = 2; while(ar.isEmpty()==false){ int u = ar.removeLast(); if(edge[u][0]!=null){ if(visited[edge[u][0].node]==false){ wt[edge[u][0].num] = num; num = 5-num; visited[edge[u][0].node] = true; ar.add(edge[u][0].node); } } if(edge[u][1]!=null){ if(visited[edge[u][1].node]==false){ wt[edge[u][1].num] = num; num = 5-num; visited[edge[u][1].node] = true; ar.add(edge[u][1].node); } } } for(int i = 1;i<n;i++){ out.print(wt[i]+" "); } out.println(); } public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); while(t-- >0){ solve(); } // Stop writing your solution here. ------------------------------------- out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int[] readIntArray(int n){ int arr[] = new int[n]; for(int i = 0;i<n;i++){ arr[i] = Integer.parseInt(next()); } return arr; } long[] readLongArray(int n){ long arr[] = new long[n]; for(int i = 0;i<n;i++){ arr[i] = Long.parseLong(next()); } return arr; } 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; } } private static void sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } } class Edge{ int node; int num; Edge(int no,int n){ node = no; num = n; } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
c4d0ba53ebdeb7d573d3f5124f8ea51b
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; import java.util.TreeMap; public class NotAssigning { static ArrayList<Integer>[]adj; static boolean vis []; static int edges[]; // we need to check that every path of length 1 or 2 must be a prime number // Idea--> we will only use 2 , 3 for the weight assignment // no assignment will be valid if there exists a node connected to 3 others public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); vis= new boolean [n]; adj= new ArrayList[n]; TreeMap<Integer,Pair> idx = new TreeMap<>(); TreeMap<Pair,Integer> w= new TreeMap<>(); boolean notValid = false; for(int i =0;i<n;i++){ adj[i]= new ArrayList<>(); } for(int i =1;i<n;i++){ int u = sc.nextInt()-1; int v = sc.nextInt()-1; int max = Math.max(u,v); int min = Math.min(u,v); idx.put(i,new Pair(min , max)); adj[u].add(v); adj[v].add(u); if(adj[u].size()>2||adj[v].size()>2)notValid=true; } if(notValid){ pw.println(-1); continue; } dfs(0,2,w); // vis[0]=true; // dfs(adj[0].get(0),2,w); // if(adj[0].size()==2)dfs(adj[0].get(1),3,w); for(int i =1;i<n;i++){ pw.print(w.get(idx.get(i))+" "); } pw.println(); } pw.close(); } static void dfs(int node , int w , TreeMap<Pair , Integer>weight){ vis[node]=true; int i =0; for(int x : adj[node]){ if(!vis[x]) { int min = Math.min(x , node); int max = Math.max(x , node); if(i%2==0){ weight.put(new Pair(min , max),w); dfs(x, 5-w,weight); } else{ weight.put(new Pair(min , max),5-w); dfs(x, w, weight); } i++; } } } static class Pair implements Comparable<Pair>{ int x; int y ; Pair(int x , int y ){ this.x=x; this.y=y; } @Override public int compareTo(Pair o) { if(this.x==o.x)return this.y-o.y; return this.x-o.x; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } 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 Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
eb09d05574ddbbd854735a0efd96571c
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int t=0;t<T;t++){ solve(sc); } } static class Edge{ public int node; public int index; Edge(int node, int index){ this.node = node; this.index = index; } } public static void solve(Scanner sc){ int V = sc.nextInt(); Boolean[] visited = new Boolean[V]; LinkedList<Edge>[] adj = new LinkedList[V]; for(int v=0;v<V;v++){ visited[v] = false; } for(int v=0;v<V;v++){ adj[v] = new LinkedList(); } for(int i=0;i<V-1;i++){ int u = sc.nextInt()-1; int v = sc.nextInt()-1; adj[u].add(new Edge(v,i)); adj[v].add(new Edge(u,i)); } //gotta go find the end or start int start = -1; for(int v=0;v<V;v++){ if(adj[v].size() == 1){ start = v; }else if(adj[v].size() > 2){ System.out.println("-1"); return; } } int[] weight = new int[V-1]; // int curNode = start; int prevNode = -1; visited[start] = true; for(int v=0;v<V;v++){ for(Edge e : adj[start]){ if(!visited[e.node]){ if(v % 2 == 0){ weight[e.index] = 2; }else{ weight[e.index] = 5; } visited[e.node] = true; start = e.node; } } } for(int w : weight){ System.out.print(w + " "); } System.out.println(""); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
48f9d9ed8acab37877e8ee0dab3a39d7
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
/* * Everything is Hard * Before Easy * Jai Mata Dii */ import java.util.*; import java.io.*; public class Main { static class FastReader{ BufferedReader br;StringTokenizer st;public FastReader(){br = new BufferedReader(new InputStreamReader(System.in));}String next(){while (st == null || !st.hasMoreElements()){try{st = new StringTokenizer(br.readLine());}catch (IOException e){e.printStackTrace();}}return st.nextToken();}int nextInt(){ return Integer.parseInt(next());}long nextLong(){return Long.parseLong(next());}double nextDouble(){return Double.parseDouble(next());}String nextLine(){String str = ""; try{str = br.readLine(); } catch (IOException e) {e.printStackTrace();} return str; }} static long mod = (long)(1e9+7); // static long mod = 998244353; // static Scanner sc = new Scanner(System.in); static FastReader sc = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static int dia; public static void main (String[] args) { int ttt = 1; ttt = sc.nextInt(); z :for(int tc=1;tc<=ttt;tc++){ int n = sc.nextInt(); List<Integer> tre[] = new ArrayList[n+1]; ini(tre); List<int[]> edges = new ArrayList<>(); for(int i=1;i<n;i++) { int u = sc.nextInt(); int v = sc.nextInt(); tre[u].add(v); tre[v].add(u); int cur[] = new int[] {u, v}; Arrays.sort(cur); edges.add(cur); } boolean is = true; for(int i=1;i<=n;i++) { if(tre[i].size() > 2) { is = false; } } if(!is) { out.write("-1\n"); continue; } HashMap<List<Integer>, Integer> hm = new HashMap<>(); dfs(1, 1, 0, tre, hm); for(int i=0;i<n-1;i++) { out.write(hm.get(Arrays.asList(edges.get(i)[0], edges.get(i)[1]))+" "); } out.write("\n"); } out.close(); } private static void dfs(int node, int par, int prev, List<Integer>[] tre, HashMap<List<Integer>, Integer> hm) { int cur = 0; if(prev == 0) cur = 2; if(prev == 2) cur = 3; if(prev == 3) cur = 2; for(int adj : tre[node]) { if(adj != par) { int min = Math.min(adj, node); int max = Math.max(adj, node); hm.put(Arrays.asList(min, max), cur); dfs(adj, node, cur, tre, hm); if(cur == 2) cur = 3; else cur = 2; } } } static long pow(long a, long b){long ret = 1;while(b>0){if(b%2 == 0){a = (a*a)%mod;b /= 2;}else{ret = (ret*a)%mod;b--;}}return ret%mod;} static long gcd(long a,long b){if(b==0) return a; return gcd(b,a%b); } private static void sort(int[] a) {List<Integer> k = new ArrayList<>();for(int val : a) k.add(val);Collections.sort(k);for(int i=0;i<a.length;i++) a[i] = k.get(i);} private static void ini(List<Integer>[] tre2){for(int i=0;i<tre2.length;i++){tre2[i] = new ArrayList<>();}} private static void init(List<int[]>[] tre2){for(int i=0;i<tre2.length;i++){tre2[i] = new ArrayList<>();}} private static void sort(long[] a) {List<Long> k = new ArrayList<>();for(long val : a) k.add(val);Collections.sort(k);for(int i=0;i<a.length;i++) a[i] = k.get(i);} }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
8e8d15a38757708009c65880d2a9fc6b
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class A { //--------------------------INPUT READER---------------------------------// static class fs { public BufferedReader br; StringTokenizer st = new StringTokenizer(""); public fs() { this(System.in); } public fs(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long nn) { int n = (int) nn; int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } long[] nal(long nn) { int n = (int) nn; long[] l = new long[n]; for(int i = 0; i < n; i++) l[i] = nl(); return l; } } //-----------------------------------------------------------------------// //---------------------------PRINTER-------------------------------------// static class Printer { static PrintWriter w; public Printer() {this(System.out);} public Printer(OutputStream os) { w = new PrintWriter(os); } public void p(int i) {w.println(i);} public void p(long l) {w.println(l);} public void p(double d) {w.println(d);} public void p(String s) { w.println(s);} public void pr(int i) {w.print(i);} public void pr(long l) {w.print(l);} public void pr(double d) {w.print(d);} public void pr(String s) { w.print(s);} public void pl() {w.println();} public void close() {w.close();} } //-----------------------------------------------------------------------// //--------------------------VARIABLES------------------------------------// static fs sc = new fs(); static OutputStream outputStream = System.out; static Printer w = new Printer(outputStream); static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; static long mod = 1000000007; //-----------------------------------------------------------------------// //--------------------------ADMIN_MODE-----------------------------------// private static void ADMIN_MODE() throws IOException { if (System.getProperty("ONLINE_JUDGE") == null) { w = new Printer(new FileOutputStream("output.txt")); sc = new fs(new FileInputStream("input.txt")); } } //-----------------------------------------------------------------------// //----------------------------START--------------------------------------// public static void main(String[] args) throws IOException { ADMIN_MODE(); int t = sc.ni();while(t-->0) solve(); w.close(); } static int[] res; static List<List<Integer>> graph; static boolean two = true; static HashMap<pr<Integer, Integer>, Integer> hm; static void solve() throws IOException { int n = sc.ni(); graph = new ArrayList<>(); res = new int[n-1]; hm = new HashMap<>(); for(int i = 0; i <= n; i++) { graph.add(new ArrayList<>()); } boolean f = false; for(int i = 0; i < n-1; i++) { int a = sc.ni(), b = sc.ni(); graph.get(a).add(b); graph.get(b).add(a); if(graph.get(a).size() > 2 || graph.get(b).size() > 2) f = true; hm.put(new pr<>(a, b), i); hm.put(new pr<>(b, a), i); } if(f) { w.p(-1); return; } int one = 0; for(int i = 0; i < n; i++) { if(graph.get(i).size() == 1) { one = i; break; } } dfs(one, -1); for(int i: res) { w.pr(i+" "); } w.pl(); } static void dfs(int at, int pt) { List<Integer> li = graph.get(at); if(pt != -1) { res[hm.get(new pr<>(at, pt))] = two?2:3; two = !two; } for(int to: li) { if(to == pt) continue; dfs(to, at); } } static class pr <T, V> { T a; V b; public pr(T a, V b) { this.a = a; this.b = b; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof pr)) return false; pr<?, ?> pr = (pr<?, ?>) o; return a.equals(pr.a) && b.equals(pr.b); } @Override public int hashCode() { return Objects.hash(a, b); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
b184fc9272324183bbbb27b0b73896b3
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class A { //--------------------------INPUT READER---------------------------------// static class fs { public BufferedReader br; StringTokenizer st = new StringTokenizer(""); public fs() { this(System.in); } public fs(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long nn) { int n = (int) nn; int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } long[] nal(long nn) { int n = (int) nn; long[] l = new long[n]; for(int i = 0; i < n; i++) l[i] = nl(); return l; } } //-----------------------------------------------------------------------// //---------------------------PRINTER-------------------------------------// static class Printer { static PrintWriter w; public Printer() {this(System.out);} public Printer(OutputStream os) { w = new PrintWriter(os); } public void p(int i) {w.println(i);} public void p(long l) {w.println(l);} public void p(double d) {w.println(d);} public void p(String s) { w.println(s);} public void pr(int i) {w.print(i);} public void pr(long l) {w.print(l);} public void pr(double d) {w.print(d);} public void pr(String s) { w.print(s);} public void pl() {w.println();} public void close() {w.close();} } //-----------------------------------------------------------------------// //--------------------------VARIABLES------------------------------------// static fs sc = new fs(); static OutputStream outputStream = System.out; static Printer w = new Printer(outputStream); static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; static long mod = 1000000007; //-----------------------------------------------------------------------// //--------------------------ADMIN_MODE-----------------------------------// private static void ADMIN_MODE() throws IOException { if (System.getProperty("ONLINE_JUDGE") == null) { w = new Printer(new FileOutputStream("output.txt")); sc = new fs(new FileInputStream("input.txt")); } } //-----------------------------------------------------------------------// //----------------------------START--------------------------------------// public static void main(String[] args) throws IOException { ADMIN_MODE(); int t = sc.ni();while(t-->0) solve(); w.close(); } static int[] res; static List<List<Integer>> graph; static boolean two = true; static HashMap<pr, Integer> hm; static void solve() throws IOException { int n = sc.ni(); graph = new ArrayList<>(); res = new int[n-1]; hm = new HashMap<>(); for(int i = 0; i <= n; i++) { graph.add(new ArrayList<>()); } boolean f = false; for(int i = 0; i < n-1; i++) { int a = sc.ni(), b = sc.ni(); graph.get(a).add(b); graph.get(b).add(a); if(graph.get(a).size() > 2 || graph.get(b).size() > 2) f = true; hm.put(new pr(a, b), i); hm.put(new pr(b, a), i); } if(f) { w.p(-1); return; } int one = 0; for(int i = 0; i < n; i++) { if(graph.get(i).size() == 1) { one = i; break; } } dfs(one, -1); for(int i: res) { w.pr(i+" "); } w.pl(); } static void dfs(int at, int pt) { List<Integer> li = graph.get(at); if(pt != -1) { res[hm.get(new pr(at, pt))] = two?2:3; two = !two; } for(int to: li) { if(to == pt) continue; dfs(to, at); } } static class pr { int x, y; public pr(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof pr)) return false; pr pr = (pr) o; return x == pr.x && y == pr.y; } @Override public int hashCode() { return Objects.hash(x, y); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
a88e230a41fd0095fad60cb3ebf9aa6e
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
//package codeforce.div2; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import static java.util.stream.Collectors.joining; /** * @author pribic (Priyank Doshi) * @see <a href="https://codeforces.com/contest/1627/problem/A" target="_top">https://codeforces.com/contest/1627/problem/A</a> * @since 15/01/22 9:08 PM */ public class C { static FastScanner sc = new FastScanner(System.in); static ArrayList<int[]>[] al; static int[] degree; static int[] weights; public static void main(String[] args) { try (PrintWriter out = new PrintWriter(System.out)) { int T = sc.nextInt(); for (int tt = 1; tt <= T; tt++) { int n = sc.nextInt(); al = new ArrayList[n]; degree = new int[n]; weights = new int[n - 1]; for (int i = 0; i < n; i++) al[i] = new ArrayList<>(); boolean degMoreThan2 = false; for (int i = 0; i < n - 1; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; if (v < u) { // we want u < v int t = u; u = v; v = t; } al[u].add(new int[]{v, i}); al[v].add(new int[]{u, i}); degree[u]++; degree[v]++; degMoreThan2 = degMoreThan2 || degree[u] > 2 || degree[v] > 2; } if (degMoreThan2) { System.out.println(-1); } else { for (int i = 0; i < n; i++) { if (al[i].size() == 1) { dfs(i, -1, 2); break; } } // print for (long w : weights) { System.out.print(w + " "); } System.out.println(); } } } } private static void dfs(int node, int parent, int prime) { // we will assign this prime for (int[] neigh : al[node]) { if (neigh[0] != parent) { //we have an edge from node to neigh weights[neigh[1]] = prime; dfs(neigh[0], node, 7 - prime); } } } static 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), 32768); } 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()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
f63766d7b6f1b1cd1f28d68f1d598458
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
//package codeforce.div2; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import static java.util.stream.Collectors.joining; /** * @author pribic (Priyank Doshi) * @see <a href="https://codeforces.com/contest/1627/problem/A" target="_top">https://codeforces.com/contest/1627/problem/A</a> * @since 15/01/22 9:08 PM */ public class C { static FastScanner sc = new FastScanner(System.in); static ArrayList<int[]>[] al; static int[] degree; static int[] weights; public static void main(String[] args) { try (PrintWriter out = new PrintWriter(System.out)) { int T = sc.nextInt(); for (int tt = 1; tt <= T; tt++) { int n = sc.nextInt(); al = new ArrayList[n]; degree = new int[n]; weights = new int[n - 1]; for (int i = 0; i < n; i++) al[i] = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; if (v < u) { // we want u < v int t = u; u = v; v = t; } al[u].add(new int[]{v, i}); al[v].add(new int[]{u, i}); degree[u]++; degree[v]++; } boolean degMoreThan2 = Arrays.stream(degree).anyMatch(num -> num > 2); if (degMoreThan2) { System.out.println(-1); } else { for (int i = 0; i < n; i++) { if (al[i].size() == 1) { dfs(i, -1, 2); break; } } // print for (long w : weights) { System.out.print(w + " "); } System.out.println(); } } } } private static void dfs(int node, int parent, int prime) { // we will assign this prime for (int[] neigh : al[node]) { if (neigh[0] != parent) { //we have an edge from node to neigh weights[neigh[1]] = prime; dfs(neigh[0], node, 7 - prime); } } } static 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), 32768); } 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()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
659e0e3ee1742d0779ac15063a302a24
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
//package codeforce.div2; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import static java.util.stream.Collectors.joining; /** * @author pribic (Priyank Doshi) * @see <a href="https://codeforces.com/contest/1627/problem/A" target="_top">https://codeforces.com/contest/1627/problem/A</a> * @since 15/01/22 9:08 PM */ public class C { static FastScanner sc = new FastScanner(System.in); static ArrayList<int[]>[] al; static int[] degree; static int[] weights; public static void main(String[] args) { try (PrintWriter out = new PrintWriter(System.out)) { int T = sc.nextInt(); for (int tt = 1; tt <= T; tt++) { int n = sc.nextInt(); al = new ArrayList[n]; degree = new int[n]; weights = new int[n - 1]; for (int i = 0; i < n; i++) al[i] = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; if (v < u) { // we want u < v int t = u; u = v; v = t; } al[u].add(new int[]{v, i}); al[v].add(new int[]{u, i}); degree[u]++; degree[v]++; } boolean degMoreThan2 = Arrays.stream(degree).anyMatch(num -> num > 2); if (degMoreThan2) { System.out.println(-1); } else { if (al[0].size() == 1) { dfs(0, -1, 2); } else { int[] left = al[0].get(0); int[] right = al[0].get(1); //assign 2 to left weights[left[1]] = 2; dfs(left[0], 0, 5); //assign 5 to right weights[right[1]] = 5; dfs(right[0], 0, 2); } // print for (long w : weights) { System.out.print(w + " "); } System.out.println(); } } } } private static void dfs(int node, int parent, int prime) { // we will assign this prime for (int[] neigh : al[node]) { if (neigh[0] != parent) { //we have an edge from node to neigh weights[neigh[1]] = prime; dfs(neigh[0], node, 7 - prime); } } } static 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), 32768); } 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()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
671a9a9b86b955d24bd1a1bb248d48c4
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
//package codeforce.div2; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import static java.util.stream.Collectors.joining; /** * @author pribic (Priyank Doshi) * @see <a href="https://codeforces.com/contest/1627/problem/A" target="_top">https://codeforces.com/contest/1627/problem/A</a> * @since 15/01/22 9:08 PM */ public class C { static FastScanner sc = new FastScanner(System.in); static ArrayList<Integer>[] al; static int[] degree; static Map<Long, Integer> weights; static List<Long> order; public static void main(String[] args) { try (PrintWriter out = new PrintWriter(System.out)) { int T = sc.nextInt(); for (int tt = 1; tt <= T; tt++) { int n = sc.nextInt(); al = new ArrayList[n]; degree = new int[n]; weights = new HashMap<>(); order = new ArrayList<>(); for (int i = 0; i < n; i++) al[i] = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; if (v < u) { // we want u < v int t = u; u = v; v = t; } al[u].add(v); al[v].add(u); degree[u]++; degree[v]++; order.add(hash(u, v)); } boolean degMoreThan2 = Arrays.stream(degree).anyMatch(num -> num > 2); if (degMoreThan2) { System.out.println(-1); } else { if (al[0].size() == 1) { dfs(0, -1, 2); } else { int left = al[0].get(0); int right = al[0].get(1); //assign 2 to left weights.put(hash(0, left), 2); dfs(left, 0, 5); //assign 5 to right weights.put(hash(0, right), 5); dfs(right, 0, 2); } // print for (long hash : order) { System.out.print(weights.get(hash) + " "); } System.out.println(); } } } } private static void dfs(int node, int parent, int prime) { // we will assign this prime for (Integer neigh : al[node]) { if (neigh != parent) { //we have an edge from node to neigh weights.put(hash(node, neigh), prime); dfs(neigh, node, prime == 2 ? 5 : 2); } } } static long hash(int u, int v) { if (v < u) { // we want u < v int t = u; u = v; v = t; } return u * 100001L + v; } static 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), 32768); } 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()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
0b16229c93877a3bd46be6f86c295709
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.lang.invoke.MethodHandles; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Random; import java.util.TreeSet; public final class CF_766_D2_C { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static long mod=1000000007; // Global vars static BufferedWriter out; static InputReader reader; static long powerMod(long b,long e,long m){ long x=1; while (e>0) { if (e%2==1) x=(b*x)%m; b=(b*b)%m; e=e/2; } return x; } static long inv(long x,long m){ return powerMod(x,m-2,m); } static class Composite implements Comparable<Composite>{ int d; int a; int b; public int compareTo(Composite X) { if (d!=X.d) return d-X.d; if (a!=X.a) return a-X.a; return b-X.b; } public Composite(int d, int a, int b) { this.d = d; this.a = a; this.b = b; } } static void dfs(ArrayList<Integer>[] friends,ArrayList<Integer>[] edge,int[] val) { int st=0; int n=friends.length; int[] color=new int[n]; // special case for 0 anc[0]=-1; if (friends[0].size()==1) { //log("case 1"); stack[st++]=0; color[0]=2; } else { //log("case 2"); int x=friends[0].get(0); anc[x]=0; int e=edge[0].get(0); val[e]=2; color[x]=2; int y=friends[0].get(1); anc[y]=0; int f=edge[0].get(1); val[f]=3; color[y]=3; stack[st++]=x; stack[st++]=y; //log("e:"+e+" f:"+f); //log(val); } while (st>0) { int u=stack[--st]; for (int t=0;t<friends[u].size();t++) { int e=edge[u].get(t); int v=friends[u].get(t); if (v!=anc[u]) { //log("processing v:"+v+" from edge:"+e); anc[v]=u; if (color[u]==2) color[v]=3; else color[v]=2; val[e]=color[v]; stack[st++]=v; } } } } static int[] stack; static int[] color; static int[] anc; static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader = new InputReader(System.in); int NX=100001; stack=new int[NX]; anc=new int[NX]; color=new int[NX]; //test(); int T=reader.readInt(); for (int t=0;t<T;t++) { int n=reader.readInt(); ArrayList<Integer>[] friends=new ArrayList[n]; ArrayList<Integer>[] edge=new ArrayList[n]; for (int u=0;u<n;u++) { friends[u]=new ArrayList<Integer>(); edge[u]=new ArrayList<Integer>(); } for (int i=0;i<n-1;i++) { int u=reader.readInt()-1; int v=reader.readInt()-1; friends[u].add(v); friends[v].add(u); edge[u].add(i); edge[v].add(i); } boolean ok=true; for (int u=0;u<n;u++) { if (friends[u].size()>2) { ok=false; break; } } if (!ok) { output("-1"); } else { int[] val=new int[n-1]; dfs(friends,edge,val); StringBuffer sb=new StringBuffer(); for (int x:val) sb.append(x+" "); output(sb); } } try { out.close(); } catch (Exception e) { } } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
25d425042e4466be7e223bc96c0cc433
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { // 一共有n个结点 int n = sc.nextInt(); // 所有边 List<Edge> list = new ArrayList<>(); // 边对索引的映射 Map<Edge, Integer> edgeMap = new HashMap<>(); // 图 Map<Integer, List<Integer>> map = new HashMap<>(); for (int i = 0; i < n - 1; i++) { int a = sc.nextInt(); int b = sc.nextInt(); Edge e = new Edge(a, b); list.add(e); edgeMap.put(e, list.size() - 1); List<Integer> list1 = map.getOrDefault(a, new ArrayList<>()); list1.add(b); map.put(a, list1); List<Integer> list2 = map.getOrDefault(b, new ArrayList<>()); list2.add(a); map.put(b, list2); } int max = map.values().stream().mapToInt(a -> a.size()).max().getAsInt(); // 一个点的度>2不行 if (max > 2) { System.out.println("-1"); } else { // 找到头结点 int cur = map.entrySet().stream() .filter(entry -> entry.getValue().size() == 1) .mapToInt(entry -> entry.getKey()).findAny().getAsInt(); // 从这里开始遍历 boolean[] vis = new boolean[n + 1]; vis[cur] = true; int[] res = new int[]{3, 2}; int cnt = 0; while (true) { // 找到下一个节点 List<Integer> nextList = map.get(cur); boolean flag = true; for (Integer next : nextList) { if (!vis[next]) { flag = false; vis[next] = true; // 找到边的索引 int idx = edgeMap.get(new Edge(cur, next)); Edge edge = list.get(idx); edge.weight = res[cnt++ % 2]; cur = next; } } if (flag) break; } StringBuilder sb = new StringBuilder(); for (Edge edge : list) { sb.append(edge.weight).append(" "); } System.out.println(sb); } } } static class Edge { int a; int b; int weight; public Edge(int a, int b) { this.a = Math.min(a, b); this.b = Math.max(a, b); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Edge edge = (Edge) o; return a == edge.a && b == edge.b; } @Override public int hashCode() { return Objects.hash(a, b); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
6af2eacecb8513d9eab8302bc7b9f756
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; public class _1627C { static Vector<Integer>[] adj; static LinkedHashMap<String,Integer> edges; static int count=0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n=sc.nextInt(); adj=new Vector[n]; for(int i=0;i<n;i++) adj[i]=new Vector<>(); int []degree=new int[n]; edges=new LinkedHashMap<>(); int max=-1; for(int i=0;i<n-1;i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; adj[u].add(v); adj[v].add(u); edges.put(u+":"+v , 0); degree[u]++; degree[v]++; max = Math.max(Math.max(degree[u], degree[v]), max); } if(max>2) System.out.println("-1"); else{ dfs(0,-1,2); // System.out.println(edges); for(Map.Entry<String,Integer> itr : edges.entrySet()) { System.out.print(itr.getValue()+" "); } System.out.println(); } } } static void dfs(int node,int par,int prev) { for (int child : adj[node]) { if (child == par) continue; prev = (prev == 2) ? 3 : 2; if (!edges.containsKey(node + ":" + child)) edges.put(child + ":" + node, prev); else edges.put(node + ":" + child, prev); dfs(child, node, prev); } } public static int gcd(int a, int b) { return (a == 0) ? b : gcd(b % a, a); } static int power(int x, int y) { int ans = 1; while (y > 0) { if ((y & 1) != 0) ans *= x; y = y >> 1; x *= x; } return ans; } public static List<Integer> sieve(int n) { List<Integer> primes = new LinkedList<>(); boolean[] composite = new boolean[n + 1]; for (int i = 2; i * i <= n; i++) for (int j = i * i; j <= n && !composite[i]; j += i) composite[j] = true; for (int j = 2; j < composite.length; j++) if (!composite[j]) primes.add(j); return primes; } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
15c57aaa0c82a1c61f950fa983dfa1ea
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import static java.lang.Math.*; import java.io.*; public class S { public static int surv = 0; public static void main(String args[])throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while(t > 0){ t--; int n = Integer.parseInt(br.readLine()); int a[][] = new int[n-1][2]; for(int i = 0; i < n-1; i++){ StringTokenizer st = new StringTokenizer(br.readLine()); a[i][0] = Integer.parseInt(st.nextToken()); a[i][1] = Integer.parseInt(st.nextToken()); } solve(a, n, sb); } System.out.print(sb.toString()); } final static int MOD = 1000000007; public static void solve(int a[][], int n, StringBuilder sb){ Map<Long, Integer> map = new HashMap<Long, Integer>(); int nei[] = new int[n+1]; Map<Integer, List<Integer>> g = new HashMap<>(); for(int i = 0; i < n-1; i++){ int u = a[i][0]; int v = a[i][1]; long key = (long)u + (long)v * 100001l; map.put(key, i); key = (long)v + (long)u * 100001l; map.put(key, i); if(!g.containsKey(u))g.put(u, new ArrayList<Integer>()); if(!g.containsKey(v))g.put(v, new ArrayList<Integer>()); g.get(u).add(v); g.get(v).add(u); nei[u]++; nei[v]++; } int start = -1; for(int i = 1; i <= n; i++){ if(nei[i] > 2){ sb.append(-1 + "\n"); return; } if(nei[i] == 1)start = i; } int ans[] = new int[n-1]; List<int[]> al = new ArrayList<int[]>(); dfs(g, start, -1, al, 2); for(int v[] : al){ long key = (long)v[0] + (long)v[1] * 100001l; ans[map.get(key)] = v[2]; //System.out.print(v[0] + " " + v[1] + " " + v[2]); //System.out.println(" " + map.get(v[0] + v[1] * 100001)); } /* for(int v : ans){ sb.append(v + " "); }*/ for(int i = 0; i < ans.length; i++){ String space = i < ans.length - 1 ? " " : ""; sb.append(ans[i] + space); } sb.append("\n"); } public static void dfs(Map<Integer, List<Integer>> g, int curr, int par, List<int[]> al, int val){ int nextVal = val == 2 ? 3 : 2; for(int nei : g.get(curr)){ if(nei != par){ //int key = curr + nei * 100001; //ans[map.get(key)] = val; al.add(new int[]{curr, nei, val}); dfs(g, nei, curr, al, nextVal); } } } public static int lower_bound(ArrayList<Integer> list, int val){ int l = 0; int r = list.size() - 1; int ans = -1; while(l <= r){ int mid = l + (r-l)/2; if(list.get(mid) >= val){ ans = list.get(mid); r = mid - 1; }else{ l = mid + 1; } } return ans; } public static int checkP(long n){ int ans = 0; while(n > 0){ ans += (n & 1); n >>= 1; } return ans; } public static List<int[]> primeFactorization(int n){ List<Integer> primes = sievePrimes(1000000); List<int[]> ans = new ArrayList<int[]>(); for(int i = 0; (long)primes.get(i)*(long)primes.get(i) <= n; i++){ int curr = primes.get(i); if(n % curr == 0){ int a[] = new int[]{curr, 0}; while(n % curr == 0){ n /= curr; a[1]++; } ans.add(a); } } if(n > 1){ ans.add(new int[]{n, 1}); } return ans; } public static List<Integer> sievePrimes(int limit){ boolean p[] = new boolean[limit+1]; for(int i = 2; i*i <= p.length; i++){ if(!p[i]){ for(int j = i*i; j < p.length; j += i){ p[j] = true; } } } List<Integer> primes = new ArrayList<Integer>(); for(int i = 2; i < p.length; i++){ if(!p[i])primes.add(i); } return primes; } public static long powerr(long base, long exp){ if(exp < 2)return base; if(exp % 2 == 0){ long ans = powerr(base, exp/2) % MOD; ans *= ans; ans %= MOD; return ans; }else{ return (((powerr(base, exp-1)) % MOD) * base) % MOD; } } public static long power(long a, long b){ if(b == 0)return 1l; long ans = power(a, b/2); ans *= ans; ans %= MOD; if(b % 2 != 0){ ans *= a; } return ans % MOD; } public static int logLong(long a){ int ans = 0; long b = 1; while(b < a){ b*=2; ans++; } return ans; } public static void sort(int a[]){ List<Integer> l = new ArrayList<Integer>(); for(int val : a){ l.add(val); } Collections.sort(l); int k = 0; for(int val : l){ a[k++] = val; } } public static void sortLong(long a[]){ List<Long> l = new ArrayList<Long>(); for(long val : a){ l.add(val); } Collections.sort(l); int k = 0; for(long val : l){ a[k++] = val; } } public static boolean isPal(String s){ int l = 0; int r = s.length() - 1; while(l <= r){ if(s.charAt(l) != s.charAt(r)){ return false; } l++; r--; } return true; } /* public static int gcd(int a, int b){ if(b > a){ int temp = a; a = b; b = temp; } if(b == 0)return a; return gcd(b, a%b); }*/ public static long gcd(long a, long b){ if(b > a){ long temp = a; a = b; b = temp; } if(b == 0)return a; return gcd(b, a%b); } // public static long lcm(long a, long b){ // return a * b/gcd(a, b); // } /*public static class DJSet{ public int a[]; public DJSet(int n){ this.a = new int[n]; Arrays.fill(a, -1); } public int find(int val){ if(a[val] >= 0){ a[val] = find(a[val]); return a[val]; }else{ return val; } } public boolean union(int val1, int val2){ int p1 = find(val1); int p2 = find(val2); if(p1 == p2){ return false; } int size1 = Math.abs(a[p1]); int size2 = Math.abs(a[p2]); if(size1 >= size2){ a[p2] = p1; a[p1] = (size1 + size2) * -1; }else{ a[p1] = p2; a[p2] = (size1 + size2) * -1; } return true; }*/ /* public static class DSU{ public int a[]; public DSU(int size){ this.a = new int[size]; Arrays.fill(a, -1); } public int find(int u){ if(a[u] < 0)return u; a[u] = find(a[u]); return a[u]; } public boolean union(int u, int v){ int p1 = find(u); int p2 = find(v); if(p1 == p2)return false; int size1 = a[p1] * -1; int size2 = a[p2] * -1; if(size1 >= size2){ a[p2] = p1; a[p1] = (size1 + size2) * -1; }else{ a[p1] = p2; a[p2] = (size1 + size2) * -1; } return true; } }*/ }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
cfa15c9758a4e952c2115f63a02fe39a
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; import java.lang.Math; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; public class Main { static PrintWriter pw; static Scanner sc; static StringBuilder ans; static long mod = 1000000000+7; static void pn(final Object arg) { pw.print(arg); pw.flush(); } /*-------------- for input in an value ---------------------*/ static int ni() { return sc.nextInt(); } static long nl() { return sc.nextLong(); } static double nd() { return sc.nextDouble(); } static String ns() { return sc.next(); } static String nLine() { return sc.nextLine(); } static void ap(int arg) { ans.append(arg); } static void ap(long arg) { ans.append(arg); } static void ap(String arg) { ans.append(arg); } static void ap(StringBuilder arg) { ans.append(arg); } static void apn() { ans.append("\n"); } static void apn(int arg) { ans.append(arg+"\n"); } static void apn(long arg) { ans.append(arg+"\n"); } static void apn(String arg) { ans.append(arg+"\n"); } static void apn(StringBuilder arg) { ans.append(arg+"\n"); } static void yes() { ap("Yes\n"); } static void no() { ap("No\n"); } /* for Dubuggin */ static void printArr(int ar[], int st , int end) { for(int i = st; i<=end; i++ ) ap(ar[i]+ "\n"); ap("\n"); } static void printArr(long ar[], int st , int end) { for(int i = st; i<=end; i++ ) ap(ar[i]+ "\n"); ap("\n"); } static void printArr(String ar[], int st , int end) { for(int i = st; i<=end; i++ ) ap(ar[i]+ "\n"); ap("\n"); } static void printIntegerList(List<Integer> ar, int st , int end) { for(int i = st; i<=end; i++ ) ap(ar.get(i)+ " "); ap("\n"); } static void printLongList(List<Long> ar, int st , int end) { for(int i = st; i<=end; i++ ) ap(ar.get(i)+ " "); ap("\n"); } static void printStringList(List<String> ar, int st , int end) { for(int i = st; i<=end; i++ ) ap(ar.get(i)+ " "); ap("\n"); } /*-------------- for input in an array ---------------------*/ static void readArray(int arr[]){ for(int i=0; i<arr.length; i++)arr[i] = ni(); } static void readArray(long arr[]){ for(int i=0; i<arr.length; i++)arr[i] = nl(); } static void readArray(String arr[]){ for(int i=0; i<arr.length; i++)arr[i] = ns(); } static void readArray(double arr[]){ for(int i=0; i<arr.length; i++)arr[i] = nd(); } /*-------------- File vs Input ---------------------*/ static void runFile() throws Exception { sc = new Scanner(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); } static void runIo() throws Exception { pw =new PrintWriter(System.out); sc = new Scanner(System.in); } static int log2(int n) { return (int)(Math.log(n) / Math.log(2)); } static boolean isPowerOfTwo (long x) { return x!=0 && ((x&(x-1)) == 0);} static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long nCr(long n, long r) { // Combinations if (n < r) return 0; if (r > n - r) { // because nCr(n, r) == nCr(n, n - r) r = n - r; } long ans = 1L; for (long i = 0; i < r; i++) { ans *= (n - i); ans /= (i + 1); } return ans; } static int countDigit(long n){return (int)Math.floor(Math.log10(n) + 1);} 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 boolean sv[] = new boolean[10002]; static void seive() { //true -> not prime // false->prime sv[0] = sv[1] = true; sv[2] = false; for(int i = 0; i< sv.length; i++) { if( !sv[i] && (long)i*(long)i < sv.length ) { for ( int j = i*i; j<sv.length ; j += i ) { sv[j] = true; } } } } static long kadensAlgo(long ar[]) { int n = ar.length; long pre = ar[0]; long ans = ar[0]; for(int i = 1; i<n; i++) { pre = Math.max(pre + ar[i], ar[i]); ans = Math.max(pre, ans); } return ans; } static long binpow( long a, long b) { long res = 1; while (b > 0) { if ( (b & 1) > 0){ res = (res * a); } a = (a * a); b >>= 1; } return res; } static long factorial(long n) { long res = 1, i; for (i = 2; i <= n; i++){ res = ((res%mod) * (i%mod))%mod; } return res; } static int getCountPrime(int n) { int ans = 0; while (n%2==0) { ans ++; n /= 2; } for (int i = 3; i *i<= n; i+= 2) { while (n%i == 0) { ans ++; n /= i; } } if(n > 1 ) ans++; return ans; } static void sort(int[] arr) { /* because Arrays.sort() uses quicksort which is dumb Collections.sort() uses merge sort */ ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } static void sort(long[] arr) { /* because Arrays.sort() uses quicksort which is dumb Collections.sort() uses merge sort */ ArrayList<Long> ls = new ArrayList<Long>(); for(Long x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } static int upperBound(long ar[], long k, int l, int r) { while (l <= r) { int m = (l + r) >> 1 ; if (ar[m] > k) { r = m - 1 ; } else { l = m + 1 ; } } return l ; } static int lowerBound(long ar[], long k, int l, int r) { while (l <= r) { int m = (l + r) >> 1 ; if (ar[m] >= k) { r = m - 1 ; } else { l = m + 1 ; } } return l ; } static void findDivisor(int n, ArrayList<Integer> al) { for(int i = 1; i*i <= n; i++){ if( n % i == 0){ if(n/i==i){ al.add(i); } else{ al.add(n/i); al.add(i); } } } } static class Pair{ int a; int b; Pair( int a, int b ){ this.a = a; this.b = b; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair pair = (Pair) o; return a == pair.a && b == pair.b; } @Override public int hashCode() { int result = a; result = 31 * result + b; return result; } } public static void main(String[] args) throws Exception { // runFile(); runIo(); int t; t = 1; t = sc.nextInt(); ans = new StringBuilder(); while( t-- > 0 ) { solve(); } pn(ans+""); } static boolean flag[]; static ArrayList<ArrayList<Integer>> ar; static Map<Pair, Integer> map; public static void solve ( ) { ar = new ArrayList<>(); map = new HashMap<>(); int n = ni(); for(int i = 0; i<=n; i++) { ar.add(new ArrayList<>()); } flag = new boolean[n+1]; int e [][] = new int[n-1][2]; for(int i = 0; i<n-1; i++) { int u = ni(); int v = ni(); e[i][0] = u; e[i][1] = v; ar.get(u).add(v); ar.get(v).add(u); } for(int i = 1; i<=n; i++){ if( ar.get(i).size() > 2 ) { apn("-1"); return; } } // for( int i = 1; i<=n ; i++ ) { // ap(i+" -> "); // for(Pair p : ar.get(i) ) { // ap(p.v+" "); // } // apn(); // } for(int i = 1; i<=n; i++) { if( ar.get(i).size() == 1 ) { dfs(i, 2); break; } } for(int ed[] : e) { int u = min(ed[0], ed[1]); int v = max(ed[0], ed[1]); Pair p = new Pair(u, v); ap(map.get(p)+" "); } apn(); } static void dfs(int u, int pre) { if( flag[u] ) return; if( pre == 2 ) pre = 3; else pre = 2; flag[u] = true; int size = ar.get(u).size(); for( int v : ar.get(u) ) { map.put(new Pair(min(u, v), max(v, u)), pre); dfs(v, pre); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
3d71e8b3227de57c0f4ae10ad963aa27
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.InputMismatchException; import java.util.Vector; /** * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools */ public class Main { static InputReader sc=new InputReader(System.in); static int maxn=100005, vis[]=new int[maxn], c[]=new int[maxn],ans[]=new int[maxn],st=-1; static boolean used[]=new boolean[maxn]; static Vector<Integer[]> map[]=new Vector[maxn]; public static void main(String[] args) { // Write your solution here int t=sc.nextInt(); while(t-->0){ solve(); } } private static void solve() { int n=sc.nextInt(); //System.out.println(n+"n"); ini(n); for(int i=1;i<=n-1;i++){ int u=sc.nextInt(); int v=sc.nextInt(); //System.out.println(u+" "+v); c[u]++; c[v]++; if(c[u]>=3||c[v]>=3){ for(int j=i+1;j<=n-1;j++){ sc.nextInt();sc.nextInt(); } System.out.println(-1); return; } if(c[u]==2||c[v]==2){ if(c[u]==2){ st=u; }else st=v; } Integer a[]={v,i}; Integer b[]={u,i}; map[u].add(a); map[v].add(b); } dfs(1,2); for(int i=1;i<n;i++){ System.out.print(ans[i]+" "); } System.out.println(); } private static void dfs(int u,int pre) { Integer p[]; for(int i=0;i<map[u].size();i++){ p=map[u].get(i); if(used[p[1]])continue; used[p[1]]=true; ans[p[1]]=5-pre; dfs(p[0],5-pre); pre=5-pre; } } static void ini(int n) { for(int i=1;i<=n;i++){ vis[i]=0; c[i]=0; map[i]=new Vector<>(); used[i]=false; } } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
730f24761cc59f046d883b3ee4acd279
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; public class Main { static class Edge{ public int node; public int index; public Edge(int n, int i){ node=n; index=i; } } static Scanner sc=new Scanner(System.in); public static void main(String[] args) { int test=sc.nextInt(); while(test-->0){ solve(); } } static void solve(){ int n=sc.nextInt(); ArrayList<ArrayList<Edge>> graph= new ArrayList<ArrayList<Edge>>(); for(int i=0;i<n;i++){ graph.add(new ArrayList<>()); } for (int i = 0; i < n - 1; i++) { int u = sc.nextInt(); int v = sc.nextInt(); u--; v--; graph.get(u).add(new Edge(v, i)); graph.get(v).add(new Edge(u, i)); } int start = 0; for (int i = 0; i < n; i++) { if (graph.get(i).size() > 2) { System.out.println("-1"); return; } else if (graph.get(i).size() == 1) { start = i; } } int[] weight = new int[n - 1]; int prevNode = -1; int curNode = start; int curWeight = 2; while (true) { ArrayList<Edge> edges = graph.get(curNode); Edge next = edges.get(0); if (next.node == prevNode) { if (edges.size() == 1) { break; } else { next = edges.get(1); } } weight[next.index] = curWeight; prevNode = curNode; curNode = next.node; curWeight = 5 - curWeight; } for (int i = 0; i < n - 1; i++) { System.out.print(weight[i]); System.out.print(" "); } System.out.println(); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
a4cb8ffb0998508e5689c25e96f77a03
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class C { @SuppressWarnings("unchecked") public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int inputs = Integer.parseInt(in.readLine()); StringBuilder ans = new StringBuilder(); while(inputs-->0) { int n = Integer.parseInt(in.readLine()); int[] degree = new int[n]; boolean bad = false; ArrayList<int[]>[] con = new ArrayList[n]; for(int i = 0; i < n; i++) { con[i] = new ArrayList<>(); } for(int i = 0; i < n-1; i++) { StringTokenizer st = new StringTokenizer(in.readLine()); int a = Integer.parseInt(st.nextToken())-1; int b = Integer.parseInt(st.nextToken())-1; degree[a]++; degree[b]++; if(degree[a] > 2 || degree[b] > 2) bad = true; con[a].add(new int[] {b, i}); con[b].add(new int[] {a, i}); } if(bad) ans.append("-1\n"); else { int[] assign = new int[n-1]; for(int i = 0; i < degree.length; i++) { if(degree[i] == 1) { dfs(i, -1, 11, con, assign); break; } } for(int i = 0; i < n-2; i++) ans.append(assign[i] + " "); ans.append(assign[n-2] + "\n"); } } System.out.print(ans); } public static void dfs(int curr, int prev, int num, ArrayList<int[]>[] con, int[] a) { for(int[] next : con[curr]) { if(next[0] != prev) { a[next[1]] = 13-num; dfs(next[0], curr, 13-num, con, a); } } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
a146dae2ad13eadbd558fa2052017c17
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class A { private static void sport(List<Integer>[] g, Map<W, Integer> map) { int n = g.length; for (int i = 0; i < n; i++) { if (g[i].size() > 2) { System.out.println(-1); return; } } int[] ans = new int[n - 1]; //dfs(new C(-1, 0), g, ans, 3, new HashSet<>()); Queue<int[]> queue = new LinkedList<>(); Set<Integer> seen = new HashSet<>(); int val = 3; for (Integer integer : g[0]) { Integer idx = map.get(new W(0, integer)); ans[idx] = val; queue.add(new int[]{val, integer}); seen.add(integer); val = val == 2 ? 3 : 2; } seen.add(0); while (!queue.isEmpty()) { int[] poll = queue.poll(); for (Integer u : g[poll[1]]) { if (!seen.contains(u)) { seen.add(u); int curr = poll[0] == 2 ? 3 : 2; Integer integer = map.get(new W(poll[1], u)); ans[integer] = curr; queue.add(new int[]{curr, u}); } } } for (int an : ans) { System.out.print(an + " "); } System.out.println(); } static class W { int u; int v; public W(int u, int v) { this.u = u; this.v = v; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; W w = (W) o; return u == w.u && v == w.v; } @Override public int hashCode() { return Objects.hash(u, v); } } static void dfs(C v, List<C>[] g, int[] ans, int prev, Set<Integer> seen) { if (v.i != -1) { ans[v.i] = prev == 2 ? 3 : 2; } seen.add(v.v); int next = prev == 2 ? 3 : 2; for (C c : g[v.v]) { if (!seen.contains(c.v)) { dfs(c, g, ans, next, seen); } next = next == 2 ? 3 : 2; } } static class C { int i; int v; public C(int i, int v) { this.i = i; this.v = v; } } public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); int t = sc.nextInt(); for (int i = 0; i < t; i++) { int n = sc.nextInt(); List<Integer>[] g = new ArrayList[n]; for (int j = 0; j < n; j++) { g[j] = new ArrayList<>(); } Map<W, Integer> map = new HashMap<>(); for (int j = 0; j < n - 1; j++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; g[u].add(v); g[v].add(u); map.put(new W(u, v), j); map.put(new W(v, u), j); } sport(g, map); } } static void shuffleArray(int[] ar) { // If running on Java 6 or older, use `new Random()` on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } void nextLine() throws IOException { br.readLine(); } long[] readArrayLong(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } int[] readArrayInt(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
398b2819c68e1f03671a46a44d8a5977
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.beans.DesignMode; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.CompletableFuture.AsynchronousCompletionTask; import org.xml.sax.ErrorHandler; import java.io.PrintStream; import java.io.PrintWriter; import java.io.DataInputStream; public class Solution { //TEMPLATE ------------------------------------------------------------------------------------- public static boolean Local(){ try{ return System.getenv("LOCAL_SYS")!=null; }catch(Exception e){ return false; } } public static boolean LOCAL; static class FastScanner { BufferedReader br; StringTokenizer st ; FastScanner(){ br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } FastScanner(String file) { try{ br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); st = new StringTokenizer(""); }catch(FileNotFoundException e) { // TODO Auto-generated catch block System.out.println("file not found"); e.printStackTrace(); } } String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String readLine() throws IOException{ return br.readLine(); } } static class Pair<T,X> { T first; X second; Pair(T first,X second){ this.first = first; this.second = second; } @Override public int hashCode(){ return Objects.hash(first,second); } @Override public boolean equals(Object obj){ return obj.hashCode() == this.hashCode(); } } static class TreeNode{ TreeNode left; TreeNode right; int min; int index; int l; int r; TreeNode(int l,int r){ this.l = l; this.r = r; } TreeNode(int l,int r,int min,int index){ this.l = l; this.r = r; this.min = min; this.index = index; } } static PrintStream debug = null; static long mod = (long)(Math.pow(10,9) + 7); //TEMPLATE -------------------------------------------------------------------------------------END// public static void main(String[] args) throws Exception { FastScanner s = new FastScanner(); LOCAL = Local(); //PrintWriter pw = new PrintWriter(System.out); if(LOCAL){ s = new FastScanner("src/input.txt"); PrintStream o = new PrintStream("src/sampleout.txt"); debug = new PrintStream("src/debug.txt"); System.setOut(o); // pw = new PrintWriter(o); } long mod = 1000000007; int tcr = s.nextInt(); StringBuilder sb = new StringBuilder(); for(int tc=0;tc<tcr;tc++){ int n = s.nextInt(); List<List<int[]>> list = new ArrayList<>(); for(int i=0;i<n;i++){list.add(new ArrayList<>());} for(int i=0;i<n-1;i++){ int v1 = s.nextInt(); int v2 = s.nextInt(); v1--;v2--; list.get(v1).add(new int[]{v2,i}); list.get(v2).add(new int[]{v1,i}); } int ans[] = new int[n-1]; boolean fans = solve(list,0,new boolean[n],ans,-1); if(!fans){ sb.append("-1\n"); }else{ for(int i=0;i<n-1;i++){ sb.append(ans[i]+" "); } sb.append('\n'); } } print(sb.toString()); } public static boolean solve(List<List<int[]>> list,int curr,boolean vis[],int ans[],int prev){ vis[curr] = true; if(prev == -1){ if(list.get(curr).size() > 2){ return false; } boolean is2 = true; for(int child[] : list.get(curr)){ if(vis[child[0]]){continue;} if(is2){ ans[child[1]] = 2; if(!solve(list,child[0],vis,ans,2)){ return false; } }else{ ans[child[1]] = 5; if(!solve(list,child[0],vis,ans,5)){ return false; } } is2 = (!is2); } }else{ if(list.get(curr).size() > 2){ return false; } boolean is2 = prev != 2; for(int child[] : list.get(curr)){ if(vis[child[0]]){continue;} if(is2){ ans[child[1]] = 2; if(!solve(list,child[0],vis,ans,2)){ return false; } }else{ ans[child[1]] = 5; if(!solve(list,child[0],vis,ans,5)){ return false; } } is2 = (!is2); } } return true; } public static int dfs(int curr,List<List<Integer>> graph,boolean vis[],int depth,List<Integer> cand){ vis[curr] = true; int cnt = 0; for(int node : graph.get(curr)){ if(!vis[node]){ cnt+=dfs(node,graph,vis,depth+1,cand); } } cand.add(depth - cnt); cnt+=1; return cnt; } public static List<int[]> print_prime_factors(int n){ List<int[]> list = new ArrayList<>(); for(int i=2;i<=(int)(Math.sqrt(n));i++){ if(n % i == 0){ int cnt = 0; while( (n % i) == 0){ n = n/i; cnt++; } list.add(new int[]{i,cnt}); } } if(n!=1){ list.add(new int[]{n,1}); } return list; } public static List<int[]> prime_factors(int n,List<Integer> sieve){ List<int[]> list = new ArrayList<>(); int index = 0; while(n > 1 && sieve.get(index) <= Math.sqrt(n)){ int curr = sieve.get(index); int cnt = 0; while((n % curr) == 0){ n = n/curr; cnt++; } if(cnt >= 1){ list.add(new int[]{curr,cnt}); } index++; } if(n > 1){ list.add(new int[]{n,1}); } return list; } public static boolean inRange(long r1,long r2,long val){ return ((val >= r1) && (val <= r2)); } static int len(long num){ return Long.toString(num).length(); } static long mulmod(long a, long b,long mod) { long ans = 0l; while(b > 0){ long curr = (b & 1l); if(curr == 1l){ ans = ((ans % mod) + a) % mod; } a = (a + a) % mod; b = b >> 1; } return ans; } public static void dbg(PrintStream ps,Object... o) throws Exception{ if(ps == null){ return; } Debug.dbg(ps,o); } public static long modpow(long num,long pow,long mod){ long val = num; long ans = 1l; while(pow > 0l){ long bit = pow & 1l; if(bit == 1){ ans = (ans * (val%mod))%mod; } val = (val * val) % mod; pow = pow >> 1; } return ans; } public static long pow(long num,long pow){ long val = num; long ans = 1l; while(pow > 0l){ long bit = pow & 1l; if(bit == 1){ ans = (ans * (val)); } val = (val * val); pow = pow >> 1; } return ans; } public static char get(int n){ return (char)('a' + n); } public static long[] sort(long arr[]){ List<Long> list = new ArrayList<>(); for(long n : arr){list.add(n);} Collections.sort(list); for(int i=0;i<arr.length;i++){ arr[i] = list.get(i); } return arr; } public static int[] sort(int arr[]){ List<Integer> list = new ArrayList<>(); for(int n : arr){list.add(n);} Collections.sort(list); for(int i=0;i<arr.length;i++){ arr[i] = list.get(i); } return arr; } // return the (index + 1) // where index is the pos of just smaller element // i.e count of elemets strictly less than num public static int justSmaller(long arr[],long num){ // System.out.println(num+"@"); int st = 0; int e = arr.length - 1; int ans = -1; while(st <= e){ int mid = (st + e)/2; if(arr[mid] >= num){ e = mid - 1; }else{ ans = mid; st = mid + 1; } } return ans + 1; } public static int justSmaller(int arr[],int num){ // System.out.println(num+"@"); int st = 0; int e = arr.length - 1; int ans = -1; while(st <= e){ int mid = (st + e)/2; if(arr[mid] >= num){ e = mid - 1; }else{ ans = mid; st = mid + 1; } } return ans + 1; } //return (index of just greater element) //count of elements smaller than or equal to num public static int justGreater(long arr[],long num){ int st = 0; int e = arr.length - 1; int ans = arr.length; while(st <= e){ int mid = (st + e)/2; if(arr[mid] <= num){ st = mid + 1; }else{ ans = mid; e = mid - 1; } } return ans; } public static int justGreater(int arr[],int num){ int st = 0; int e = arr.length - 1; int ans = arr.length; while(st <= e){ int mid = (st + e)/2; if(arr[mid] <= num){ st = mid + 1; }else{ ans = mid; e = mid - 1; } } return ans; } public static void println(Object obj){ System.out.println(obj.toString()); } public static void print(Object obj){ System.out.print(obj.toString()); } public static int gcd(int a,int b){ if(b == 0){return a;} return gcd(b,a%b); } public static long gcd(long a,long b){ if(b == 0l){ return a; } return gcd(b,a%b); } public static int find(int parent[],int v){ if(parent[v] == v){ return v; } return parent[v] = find(parent, parent[v]); } public static List<Integer> sieve(){ List<Integer> prime = new ArrayList<>(); int arr[] = new int[100001]; Arrays.fill(arr,1); arr[1] = 0; arr[2] = 1; for(int i=2;i<100001;i++){ if(arr[i] == 1){ prime.add(i); for(long j = (i*1l*i);j<100001;j+=i){ arr[(int)j] = 0; } } } return prime; } static boolean isPower(long n,long a){ long log = (long)(Math.log(n)/Math.log(a)); long power = (long)Math.pow(a,log); if(power == n){return true;} return false; } private static int mergeAndCount(int[] arr, int l,int m, int r) { // Left subarray int[] left = Arrays.copyOfRange(arr, l, m + 1); // Right subarray int[] right = Arrays.copyOfRange(arr, m + 1, r + 1); int i = 0, j = 0, k = l, swaps = 0; while (i < left.length && j < right.length) { if (left[i] <= right[j]) arr[k++] = left[i++]; else { arr[k++] = right[j++]; swaps += (m + 1) - (l + i); } } while (i < left.length) arr[k++] = left[i++]; while (j < right.length) arr[k++] = right[j++]; return swaps; } // Merge sort function private static int mergeSortAndCount(int[] arr, int l,int r) { // Keeps track of the inversion count at a // particular node of the recursion tree int count = 0; if (l < r) { int m = (l + r) / 2; // Total inversion count = left subarray count // + right subarray count + merge count // Left subarray count count += mergeSortAndCount(arr, l, m); // Right subarray count count += mergeSortAndCount(arr, m + 1, r); // Merge count count += mergeAndCount(arr, l, m, r); } return count; } static class Debug{ //change to System.getProperty("ONLINE_JUDGE")==null; for CodeForces 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>) t); }catch(ClassCastException e) { if(t instanceof int[]) { String s = Arrays.toString((int[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; }else if(t instanceof long[]) { String s = Arrays.toString((long[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; }else if(t instanceof char[]) { String s = Arrays.toString((char[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; }else if(t instanceof double[]) { String s = Arrays.toString((double[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; }else if(t instanceof boolean[]) { String s = Arrays.toString((boolean[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; } 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("}\n"); return ret.toString(); } public static void dbg(PrintStream ps,Object... o) throws Exception { if(LOCAL) { System.setErr(ps); System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [\n"); for(int i = 0; i<o.length; i++) { if(i!=0) { System.err.print(", "); } System.err.print(ts(o[i])); } System.err.println("]"); } } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
8b2ac125fbaf7c6a3dba6348bb7f21f6
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Scanner; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { public static void main(String[]args) throws IOException { new Main().run(); } File input=new File("D:\\test\\input.txt"); void run() throws IOException{ // new solve().setIO(input, System.out).run(); new solve().setIO(System.in, System.out).run(); } class solve extends ioTask{ int n,m,t,q,i,j,r,c; int cnt=0; // int[]p=new int[500005]; // boolean[]isp=new boolean[500005]; // void judge(int k) { // boolean book=true; // for(i=0;i<cnt&&p[i]<=k/2;i++) // { // if(!isp[k-p[i]]) { // if(book) { // out.println(k+"!!!!!"); // book=false; // } // out.println(p[i]+" "+(k-p[i])); // } // } // } int ans[]=new int[100005]; graph g=new graph(100005,200005); class node{ int u,p; public node(int u,int p) { this.u=u; this.p=p; } } void run() throws IOException { // for(i=2;i<500005;i++) // { // if(!isp[i]) { // p[cnt++]=i; // } // for(j=0;j<cnt&&p[j]*i<500005;j++) // { // isp[p[j]*i]=true; // if(i%p[j]==0)break; // } // } // t=in.in(); ss:while(t-->0) { n=in.in(); g.init(n); int[]inn=new int[n+1]; { boolean ans=true; for(i=1;i<n;i++) { int u=in.in(); int v=in.in(); if(ans) { inn[u]++; inn[v]++; if(inn[u]>2||inn[v]>2) { ans=false; continue; } g.add(u, v, i); g.add(v, u, i); } } if(!ans) { out.println(-1); continue ss; } } int root=1; for(i=1;i<=n;i++) { if(inn[i]==1) { root=i; break; } } Queue<Integer>q=new LinkedList<Integer>(); int[]book=new int[n+1]; book[root]=2; q.add(root); while(!q.isEmpty()) { int u=q.poll(); for(j=g.head[u];j>0;j=g.nxt[j]) { int v=g.to[j]; if(book[v]!=0)continue; book[v]=book[u]^1; ans[g.w[j]]=book[v]; q.add(v); } } for(i=1;i<n;i++)out.print(ans[i]+" "); out.println(); } out.close(); } } class In{ private StringTokenizer in=new StringTokenizer(""); private InputStream is; private BufferedReader bf; public In(File file) throws IOException { is=new FileInputStream(file); init(); } public In(InputStream is) throws IOException { this.is=is; init(); } private void init() throws IOException { bf=new BufferedReader(new InputStreamReader(is)); } boolean hasNext() throws IOException { return in.hasMoreTokens()||bf.ready(); } String ins() throws IOException { while(!in.hasMoreTokens()) { in=new StringTokenizer(bf.readLine()); } return in.nextToken(); } int in() throws IOException { return Integer.parseInt(ins()); } long inl() throws IOException { return Long.parseLong(ins()); } double ind() throws IOException { return Double.parseDouble(ins()); } } class Out{ PrintWriter out; private OutputStream os; private void init() { out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(os))); } public Out(File file) throws IOException { os=new FileOutputStream(file); init(); } public Out(OutputStream os) throws IOException { this.os=os; init(); } } class graph{ int[]to,nxt,head,w; int cnt; void init(int n) { cnt=1; for(int i=1;i<=n;i++) { head[i]=0; } } public graph(int n,int m) { to=new int[m+1]; nxt=new int[m+1]; head=new int[n+1]; w=new int[m+1]; cnt=1; } void add(int u,int v,int l) { to[cnt]=v; nxt[cnt]=head[u]; w[cnt]=l; head[u]=cnt++; } } abstract class ioTask{ In in; PrintWriter out; public ioTask setIO(File in,File out) throws IOException{ this.in=new In(in); this.out=new Out(out).out; return this; } public ioTask setIO(File in,OutputStream out) throws IOException{ this.in=new In(in); this.out=new Out(out).out; return this; } public ioTask setIO(InputStream in,OutputStream out) throws IOException{ this.in=new In(in); this.out=new Out(out).out; return this; } public ioTask setIO(InputStream in,File out) throws IOException{ this.in=new In(in); this.out=new Out(out).out; return this; } void run()throws IOException{ } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
675855edc62ec3e00589df5aff3dd50e
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
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.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; public final class CFPS { static FastReader fr = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static final int gigamod = 1000000007; static final int mod = 998244353; static int t = 1; static double epsilon = 0.0000000001; static boolean[] isPrime; static int[] smallestFactorOf; static final int UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3; static long cmp; static int fastVar; @SuppressWarnings({"unused"}) public static void main(String[] args) throws Exception { t = fr.nextInt(); OUTER: for (int tc = 0; tc < t; tc++) { int n = fr.nextInt(); ArrayList<Edge>[] outFrom = new ArrayList[n]; for (int i = 0; i < n; i++) outFrom[i] = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { int from = fr.nextInt() - 1, to = fr.nextInt() - 1; outFrom[from].add(new Edge(from, to, -1, i)); outFrom[to].add(new Edge(to, from, -1, i)); } for (int i = 0; i < n; i++) if (outFrom[i].size() >= 3) { out.println(-1); continue OUTER; } // we will do DFS if (outFrom[0].size() == 1) { dfs(0, -1, 0, outFrom); } else { Edge e1 = null, e2 = null; for (int i = 0; i < 2; i++) if (i == 1) e1 = outFrom[0].get(i); else e2 = outFrom[0].get(i); e1.weight = 0; e2.weight = 1; dfs(e1.to, e1.from, 1, outFrom); dfs(e2.to, e2.from, 0, outFrom); } ArrayList<Edge> edges = new ArrayList<>(); for (int i = 0; i < n; i++) for (Edge e : outFrom[i]) if (e.weight != -1) edges.add(e); Collections.sort(edges, (Edge e1, Edge e2) -> Integer.compare(e1.id, e2.id)); for (int i = 0; i < edges.size(); i++) { Edge e = edges.get(i); if (e.weight == 0) out.print(2 + " "); else out.print(3 + " "); } out.println(); } out.close(); } static void dfs(int current, int from, int mode, ArrayList<Edge>[] outFrom) { for (Edge e : outFrom[current]) if (e.to != from) { e.weight = mode; dfs(e.to, current, mode^1, outFrom); } } // (range add - segment min) segTree static int nn; static int[] arr; static int[] tree; static int[] lazy; static void build(int node, int leftt, int rightt) { if (leftt == rightt) { tree[node] = arr[leftt]; return; } int mid = (leftt + rightt) >> 1; build(node << 1, leftt, mid); build(node << 1 | 1, mid + 1, rightt); tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]); } static void segAdd(int node, int leftt, int rightt, int segL, int segR, int val) { if (lazy[node] != 0) { tree[node] += lazy[node]; if (leftt != rightt) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; } lazy[node] = 0; } if (segL > rightt || segR < leftt) return; if (segL <= leftt && rightt <= segR) { tree[node] += val; if (leftt != rightt) { lazy[node << 1] += val; lazy[node << 1 | 1] += val; } lazy[node] = 0; return; } int mid = (leftt + rightt) >> 1; segAdd(node << 1, leftt, mid, segL, segR, val); segAdd(node << 1 | 1, mid + 1, rightt, segL, segR, val); tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]); } static int minQuery(int node, int leftt, int rightt, int segL, int segR) { if (lazy[node] != 0) { tree[node] += lazy[node]; if (leftt != rightt) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; } lazy[node] = 0; } if (segL > rightt || segR < leftt) return Integer.MAX_VALUE / 10; if (segL <= leftt && rightt <= segR) return tree[node]; int mid = (leftt + rightt) >> 1; return Math.min(minQuery(node << 1, leftt, mid, segL, segR), minQuery(node << 1 | 1, mid + 1, rightt, segL, segR)); } static class Segment { int li, ri, wi, id; Segment(int ll, int rr, int ww, int ii) { li = ll; ri = rr; wi = ww; id = ii; } } static void compute_automaton(String s, int[][] aut) { s += '#'; int n = s.length(); int[] pi = prefix_function(s.toCharArray()); for (int i = 0; i < n; i++) { for (int c = 0; c < 26; c++) { int j = i; while (j > 0 && 'A' + c != s.charAt(j)) j = pi[j-1]; if ('A' + c == s.charAt(j)) j++; aut[i][c] = j; } } } static void timeDFS(int current, int from, UGraph ug, int[] time, int[] tIn, int[] tOut) { tIn[current] = ++time[0]; for (int adj : ug.adj(current)) if (adj != from) timeDFS(adj, current, ug, time, tIn, tOut); tOut[current] = ++time[0]; } static class Pair implements Comparable<Pair> { int first, second; int idx; Pair() { first = second = 0; } Pair (int ff, int ss, int ii) { first = ff; second = ss; idx = ii; } Pair (int ff, int ss) { first = ff; second = ss; idx = -1; } public int compareTo(Pair that) { cmp = first - that.first; if (cmp == 0) cmp = second - that.second; return (int) cmp; } } static boolean areCollinear(long x1, long y1, long x2, long y2, long x3, long y3) { // we will check if c3 lies on line through (c1, c2) long a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); return a == 0; } static int[] treeDiameter(UGraph ug) { int n = ug.V(); int farthest = -1; int[] distTo = new int[n]; diamDFS(0, -1, 0, ug, distTo); int maxDist = -1; for (int i = 0; i < n; i++) if (maxDist < distTo[i]) { maxDist = distTo[i]; farthest = i; } distTo = new int[n + 1]; diamDFS(farthest, -1, 0, ug, distTo); distTo[n] = farthest; return distTo; } static void diamDFS(int current, int from, int dist, UGraph ug, int[] distTo) { distTo[current] = dist; for (int adj : ug.adj(current)) if (adj != from) diamDFS(adj, current, dist + 1, ug, distTo); } static class TreeDistFinder { UGraph ug; int n; int[] depthOf; LCA lca; TreeDistFinder(UGraph ug) { this.ug = ug; n = ug.V(); depthOf = new int[n]; depthCalc(0, -1, ug, 0, depthOf); lca = new LCA(ug, 0); } TreeDistFinder(UGraph ug, int a) { this.ug = ug; n = ug.V(); depthOf = new int[n]; depthCalc(a, -1, ug, 0, depthOf); lca = new LCA(ug, a); } private void depthCalc(int current, int from, UGraph ug, int depth, int[] depthOf) { depthOf[current] = depth; for (int adj : ug.adj(current)) if (adj != from) depthCalc(adj, current, ug, depth + 1, depthOf); } public int dist(int a, int b) { int lc = lca.lca(a, b); return (depthOf[a] - depthOf[lc] + depthOf[b] - depthOf[lc]); } } public static long[][] GCDSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; } else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = gcd(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeGCDQ(long[][] table, int l, int r) { // [a,b) if(l > r)return 1; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return gcd(table[t][l], table[t][r-(1<<t)]); } static class Trie { TrieNode root; Trie(char[][] strings) { root = new TrieNode('A', false); construct(root, strings); } public Stack<String> set(TrieNode root) { Stack<String> set = new Stack<>(); StringBuilder sb = new StringBuilder(); for (TrieNode next : root.next) collect(sb, next, set); return set; } private void collect(StringBuilder sb, TrieNode node, Stack<String> set) { if (node == null) return; sb.append(node.character); if (node.isTerminal) set.add(sb.toString()); for (TrieNode next : node.next) collect(sb, next, set); if (sb.length() > 0) sb.setLength(sb.length() - 1); } private void construct(TrieNode root, char[][] strings) { // we have to construct the Trie for (char[] string : strings) { if (string.length == 0) continue; root.next[string[0] - 'a'] = put(root.next[string[0] - 'a'], string, 0); if (root.next[string[0] - 'a'] != null) root.isLeaf = false; } } private TrieNode put(TrieNode node, char[] string, int idx) { boolean isTerminal = (idx == string.length - 1); if (node == null) node = new TrieNode(string[idx], isTerminal); node.character = string[idx]; node.isTerminal |= isTerminal; if (!isTerminal) { node.isLeaf = false; node.next[string[idx + 1] - 'a'] = put(node.next[string[idx + 1] - 'a'], string, idx + 1); } return node; } class TrieNode { char character; TrieNode[] next; boolean isTerminal, isLeaf; boolean canWin, canLose; TrieNode(char c, boolean isTerminallll) { character = c; isTerminal = isTerminallll; next = new TrieNode[26]; isLeaf = true; } } } static class Edge implements Comparable<Edge> { int from, to; long weight; int id; // int hash; Edge(int fro, int t, long wt, int i) { from = fro; to = t; id = i; weight = wt; // hash = Objects.hash(from, to, weight); } /*public int hashCode() { return hash; }*/ public int compareTo(Edge that) { return Long.compare(this.id, that.id); } } public static long[][] minSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; }else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = Math.min(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeMinQ(long[][] table, int l, int r) { // [a,b) if(l >= r)return Integer.MAX_VALUE; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return Math.min(table[t][l], table[t][r-(1<<t)]); } public static long[][] maxSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; }else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = Math.max(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeMaxQ(long[][] table, int l, int r) { // [a,b) if(l >= r)return Integer.MIN_VALUE; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return Math.max(table[t][l], table[t][r-(1<<t)]); } static class LCA { int[] height, first, segtree; ArrayList<Integer> euler; boolean[] visited; int n; LCA(UGraph ug, int root) { n = ug.V(); height = new int[n]; first = new int[n]; euler = new ArrayList<>(); visited = new boolean[n]; dfs(ug, root, 0); int m = euler.size(); segtree = new int[m * 4]; build(1, 0, m - 1); } void dfs(UGraph ug, int node, int h) { visited[node] = true; height[node] = h; first[node] = euler.size(); euler.add(node); for (int adj : ug.adj(node)) { if (!visited[adj]) { dfs(ug, adj, h + 1); euler.add(node); } } } void build(int node, int b, int e) { if (b == e) { segtree[node] = euler.get(b); } else { int mid = (b + e) / 2; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); int l = segtree[node << 1], r = segtree[node << 1 | 1]; segtree[node] = (height[l] < height[r]) ? l : r; } } int query(int node, int b, int e, int L, int R) { if (b > R || e < L) return -1; if (b >= L && e <= R) return segtree[node]; int mid = (b + e) >> 1; int left = query(node << 1, b, mid, L, R); int right = query(node << 1 | 1, mid + 1, e, L, R); if (left == -1) return right; if (right == -1) return left; return height[left] < height[right] ? left : right; } int lca(int u, int v) { int left = first[u], right = first[v]; if (left > right) { int temp = left; left = right; right = temp; } return query(1, 0, euler.size() - 1, left, right); } } static class FenwickTree { long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates public FenwickTree(int size) { array = new long[size + 1]; } public long rsq(int ind) { assert ind > 0; long sum = 0; while (ind > 0) { sum += array[ind]; //Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number ind -= ind & (-ind); } return sum; } public long rsq(int a, int b) { assert b >= a && a > 0 && b > 0; return rsq(b) - rsq(a - 1); } public void update(int ind, long value) { assert ind > 0; while (ind < array.length) { array[ind] += value; //Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number ind += ind & (-ind); } } public int size() { return array.length - 1; } } static class Point implements Comparable<Point> { long x; long y; long z; long id; // private int hashCode; Point() { x = z = y = 0; // this.hashCode = Objects.hash(x, y, cost); } Point(Point p) { this.x = p.x; this.y = p.y; this.z = p.z; this.id = p.id; // this.hashCode = Objects.hash(x, y, cost); } Point(long x, long y, long z, long id) { this.x = x; this.y = y; this.z = z; this.id = id; // this.hashCode = Objects.hash(x, y, id); } Point(long a, long b) { this.x = a; this.y = b; this.z = 0; // this.hashCode = Objects.hash(a, b); } Point(long x, long y, long id) { this.x = x; this.y = y; this.id = id; } @Override public int compareTo(Point o) { if (this.x < o.x) return -1; if (this.x > o.x) return 1; if (this.y < o.y) return -1; if (this.y > o.y) return 1; if (this.z < o.z) return -1; if (this.z > o.z) return 1; return 0; } @Override public boolean equals(Object that) { return this.compareTo((Point) that) == 0; } } static class BinaryLift { // FUNCTIONS: k-th ancestor and LCA in log(n) int[] parentOf; int maxJmpPow; int[][] binAncestorOf; int n; int[] lvlOf; // How this works? // a. For every node, we store the b-ancestor for b in {1, 2, 4, 8, .. log(n)}. // b. When we need k-ancestor, we represent 'k' in binary and for each set bit, we // lift level in the tree. public BinaryLift(UGraph tree) { n = tree.V(); maxJmpPow = logk(n, 2) + 1; parentOf = new int[n]; binAncestorOf = new int[n][maxJmpPow]; lvlOf = new int[n]; for (int i = 0; i < n; i++) Arrays.fill(binAncestorOf[i], -1); parentConstruct(0, -1, tree, 0); binConstruct(); } // TODO: Implement lvlOf[] initialization public BinaryLift(int[] parentOf) { this.parentOf = parentOf; n = parentOf.length; maxJmpPow = logk(n, 2) + 1; binAncestorOf = new int[n][maxJmpPow]; lvlOf = new int[n]; for (int i = 0; i < n; i++) Arrays.fill(binAncestorOf[i], -1); UGraph tree = new UGraph(n); for (int i = 1; i < n; i++) tree.addEdge(i, parentOf[i]); binConstruct(); parentConstruct(0, -1, tree, 0); } private void parentConstruct(int current, int from, UGraph tree, int depth) { parentOf[current] = from; lvlOf[current] = depth; for (int adj : tree.adj(current)) if (adj != from) parentConstruct(adj, current, tree, depth + 1); } private void binConstruct() { for (int node = 0; node < n; node++) for (int lvl = 0; lvl < maxJmpPow; lvl++) binConstruct(node, lvl); } private int binConstruct(int node, int lvl) { if (node < 0) return -1; if (lvl == 0) return binAncestorOf[node][lvl] = parentOf[node]; if (node == 0) return binAncestorOf[node][lvl] = -1; if (binAncestorOf[node][lvl] != -1) return binAncestorOf[node][lvl]; return binAncestorOf[node][lvl] = binConstruct(binConstruct(node, lvl - 1), lvl - 1); } // return ancestor which is 'k' levels above this one public int ancestor(int node, int k) { if (node < 0) return -1; if (node == 0) if (k == 0) return node; else return -1; if (k > (1 << maxJmpPow) - 1) return -1; if (k == 0) return node; int ancestor = node; int highestBit = Integer.highestOneBit(k); while (k > 0 && ancestor != -1) { ancestor = binAncestorOf[ancestor][logk(highestBit, 2)]; k -= highestBit; highestBit = Integer.highestOneBit(k); } return ancestor; } public int lca(int u, int v) { if (u == v) return u; // The invariant will be that 'u' is below 'v' initially. if (lvlOf[u] < lvlOf[v]) { int temp = u; u = v; v = temp; } // Equalizing the levels. u = ancestor(u, lvlOf[u] - lvlOf[v]); if (u == v) return u; // We will now raise level by largest fitting power of two until possible. for (int power = maxJmpPow - 1; power > -1; power--) if (binAncestorOf[u][power] != binAncestorOf[v][power]) { u = binAncestorOf[u][power]; v = binAncestorOf[v][power]; } return ancestor(u, 1); } } static class DFSTree { // NOTE: The thing is made keeping in mind that the whole // input graph is connected. UGraph tree; UGraph backUG; int hasBridge; int n; Edge backEdge; DFSTree(UGraph ug) { this.n = ug.V(); tree = new UGraph(n); hasBridge = -1; backUG = new UGraph(n); treeCalc(0, -1, new boolean[n], ug); } private void treeCalc(int current, int from, boolean[] marked, UGraph ug) { if (marked[current]) { // This is a backEdge. backUG.addEdge(from, current); backEdge = new Edge(from, current, 1, 0); return; } if (from != -1) tree.addEdge(from, current); marked[current] = true; for (int adj : ug.adj(current)) if (adj != from) treeCalc(adj, current, marked, ug); } public boolean hasBridge() { if (hasBridge != -1) return (hasBridge == 1); // We have to determine the bridge. bridgeFinder(); return (hasBridge == 1); } int[] levelOf; int[] dp; private void bridgeFinder() { // Finding the level of each node. levelOf = new int[n]; levelDFS(0, -1, 0); // Applying DP solution. // dp[i] -> Highest level reachable from subtree of 'i' using // some backEdge. dp = new int[n]; Arrays.fill(dp, Integer.MAX_VALUE / 100); dpDFS(0, -1); // Now, we will check each edge and determine whether its a // bridge. for (int i = 0; i < n; i++) for (int adj : tree.adj(i)) { // (i -> adj) is the edge. if (dp[adj] > levelOf[i]) hasBridge = 1; } if (hasBridge != 1) hasBridge = 0; } private void levelDFS(int current, int from, int lvl) { levelOf[current] = lvl; for (int adj : tree.adj(current)) if (adj != from) levelDFS(adj, current, lvl + 1); } private int dpDFS(int current, int from) { dp[current] = levelOf[current]; for (int back : backUG.adj(current)) dp[current] = Math.min(dp[current], levelOf[back]); for (int adj : tree.adj(current)) if (adj != from) dp[current] = Math.min(dp[current], dpDFS(adj, current)); return dp[current]; } } static class UnionFind { // Uses weighted quick-union with path compression. private int[] parent; // parent[i] = parent of i private int[] size; // size[i] = number of sites in tree rooted at i // Note: not necessarily correct if i is not a root node private int count; // number of components public UnionFind(int n) { count = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } // Number of connected components. public int count() { return count; } // Find the root of p. public int find(int p) { while (p != parent[p]) p = parent[p]; return p; } public boolean connected(int p, int q) { return find(p) == find(q); } public int numConnectedTo(int node) { return size[find(node)]; } // Weighted union. public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make smaller root point to larger one if (size[rootP] < size[rootQ]) { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } else { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } count--; } public static int[] connectedComponents(UnionFind uf) { // We can do this in nlogn. int n = uf.size.length; int[] compoColors = new int[n]; for (int i = 0; i < n; i++) compoColors[i] = uf.find(i); HashMap<Integer, Integer> oldToNew = new HashMap<>(); int newCtr = 0; for (int i = 0; i < n; i++) { int thisOldColor = compoColors[i]; Integer thisNewColor = oldToNew.get(thisOldColor); if (thisNewColor == null) thisNewColor = newCtr++; oldToNew.put(thisOldColor, thisNewColor); compoColors[i] = thisNewColor; } return compoColors; } } static class UGraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public UGraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); adj[to].add(from); } public HashSet<Integer> adj(int from) { return adj[from]; } public int degree(int v) { return adj[v].size(); } public int V() { return adj.length; } public int E() { return E; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int current, boolean[] marked, UGraph g) { if (marked[current]) return; marked[current] = true; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) { if (marked[current]) return; marked[current] = true; if (from != -1) distTo[current] = distTo[from] + 1; HashSet<Integer> adj = g.adj(current); int alreadyMarkedCtr = 0; for (int adjc : adj) { if (marked[adjc]) alreadyMarkedCtr++; dfsMark(adjc, current, distTo, marked, g, endPoints); } if (alreadyMarkedCtr == adj.size()) endPoints.add(current); } public static void bfsOrder(int current, UGraph g) { } public static void dfsMark(int current, int[] colorIds, int color, UGraph g) { if (colorIds[current] != -1) return; colorIds[current] = color; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, colorIds, color, g); } public static int[] connectedComponents(UGraph g) { int n = g.V(); int[] componentId = new int[n]; Arrays.fill(componentId, -1); int colorCtr = 0; for (int i = 0; i < n; i++) { if (componentId[i] != -1) continue; dfsMark(i, componentId, colorCtr, g); colorCtr++; } return componentId; } public static boolean hasCycle(UGraph ug) { int n = ug.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, ug, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = ug.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, ug, marked, hasCycleFirst, current); } } } static class Digraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public Digraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); } public HashSet<Integer> adj(int from) { return adj[from]; } public int V() { return adj.length; } public int E() { return E; } public Digraph reversed() { Digraph dg = new Digraph(V()); for (int i = 0; i < V(); i++) for (int adjVert : adj(i)) dg.addEdge(adjVert, i); return dg; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static int[] KosarajuSharirSCC(Digraph dg) { int[] id = new int[dg.V()]; Digraph reversed = dg.reversed(); // Gotta perform topological sort on this one to get the stack. Stack<Integer> revStack = Digraph.topologicalSort(reversed); // Initializing id and idCtr. id = new int[dg.V()]; int idCtr = -1; // Creating a 'marked' array. boolean[] marked = new boolean[dg.V()]; while (!revStack.isEmpty()) { int vertex = revStack.pop(); if (!marked[vertex]) sccDFS(dg, vertex, marked, ++idCtr, id); } return id; } private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) { marked[source] = true; id[source] = idCtr; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id); } public static Stack<Integer> topologicalSort(Digraph dg) { // dg has to be a directed acyclic graph. // We'll have to run dfs on the digraph and push the deepest nodes on stack first. // We'll need a Stack<Integer> and a int[] marked. Stack<Integer> topologicalStack = new Stack<Integer>(); boolean[] marked = new boolean[dg.V()]; // Calling dfs for (int i = 0; i < dg.V(); i++) if (!marked[i]) runDfs(dg, topologicalStack, marked, i); return topologicalStack; } static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) { marked[source] = true; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) runDfs(dg, topologicalStack, marked, adjVertex); topologicalStack.add(source); } } static class FastReader { private BufferedReader bfr; private StringTokenizer st; public FastReader() { bfr = new BufferedReader(new InputStreamReader(System.in)); } String next() { if (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bfr.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()); } char nextChar() { return next().toCharArray()[0]; } String nextString() { return next(); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } double[] nextDoubleArray(int n) { double[] arr = new double[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextDouble(); return arr; } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } int[][] nextIntGrid(int n, int m) { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) grid[i][j] = fr.nextInt(); } return grid; } } @SuppressWarnings("serial") static class CountMap<T> extends TreeMap<T, Integer>{ CountMap() { } CountMap(Comparator<T> cmp) { } CountMap(T[] arr) { this.putCM(arr); } public Integer putCM(T key) { return super.put(key, super.getOrDefault(key, 0) + 1); } public Integer removeCM(T key) { int count = super.getOrDefault(key, -1); if (count == -1) return -1; if (count == 1) return super.remove(key); else return super.put(key, count - 1); } public Integer getCM(T key) { return super.getOrDefault(key, 0); } public void putCM(T[] arr) { for (T l : arr) this.putCM(l); } } static long dioGCD(long a, long b, long[] x0, long[] y0) { if (b == 0) { x0[0] = 1; y0[0] = 0; return a; } long[] x1 = new long[1], y1 = new long[1]; long d = dioGCD(b, a % b, x1, y1); x0[0] = y1[0]; y0[0] = x1[0] - y1[0] * (a / b); return d; } static boolean diophantine(long a, long b, long c, long[] x0, long[] y0, long[] g) { g[0] = dioGCD(Math.abs(a), Math.abs(b), x0, y0); if (c % g[0] > 0) { return false; } x0[0] *= c / g[0]; y0[0] *= c / g[0]; if (a < 0) x0[0] = -x0[0]; if (b < 0) y0[0] = -y0[0]; return true; } static long[][] prod(long[][] mat1, long[][] mat2) { int n = mat1.length; long[][] prod = new long[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) // determining prod[i][j] // it will be the dot product of mat1[i][] and mat2[][i] for (int k = 0; k < n; k++) prod[i][j] += mat1[i][k] * mat2[k][j]; return prod; } static long[][] matExpo(long[][] mat, long power) { int n = mat.length; long[][] ans = new long[n][n]; if (power == 0) return null; if (power == 1) return mat; long[][] half = matExpo(mat, power / 2); ans = prod(half, half); if (power % 2 == 1) { ans = prod(ans, mat); } return ans; } static int KMPNumOcc(char[] text, char[] pat) { int n = text.length; int m = pat.length; char[] patPlusText = new char[n + m + 1]; for (int i = 0; i < m; i++) patPlusText[i] = pat[i]; patPlusText[m] = '^'; // Seperator for (int i = 0; i < n; i++) patPlusText[m + i] = text[i]; int[] fullPi = piCalcKMP(patPlusText); int answer = 0; for (int i = 0; i < n + m + 1; i++) if (fullPi[i] == m) answer++; return answer; } static int[] piCalcKMP(char[] s) { int n = s.length; int[] pi = new int[n]; for (int i = 1; i < n; i++) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; } static boolean[] prefMatchesSuff(char[] s) { int n = s.length; boolean[] res = new boolean[n + 1]; int[] pi = prefix_function(s); res[0] = true; for (int p = n; p != 0; p = pi[p]) res[p] = true; return res; } static int[] prefix_function(char[] s) { int n = s.length; int[] pi = new int[n]; for (int i = 1; i < n; i++) { int j = pi[i-1]; while (j > 0 && s[i] != s[j]) j = pi[j-1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; } static long hash(long key) { long h = Long.hashCode(key); h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4); return h & (gigamod-1); } static int mapTo1D(int row, int col, int n, int m) { // Maps elements in a 2D matrix serially to elements in // a 1D array. return row * m + col; } static int[] mapTo2D(int idx, int n, int m) { // Inverse of what the one above does. int[] rnc = new int[2]; rnc[0] = idx / m; rnc[1] = idx % m; return rnc; } static boolean[] primeGenerator(int upto) { // Sieve of Eratosthenes: isPrime = new boolean[upto + 1]; smallestFactorOf = new int[upto + 1]; Arrays.fill(smallestFactorOf, 1); Arrays.fill(isPrime, true); isPrime[1] = isPrime[0] = false; for (long i = 2; i < upto + 1; i++) if (isPrime[(int) i]) { smallestFactorOf[(int) i] = (int) i; // Mark all the multiples greater than or equal // to the square of i to be false. for (long j = i; j * i < upto + 1; j++) { if (isPrime[(int) j * (int) i]) { isPrime[(int) j * (int) i] = false; smallestFactorOf[(int) j * (int) i] = (int) i; } } } return isPrime; } static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) { if (smallestFactorOf == null) primeGenerator(num + 1); HashMap<Integer, Integer> fnps = new HashMap<>(); while (num != 1) { fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1); num /= smallestFactorOf[num]; } return fnps; } static HashMap<Long, Integer> primeFactorization(long num) { // Returns map of factor and its power in the number. HashMap<Long, Integer> map = new HashMap<>(); while (num % 2 == 0) { num /= 2; Integer pwrCnt = map.get(2L); map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1); } for (long i = 3; i * i <= num; i += 2) { while (num % i == 0) { num /= i; Integer pwrCnt = map.get(i); map.put(i, pwrCnt != null ? pwrCnt + 1 : 1); } } // If the number is prime, we have to add it to the // map. if (num != 1) map.put(num, 1); return map; } static HashSet<Long> divisors(long num) { HashSet<Long> divisors = new HashSet<Long>(); divisors.add(1L); divisors.add(num); for (long i = 2; i * i <= num; i++) { if (num % i == 0) { divisors.add(num/i); divisors.add(i); } } return divisors; } static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) { if (m > limit) return; if (m <= limit && n <= limit) coprimes.add(new Point(m, n)); if (coprimes.size() > numCoprimes) return; coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes); coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes); coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes); } static long nCr(long n, long r, long[] fac) { long p = gigamod; if (r == 0) return 1; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long modDiv(long a, long b){return mod(a * power(b, mod - 2, mod), mod);} static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); } static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; } static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } 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 String toString(int[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(boolean[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(long[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(char[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+"");return sb.toString();} static String toString(int[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(long[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++) {sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(double[][] dp){StringBuilder sb=new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(char[][] dp){StringBuilder sb = new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+"");}sb.append('\n');}return sb.toString();} static long mod(long a, long m){return(a%m+1000000L*m)%m;} } // NOTES: // ASCII VALUE OF 'A': 65 // ASCII VALUE OF 'a': 97 // Range of long: 9 * 10^18 // ASCII VALUE OF '0': 48 // Primes upto 'n' can be given by (n / (logn)).
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
b7e26a358d1e80ea362c32fcdadf3787
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.awt.Point; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class C1627 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int t=0; t<T; t++) { int N = in.nextInt(); Node[] nodes = new Node[N]; for (int n=0; n<N; n++) { Node node = new Node(); node.id = n+1; nodes[n] = node; } List<Point> edges = new ArrayList<>(); for (int n=1; n<N; n++) { int u = in.nextInt()-1; int v = in.nextInt()-1; Node nodeu = nodes[u]; Node nodev = nodes[v]; nodeu.next.add(nodev); nodev.next.add(nodeu); edges.add(new Point(u,v)); } boolean possible = true; Node start = null; for (Node node : nodes) { int degree = node.next.size(); if (degree == 1) { start = node; } else if (degree >= 3) { possible = false; break; } } if (possible) { int pos = 0; start.pos = pos++; Node last = start; Node current = start.next.get(0); while (true) { current.pos = pos++; if (current.next.size() == 1) break; Node next = null; for (Node node : current.next) { if (node != last) { next = node; } } last = current; current = next; } StringBuilder out = new StringBuilder(); for (Point p : edges) { out.append((Math.min(nodes[p.x].pos, nodes[p.y].pos) % 2 == 0) ? "2 " : "3 "); } System.out.println(out); } else { System.out.println("-1"); } } } static class Node { int id; int pos; List<Node> next = new ArrayList<>(); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
5221ec616135b64aa29f5c89506bcca8
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; //import javafx.util.*; public class Main { static PrintWriter out = new PrintWriter(System.out); static FastReader in = new FastReader(); static int INF = Integer.MAX_VALUE; static int NINF = Integer.MIN_VALUE; public static StringBuilder str = new StringBuilder(); public static boolean flag = true; public static ArrayList<Integer> arr = new ArrayList<>(); public static void main (String[] args) throws java.lang.Exception { //check if you have to take product or the constraints are big int t = i(); while(t-- > 0){ int n = i(); ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); for(int i = 0;i < n;i++) graph.add(new ArrayList<>()); ArrayList<pair> v = new ArrayList<>(); boolean flag = false; for(int i = 0;i < n - 1;i++){ int a1 = i(); int b1 = i(); a1--; b1--; int a = Math.min(a1,b1); int b = Math.max(a1,b1); v.add(new pair(a,b)); graph.get(a).add(b); graph.get(b).add(a); if(graph.get(a).size() > 2 || graph.get(b).size() > 2){ flag = true; } } if(flag){ out.println(-1); continue; } HashMap<pair,Integer> map = new HashMap<>(); int start = -1; for(int i = 0;i < n;i++){ if(graph.get(i).size() == 1){ start = i; break; } } boolean[] visited = new boolean[n]; visited[start] = true; int curr = 3; while(true){ int ini = start; for(int k = 0;k < graph.get(start).size();k++){ if(!visited[graph.get(start).get(k)]){ visited[graph.get(start).get(k)] = true; start = graph.get(start).get(k); break; } } if(ini == start){ break; } pair p = new pair(Math.min(ini,start), Math.max(ini,start)) ; map.put(p,curr); curr = 5 - curr; } for(int i = 0;i < v.size();i++){ pair p = new pair(v.get(i).x,v.get(i).y); out.print(map.get(p) + " "); } out.println(); } out.close(); } public static void sort(int[] arr){ ArrayList<Integer> ls = new ArrayList<>(); for(int x : arr){ ls.add(x); } Collections.sort(ls); for(int i = 0;i < arr.length;i++){ arr[i] = ls.get(i); } } public static void reverse(int[] arr){ int n = arr.length; for(int i = 0;i < n/2;i++){ int temp = arr[i]; arr[i] = arr[n-1-i]; arr[n-1-i] = temp; } } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static int[] input(int N){ int A[]=new int[N]; for(int i=0; i<N; i++) { A[i]=in.nextInt(); } return A; } static long[] inputLong(int N) { long A[]=new long[N]; for(int i=0; i<A.length; i++)A[i]=in.nextLong(); return A; } } class pair implements Comparable<pair> { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } 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 Integer(x).hashCode() * 31 + new Integer(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Integer.compare(this.y, other.y); } return Integer.compare(this.x, other.x); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st==null || !st.hasMoreElements()) { try { st=new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
3bf86d1f4c8f6a3f5a376240f9bbf54d
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedOutputStream; 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.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Practice1 { static long[] sort(long[] arr) { int n=arr.length; ArrayList<Long> al=new ArrayList<>(); for(int i=0;i<n;i++) { al.add(arr[i]); } Collections.sort(al); for(int i=0;i<n;i++) { arr[i]=al.get(i); } return arr; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long nCr(int n, int r) { // int x=1000000007; long dp[][]=new long[2][r+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=i&&j<=r;j++){ if(i==0||j==0||i==j){ dp[i%2][j]=1; }else { // dp[i%2][j]=(dp[(i-1)%2][j]+dp[(i-1)%2][j-1])%x; dp[i%2][j]=(dp[(i-1)%2][j]+dp[(i-1)%2][j-1]); } } } return dp[n%2][r]; } public static class UnionFind { private final int[] p; public UnionFind(int n) { p = new int[n]; for (int i = 0; i < n; i++) { p[i] = i; } } public int find(int x) { return x == p[x] ? x : (p[x] = find(p[x])); } public void union(int x, int y) { x = find(x); y = find(y); if (x != y) { p[x] = y; } } } public static boolean ispalin(String str) { int n=str.length(); for(int i=0;i<n/2;i++) { if(str.charAt(i)!=str.charAt(n-i-1)) { return false; } } return true; } static class Pair{ int val; int pos; Pair(int val,int pos){ this.val=val; this.pos=pos; } } static long power(long N,long R) { long x=1000000007; if(R==0) return 1; if(R==1) return N; long temp= power(N,R/2)%x; // (a*b)%p = (a%p*b%p)*p temp=(temp*temp)%x; if(R%2==0){ return temp%x; }else{ return (N*temp)%x; } } public static String binary(int n) { StringBuffer ans=new StringBuffer(); int a=4; while(a-->0) { int temp=(n&1); if(temp!=0) { ans.append('1'); }else { ans.append('0'); } n =n>>1; } ans=ans.reverse(); return ans.toString(); } public static int find(String[][] arr,boolean[][] vis,int dir,int i,int j) { if(i<0||i>=arr.length||j<0||j>=arr[0].length) return 0; if(vis[i][j]==true) return 0; if(dir==1&&arr[i][j].charAt(0)=='1') return 0; if(dir==2&&arr[i][j].charAt(1)=='1') return 0; if(dir==3&&arr[i][j].charAt(2)=='1') return 0; if(dir==4&&arr[i][j].charAt(3)=='1') return 0; vis[i][j]=true; int a=find(arr,vis,1,i+1,j); int b=find(arr,vis,2,i-1,j); int c=find(arr,vis,3,i,j+1); int d=find(arr,vis,4,i,j-1); return 1+a+b+c+d; } static ArrayList<Integer> allDivisors(int n) { ArrayList<Integer> al=new ArrayList<>(); int i=2; while(i*i<=n) { if(n%i==0) al.add(i); if(n%i==0&&i*i!=n) al.add(n/i); i++; } return al; } static int[] sort(int[] arr) { int n=arr.length; ArrayList<Integer> al=new ArrayList<>(); for(int i=0;i<n;i++) { al.add(arr[i]); } Collections.sort(al); for(int i=0;i<n;i++) { arr[i]=al.get(i); } return arr; } /** Code for Dijkstra's algorithm **/ public static class ListNode { int vertex, weight; ListNode(int v, int w) { vertex = v; weight = w; } int getVertex() { return vertex; } int getWeight() { return weight; } } public static int[] dijkstra( int V, ArrayList<ArrayList<ListNode> > graph, int source) { int[] distance = new int[V]; for (int i = 0; i < V; i++) distance[i] = Integer.MAX_VALUE; distance[0] = 0; PriorityQueue<ListNode> pq = new PriorityQueue<>( (v1, v2) -> v1.getWeight() - v2.getWeight()); pq.add(new ListNode(source, 0)); while (pq.size() > 0) { ListNode current = pq.poll(); for (ListNode n : graph.get(current.getVertex())) { if (distance[current.getVertex()] + n.getWeight() < distance[n.getVertex()]) { distance[n.getVertex()] = n.getWeight() + distance[current.getVertex()]; pq.add(new ListNode( n.getVertex(), distance[n.getVertex()])); } } } // If you want to calculate distance from source to // a particular target, you can return // distance[target] return distance; } public static ArrayList<Integer> find(int n){ ArrayList<Integer> al=new ArrayList<>(); int i=2; while(n>1) { while(n%i==0) { al.add(i); n /=i; } i++; } return al; } public static void find(HashMap<Integer,ArrayList<Integer>> map, HashMap<String,Integer> map1,boolean[] vis,int val,int node) { if(vis[node]==true) return; vis[node]=true; for(Integer i: map.get(node)) { if(vis[i]==false) { map1.put(node+"#"+i,val); map1.put(i+"#"+node,val); }; if(val==2)find(map,map1,vis,3,i); else find(map,map1,vis,2,i); } } public static void main (String[] args) { PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); // out.print(); //out.println(); FastReader sc=new FastReader(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int[][] arr=new int[n-1][2]; HashMap<Integer,ArrayList<Integer>> map=new HashMap<>(); for(int i=1;i<=n;i++) { map.put(i,new ArrayList<>()); } for(int i=0;i<n-1;i++) { int u=sc.nextInt(); int v=sc.nextInt(); arr[i][0]=u; arr[i][1]=v; map.get(u).add(v); map.get(v).add(u); } boolean bol=true; int start=-1; for(Map.Entry<Integer,ArrayList<Integer>> m: map.entrySet()) { if(m.getValue().size()>2) bol=false; if(m.getValue().size()==1) start=m.getKey(); } if(bol==false) { out.println(-1); continue; } HashMap<String,Integer> map1=new HashMap<>(); boolean[] vis=new boolean[n+1]; // out.println("start : "+start); find(map,map1,vis,2,start); StringBuffer ans=new StringBuffer(); for(int i=0;i<n-1;i++) { ans.append(map1.get(arr[i][0]+"#"+arr[i][1])+" "); } out.println(ans); } out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
2fdde6f3bbb81fa4170fe1f9fd6a3aa7
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
/* Challenge 1: Newbie to CM in 1year (Dec 2021 - Nov 2022) 🔥 5* Codechef Challenge 2: CM to IM in 1 year (Dec 2022 - Nov 2023) 🔥🔥 6* Codechef Challenge 3: IM to GM in 1 year (Dec 2023 - Nov 2024) 🔥🔥🔥 7* Codechef Goal: Become better in CP! Key: Consistency and Discipline Desire: SDE @ Google USA */ import java.util.*; import java.io.*; import java.math.*; public class Coder { static StringBuffer str=new StringBuffer(); static int n; static List<List<Integer>> l; static Map<String, Integer> map; static void dfs(int u, int p, int c){ int col[]=new int[2]; col[0]=c; col[1]=c==2?3:2; int idx=0; for(int v:l.get(u)){ if(v==p) continue; map.put(u+"-"+v, col[idx]); map.put(v+"-"+u, col[idx]); dfs(v, u, col[idx]==2?3:2); idx++; } } static boolean solve(){ for(int i=1;i<=n;i++){ if(l.get(i).size()>2) return false; } dfs(1, -1, 2); return true; } public static void main(String[] args) throws java.lang.Exception { BufferedReader bf; PrintWriter pw; boolean lenv=false; if(lenv){ bf = new BufferedReader( new FileReader("input.txt")); pw=new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); }else{ bf = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new OutputStreamWriter(System.out)); } int t = Integer.parseInt(bf.readLine().trim()); while (t-- > 0) { n=Integer.parseInt(bf.readLine().trim()); l=new ArrayList<>(); map=new HashMap<>(); List<int []> ans=new ArrayList<>(); for(int i=0;i<=n;i++) l.add(new ArrayList<>()); for(int i=0;i<n-1;i++){ String st[]=bf.readLine().trim().split("\\s+"); int u=Integer.parseInt(st[0]); int v=Integer.parseInt(st[1]); ans.add(new int[]{u, v}); map.put(u+"-"+v, 0); map.put(v+"-"+u, 0); l.get(u).add(v); l.get(v).add(u); } if(solve()){ for(int i=0;i<n-1;i++) str.append(map.get(ans.get(i)[0]+"-"+ans.get(i)[1])).append(" "); str.append("\n"); }else str.append("-1\n"); } pw.println(str); pw.flush(); // System.outin.print(str); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
d5b385d4fbdd52e2ed13816e880226db
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class C { public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int T = in.nextInt(); for(int ttt = 1; ttt <= T; ttt++) { int n = in.nextInt(); int[][] edges = new int[n-1][2]; Map<Integer, List<int[]>> map = new HashMap<>(); int max = 0; for(int i = 0; i < n-1; i++) { edges[i][0] = in.nextInt(); edges[i][1] = in.nextInt(); if(!map.containsKey(edges[i][0])) map.put(edges[i][0], new ArrayList<>()); if(!map.containsKey(edges[i][1])) map.put(edges[i][1], new ArrayList<>()); map.get(edges[i][0]).add(new int[]{edges[i][1], 0}); map.get(edges[i][1]).add(new int[]{edges[i][0], 0}); max = Math.max(max, Math.max(map.get(edges[i][0]).size(), map.get(edges[i][1]).size())); } if(max > 2) out.println(-1); else { int start = 1; for(int key : map.keySet()) { if(map.get(key).size()==1) { start = key; } } dfs(start, 0, map, 2); for(int[] e : edges) { for(int[] u : map.get(e[0])) { if(u[0]==e[1]) { out.print(u[1] + " "); } } } out.println(); } } out.close(); } static void dfs(int v, int p, Map<Integer, List<int[]>> map, int val) { for(int[] u : map.get(v)) { if(u[0]!=p) { dfs(u[0], v, map, (val==2 ? 3: 2)); } } for(int[] e : map.get(v)) { if(e[0]==p) { e[1] = val; } } if(map.containsKey(p)) { for(int[] e : map.get(p)) { if(e[0]==v) { e[1] = val; } } } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } int[] readInt(int size) { int[] arr = new int[size]; for(int i = 0; i < size; i++) arr[i] = Integer.parseInt(next()); return arr; } long[] readLong(int size) { long[] arr = new long[size]; for(int i = 0; i < size; i++) arr[i] = Long.parseLong(next()); return arr; } int[][] read2dArray(int rows, int cols) { int[][] arr = new int[rows][cols]; for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) arr[i][j] = Integer.parseInt(next()); } return arr; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
0ec06a3edbbb69fdc1c5832c5ef3bdae
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class C { public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int T = in.nextInt(); for(int ttt = 1; ttt <= T; ttt++) { int n = in.nextInt(); HashMap<Integer, HashSet<int[]>> map = new HashMap<>(); int[][] edges = new int[n-1][2]; boolean p = true; for(int i = 0; i < n-1; i++) { int u = in.nextInt(); int v = in.nextInt(); edges[i][0] = u; edges[i][1] = v; if(!map.containsKey(u)) map.put(u, new HashSet<>()); if(!map.containsKey(v)) map.put(v, new HashSet<>()); map.get(u).add(new int[]{v, 0}); map.get(v).add(new int[]{u, 0}); if(map.get(u).size()>2) p = false; if(map.get(v).size()>2) p = false; } if(p) { int start = 1; for(int key : map.keySet()) { if(map.get(key).size() == 1) { start = key; break; } } boolean[] visited = new boolean[n+1]; visited[start] = true; dfs(map, visited, start, 2); for(int[] edge : edges) { for(int[] node : map.get(edge[0])) { if(node[0] == edge[1]) out.print(node[1] + " "); } } out.println(); } else out.println(-1); } out.close(); } public static void dfs(HashMap<Integer, HashSet<int[]>> map, boolean[] visited, int cur, int val) { for(int[] adj : map.get(cur)) { if(!visited[adj[0]]) { visited[adj[0]] = true; adj[1] = val; for(int[] node : map.get(adj[0])) { if(node[0] == cur) node[1] = val; } int newVal = val == 2 ? 3 : 2; dfs(map, visited, adj[0], newVal); } } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } int[] readInt(int size) { int[] arr = new int[size]; for(int i = 0; i < size; i++) arr[i] = Integer.parseInt(next()); return arr; } long[] readLong(int size) { long[] arr = new long[size]; for(int i = 0; i < size; i++) arr[i] = Long.parseLong(next()); return arr; } int[][] read2dArray(int rows, int cols) { int[][] arr = new int[rows][cols]; for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) arr[i][j] = Integer.parseInt(next()); } return arr; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
bd37457ab21c08210da099c3bd20b854
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.Scanner; public class C { static int N = 100010; static int[] cot = new int[N]; static boolean[] vis = new boolean[N]; static int[] h = new int[N]; static int[] des = new int[2 * N], next = new int[2 * N]; static int idx = 0; static int[] ans = new int[N]; public static void main(String[] args) { Scanner in = new Scanner(System.in); int round = in.nextInt(); for (int z = 0; z < round; z++) { int n = in.nextInt(); for (int i = 1; i <= n; i++) { h[i] = -1; vis[i] = false; cot[i] = 0; } idx = 0; boolean flag = true; for (int i = 1; i < n; i++) { int a = in.nextInt(); int b = in.nextInt(); des[idx] = b; next[idx] = h[a]; h[a] = idx++; des[idx] = a; next[idx] = h[b]; h[b] = idx++; if (++cot[a] >= 3 | ++cot[b] >= 3) flag = false; } if (!flag) System.out.println(-1); else { int startPoint = -1; for (int i = 1; i <= n; i++) if (cot[i] == 1) { startPoint = i; break; } dfs(startPoint, 3); for (int i = 1; i < n; i++) System.out.print(ans[i] + " "); System.out.println(); } } } private static void dfs(int point, int preLen) { vis[point] = true; for (int i = h[point]; i != -1; i = next[i]) if (!vis[des[i]]) { ans[i / 2 + 1] = 5 - preLen; // System.out.println(point + ">" + des[i] + " " + ans[i / 2 + 1] + " " + (i / 2 // + 1)); dfs(des[i], ans[i / 2 + 1]); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
6e249ef53e0c12bb0b8171ac5c120207
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); for (int i = 0; i < t; i++) { notSitting(scanner); } } private static void notSitting(Scanner scanner) { int n = scanner.nextInt(); int[] num = new int[n - 1]; int[] ct = new int[n]; boolean[] visited = new boolean[n]; List<int[]>[] edges = new List[n]; for (int i = 0; i < n; i++) { edges[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int u = scanner.nextInt() - 1; int v = scanner.nextInt() - 1; edges[u].add(new int[]{v, i}); edges[v].add(new int[]{u, i}); ct[u]++; ct[v]++; } int start = -1; for (int i = 0; i < n; i++) { if (ct[i] >= 3) { System.out.println(-1); return; } else if (ct[i] == 1) { start = i; } } visited[start] = true; boolean odd = false; for (int i = 0; i < n - 1; i++) { for (int[] e : edges[start]) { if (!visited[e[0]]) { visited[e[0]] = true; num[e[1]] = odd ? 3 : 2; odd = !odd; start = e[0]; break; } } } for (int i = 0; i < n - 1; i++) { System.out.print(num[i]); System.out.print(" "); } System.out.println(); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
368cd107f92a7159687b7749f65c0813
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class NotAssigning { static class Fast { BufferedReader br; StringTokenizer st; public Fast() { 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()); } int[] readArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readArray1(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void build(LinkedList<Integer> adj[],int n)// index starts from 1 { adj=new LinkedList[n+1]; for(int i=0;i<=n;i++) adj[i]=(new LinkedList<>()); } static void addEdges(LinkedList<Integer> adj[],int n) //index starts from 1 { Fast sc = new Fast(); for(int i=1;i<=n-1;i++) { int u=sc.nextInt(); int v= sc.nextInt(); adj[u].add(v); adj[v].add(u); } } static void build(ArrayList<ArrayList<Integer>> adj,int n)// index starts from 1 { for(int i=0;i<=n;i++) adj.add(new ArrayList<>()); } /* static void addEdges(ArrayList<ArrayList<Integer>> adj,int n) //index starts from 1 { Fast sc = new Fast(); PrintWriter out = new PrintWriter(System.out); int a[]=new int[n+1]; int b[]=new int[n+1]; for(int i=1;i<=n-1;i++) { int u=sc.nextInt(); int v= sc.nextInt(); a[i]=u; b[i]=v; adj.get(u).add(v); adj.get(v).add(u); } int f = 0; int u=0; for (int i = 1; i <= n; i++) { if (adj.get(i).size() > 2) { f = 1; break; } if(adj.get(i).size()==1) u=i; } if (f == 1) { out.println(-1); return; } int vis[]=new int[n+1]; Arrays.fill(vis,-1); HashMap<Pair,Integer> h=new HashMap<Pair, Integer>(); dfs(adj,h,vis,u,-1,0); for(int i=1;i<=n-1;i++) { out.print(h.get(new Pair(Math.min(a[i],b[i]),Math.max(a[i],b[i])))+" "); } out.println(); // out.close(); }*/ static class Pair implements Comparator<Pair> { int x,y,idx; Pair(){} Pair(int x,int y,int idx) { this.x=x; this.y=y; this.idx=idx; } public int compare(Pair a,Pair b) { if(a.idx>b.idx) return 1; else if(a.idx<b.idx) return -1; return 0; } } // CODE BEGINS HERE______________________________________________ static void dfs( ArrayList<int []> adj[],int vis[],int u,int par,int track,int ans[]) { vis[u]=1; for(int nei[]:adj[u]) { int des=nei[0]; int idx=nei[1]; if(vis[des]==-1) { ans[idx-1] = track == 0 ? 2 : 3; dfs(adj, vis, nei[0], u, track ^ 1,ans); track=1; } } } public static void main(String args[]) { Fast sc = new Fast(); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); outer: while (t-- > 0) { int n = sc.nextInt();int ans[]=new int[n-1]; ArrayList<int []> adj[] = new ArrayList[n+1]; for(int i=0;i<=n;i++) adj[i]=new ArrayList<>(); for(int i=1;i<=n-1;i++) { int u=sc.nextInt(); int v= sc.nextInt(); adj[u].add(new int[]{v,i}); adj[v].add(new int[]{u,i}); } int f = 0; int u=0; for (int i = 1; i <= n; i++) { if(adj[i].size()>2) { out.println(-1); continue outer; } } int vis[]=new int[n+1]; Arrays.fill(vis,-1); HashMap<Pair,Integer> h=new HashMap<Pair, Integer>(); dfs(adj,vis,1,-1,0,ans); for(int an:ans) out.print(an+" "); out.println(); } out.close(); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
3bca4806a3f09a3c79c4886287518024
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class NotAssigning { static class Fast { BufferedReader br; StringTokenizer st; public Fast() { 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()); } int[] readArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readArray1(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void build(LinkedList<Integer> adj[],int n)// index starts from 1 { adj=new LinkedList[n+1]; for(int i=0;i<=n;i++) adj[i]=(new LinkedList<>()); } static void addEdges(LinkedList<Integer> adj[],int n) //index starts from 1 { Fast sc = new Fast(); for(int i=1;i<=n-1;i++) { int u=sc.nextInt(); int v= sc.nextInt(); adj[u].add(v); adj[v].add(u); } } static void build(ArrayList<ArrayList<Integer>> adj,int n)// index starts from 1 { for(int i=0;i<=n;i++) adj.add(new ArrayList<>()); } /* static void addEdges(ArrayList<ArrayList<Integer>> adj,int n) //index starts from 1 { Fast sc = new Fast(); PrintWriter out = new PrintWriter(System.out); int a[]=new int[n+1]; int b[]=new int[n+1]; for(int i=1;i<=n-1;i++) { int u=sc.nextInt(); int v= sc.nextInt(); a[i]=u; b[i]=v; adj.get(u).add(v); adj.get(v).add(u); } int f = 0; int u=0; for (int i = 1; i <= n; i++) { if (adj.get(i).size() > 2) { f = 1; break; } if(adj.get(i).size()==1) u=i; } if (f == 1) { out.println(-1); return; } int vis[]=new int[n+1]; Arrays.fill(vis,-1); HashMap<Pair,Integer> h=new HashMap<Pair, Integer>(); dfs(adj,h,vis,u,-1,0); for(int i=1;i<=n-1;i++) { out.print(h.get(new Pair(Math.min(a[i],b[i]),Math.max(a[i],b[i])))+" "); } out.println(); // out.close(); }*/ static class Pair implements Comparator<Pair> { int x,y,idx; Pair(){} Pair(int x,int y,int idx) { this.x=x; this.y=y; this.idx=idx; } public int compare(Pair a,Pair b) { if(a.idx>b.idx) return 1; else if(a.idx<b.idx) return -1; return 0; } } static void dfs( ArrayList<int []> adj[],int vis[],int u,int par,int track,int ans[]) { vis[u]=1; // h.put(new Pair(Math.min(u,par),Math.max(u,par)),track==0?2:3); for(int nei[]:adj[u]) { int des=nei[0]; int idx=nei[1]; if(vis[des]==-1) { ans[idx-1] = track == 0 ? 2 : 3; dfs(adj, vis, nei[0], u, track ^ 1,ans); track=1; } } } public static void main(String args[]) { Fast sc = new Fast(); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); outer: while (t-- > 0) { int n = sc.nextInt();int ans[]=new int[n-1]; ArrayList<int []> adj[] = new ArrayList[n+1]; for(int i=0;i<=n;i++) adj[i]=new ArrayList<>(); // build(adj, n); // addEdges(adj, n); int a[]=new int[n+1]; int b[]=new int[n+1]; int c[]=new int[n+1]; for(int i=1;i<=n-1;i++) { int u=sc.nextInt(); int v= sc.nextInt(); a[i]=u; b[i]=v; c[u]++;c[v]++; adj[u].add(new int[]{v,i}); adj[v].add(new int[]{u,i}); } int f = 0; int u=0; for (int i = 1; i <= n; i++) { if(adj[i].size()>2) { out.println(-1); continue outer; } if(c[i]>2) { out.println(-1); continue outer; } } if(f==1) { out.println(-1); continue ; } int vis[]=new int[n+1]; Arrays.fill(vis,-1); HashMap<Pair,Integer> h=new HashMap<Pair, Integer>(); dfs(adj,vis,1,-1,0,ans); for(int an:ans) out.print(an+" "); /* for(int i=1;i<=n-1;i++) { out.print(h.get(new Pair(Math.min(a[i],b[i]),Math.max(a[i],b[i])))+" "); }*/ out.println(); } out.close(); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
b71c0c4dbacd5dbc3450b0506281d422
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int i, j, k, n, m, t, y, x, sum = 0; static long mod = 998244353; static FastScanner fs = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); static String str; public static void main(String[] args) { t = fs.nextInt(); while (t-- > 0) { n = fs.nextInt(); List<Pair>[] g = new ArrayList[n+1]; for(i=1;i<=n;i++){ g[i] = new ArrayList(); } for(i=0;i<n-1;i++){ x = fs.nextInt(); y = fs.nextInt(); g[x].add(new Pair(y,i)); g[y].add(new Pair(x,i)); } boolean isPossible = true; int l1 =0, l2=0; for(i=1;i<=n;i++){ if(g[i].size()>2) isPossible = false; if(g[i].size()==1) if(l1==0) l1 = i; else l2 =i; } if(!isPossible){ out.println(-1); continue; } i = l1; k=0; int [] ans = new int[n]; int [] vis = new int[n+1]; j=0; while(i!=l2){ Pair p = g[i].get(0); if(p.x==j) p = g[i].get(1); if(k%2==0) ans[p.y] = 2; else ans[p.y]=5; k++; j=i; i = p.x; } for(i=0;i<n-1;i++){ out.print(ans[i]+" "); } out.println(); } out.close(); } /*static long nck(int n , int k){ long a = fact[n]; long b = modInv(fact[k]); b*= modInv(fact[n-k]); b%=mod; return (a*b)%mod; } static void populateFact(){ fact[0]=1; fact[1] = 1; for(i=2;i<300005;i++){ fact[i]=i*fact[i-1]; fact[i]%=mod; } } */ static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long exp(long base, long pow) { if (pow == 0) return 1; long half = exp(base, pow / 2); if (pow % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } static long mul(long a, long b) { return ((a % mod) * (b % mod)) % mod; } static long add(long a, long b) { return ((a % mod) + (b % mod)) % mod; } static long modInv(long x) { return exp(x, mod - 2); } static void ruffleSort(int[] a) { //ruffle int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n), temp = a[i]; a[i] = a[oi]; a[oi] = temp; } //then sort Arrays.sort(a); } static void ruffleSort(long[] a) { //ruffle int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n); long temp = a[i]; a[i] = a[oi]; a[oi] = temp; } Arrays.sort(a); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } static class Pair implements Comparable<Pair> { public int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if (x == o.x) return Integer.compare(y, o.y); return Integer.compare(x, o.x); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
ded4a995a04ed8f9b7bba81d3d3c3b18
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Arrays; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.TreeSet; import java.util.TreeMap; import java.util.PriorityQueue; import java.util.Collections; import java.util.Stack; import java.math.BigInteger; import java.util.LinkedList; import java.util.Iterator; public class First { public static void main(String[] args) { FastScanner fs = new FastScanner(); int T = fs.nextInt(); for (int tt = 0; tt < T; tt++) { solve(fs); } } static void solve(FastScanner fs) { int n=fs.nextInt(); ArrayList<ArrayList<Integer>> g=new ArrayList<>(); for(int i=0;i<n;++i) g.add(new ArrayList<>()); ArrayList<Pair> q=new ArrayList<>(); for(int i=0;i<n-1;++i) { int u=fs.nextInt(); int v=fs.nextInt(); u--; v--; q.add(new Pair(u, v)); g.get(u).add(v); g.get(v).add(u); } map=new TreeMap<>(); if(!dfs(g, 0, -1, 2)) { pn(-1); return ; } // pn(map); // pn(q.size()); for(Pair p:q) { // pn(p); p(map.get(p)+" "); } pn(""); } static TreeMap<Pair, Integer> map; static boolean dfs(ArrayList<ArrayList<Integer>> g, int u, int p, int val) { ArrayList<Integer> nbrs=g.get(u); if(nbrs.size()>2) return false; for(int i=0;i<nbrs.size();++i) { int child=nbrs.get(i); if(p==-1) { if(!dfs(g, child, u, 5-val)) return false; map.put(new Pair(child, u), val); map.put(new Pair(u, child), val); val=3; } else if(child!=p) { if(!dfs(g, child, u, 5-val)) return false; map.put(new Pair(child, u), val); map.put(new Pair(u, child), val); } } return true; } static long MOD=(long)(1e9+7); static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } static void pn(Object o) { System.out.println(o); } static void p(Object o) { System.out.print(o); } static void flush() { System.out.flush(); } static void debugInt(int[] arr) { for(int i=0;i<arr.length;++i) System.out.print(arr[i]+" "); System.out.println(); } static void debugIntInt(int[][] arr) { for(int i=0;i<arr.length;++i) { for(int j=0;j<arr[0].length;++j) System.out.print(arr[i][j]+" "); System.out.println(); } System.out.println(); } static void debugLong(long[] arr) { for(int i=0;i<arr.length;++i) System.out.print(arr[i]+" "); System.out.println(); } static void debugLongLong(long[][] arr) { for(int i=0;i<arr.length;++i) { for(int j=0;j<arr[0].length;++j) System.out.print(arr[i][j]+" "); System.out.println(); } System.out.println(); } static long[] takeLong(int n, FastScanner fs) { long[] arr=new long[n]; for(int i=0;i<n;++i) arr[i]=fs.nextLong(); return arr; } static long[][] takeLongLong(int m, int n, FastScanner fs) { long[][] arr=new long[m][n]; for(int i=0;i<m;++i) for(int j=0;j<n;++j) arr[i][j]=fs.nextLong(); return arr; } static int[] takeInt(int n, FastScanner fs) { int[] arr=new int[n]; for(int i=0;i<n;++i) arr[i]=fs.nextInt(); return arr; } static int[][] takeIntInt(int m, int n, FastScanner fs) { int[][] arr=new int[m][n]; for(int i=0;i<m;++i) for(int j=0;j<n;++j) arr[i][j]=fs.nextInt(); return arr; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static int getDecimalFromBinary(String s) { long no=0; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='1') no++; no=no<<1; } return (int)(no>>1); } static String getBinaryFromDecimal(int x) { StringBuilder sb=new StringBuilder(); for(int i=0;i<31;++i) { if((x&1)==0) sb.append('0'); else sb.append('1'); x=x>>1; } return sb.reverse().toString(); } static boolean[] sieve() { int size=(int)(1e5+5); boolean[] isPrime=new boolean[size]; Arrays.fill(isPrime, true); for(int i=2;i<size;++i) for(int j=2*i;isPrime[i]==true && j<size;j+=i) isPrime[j]=false; return isPrime; } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } } class Pair implements Comparable<Pair> { int u; int v; Pair(int u, int v) { this.u=u; this.v=v; } public int compareTo(Pair o) { if (u!=o.u) return Integer.compare(u, o.u); else return Integer.compare(v, o.v); } public String toString() { return (u+1)+":"+(v+1); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
4776cf5ffc2a64ac94c400458309b8a9
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
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_766_Div2 { public static int MOD = 998244353; 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 T = in.nextInt(); int[] list = {2, 3}; for (int z = 0; z < T; z++) { int n = in.nextInt(); int[][] edge = new int[n - 1][2]; ArrayList<Integer>[] map = new ArrayList[n]; for (int i = 0; i < n; i++) { map[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { for (int j = 0; j < 2; j++) { edge[i][j] = in.nextInt() - 1; map[edge[i][j]].add(i); } } int index = -1; for (int i = 0; i < n; i++) { if (map[i].size() == 1) { index = i; break; } } if (n == 2) { out.println(2); continue; } if (n == 3) { out.println(2 + " " + 3); continue; } LinkedList<Integer> q = new LinkedList<>(); q.add(index); boolean ok = true; int[] re = new int[n - 1]; Arrays.fill(re, -1); int cur = 0; while (!q.isEmpty()) { int v = q.poll(); if (map[v].size() > 2) { ok = false; break; } for (int i : map[v]) { if (re[i] != -1) { continue; } int other = v == edge[i][0] ? edge[i][1] : edge[i][0]; q.add(other); re[i] = list[cur]; } cur = 1 - cur; } //System.out.println(ok); if (!ok) { out.println(-1); continue; } for (int i : re) { out.print(i + " "); } out.println(); } out.close(); } static int abs(int a) { return a < 0 ? -a : a; } 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 { int x; int y; public Point(int start, int end) { this.x = start; this.y = end; } public String toString() { return x + " " + y; } } 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, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return (val * val); } else { return (val * ((val * a))); } } 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
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
1a639e3096061375f3ccae72537cc508
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class C { public static void main(String[] args) { new C().run(); } BufferedReader br; PrintWriter out; long mod = (long) (1e9 + 7), inf = (long) (3e18); class pair { int F, S; pair(int f, int s) { F = f; S = s; } } void solve() { int t = ni(); while(t-- > 0) { //TODO: int n=ni(); ArrayList<Integer>[] adj= new ArrayList[n]; for(int i=0; i<n; i++){ adj[i]=new ArrayList<>(); } int[] degree= new int[n]; HashMap<String, Integer> map= new HashMap<>(); for(int i=0; i<n-1; i++){ int x= ni()-1; int y=ni()-1; adj[x].add(y); adj[y].add(x); degree[x]++; degree[y]++; map.put(getHash(x, y), i); } int i=0; for(; i<n; i++){ if(degree[i]>2){ break; } } if(i<n){ out.println(-1); continue; } int[] res= new int[n]; dfs(0, 0, res, adj, map, 2); for(i=0; i<n-1; i++){ out.print(res[i]+" "); } out.println(); } } private void dfs(int u, int p, int[] res, ArrayList<Integer>[] adj, HashMap<String, Integer> map, int val){ for(int e: adj[u]){ if(e==p){ continue; } int x=map.get(getHash(e, u)); res[x]=5-val; dfs(e, u, res, adj, map, 5-val); val=5-val; } } private String getHash(int u, int v){ if(u>v){ return u+" "+v; } return v+" "+u; } // -------- I/O Template ------------- char nc() { return ns().charAt(0); } String nLine() { try { return br.readLine(); } catch(IOException e) { return "-1"; } } double nd() { return Double.parseDouble(ns()); } long nl() { return Long.parseLong(ns()); } int ni() { return Integer.parseInt(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } StringTokenizer ip; String ns() { if(ip == null || !ip.hasMoreTokens()) { try { ip = new StringTokenizer(br.readLine()); if(ip == null || !ip.hasMoreTokens()) ip = new StringTokenizer(br.readLine()); } catch(IOException e) { throw new InputMismatchException(); } } return ip.nextToken(); } void run() { try { if (System.getProperty("ONLINE_JUDGE") == null) { br = new BufferedReader(new FileReader("/media/ankanchanda/Data1/WORKPLACE/DS and CP/Competitive Programming/VSCODE/IO/input.txt")); out = new PrintWriter("/media/ankanchanda/Data1/WORKPLACE/DS and CP/Competitive Programming/VSCODE/IO/output.txt"); } else { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } catch (FileNotFoundException e) { System.out.println(e); } solve(); out.flush(); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
73feffc36bf0e4a6c06a546b4392c0e0
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; public class C1627{ static FastScanner fs = null; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = fs.nextInt(); while (t-->0) { int n = fs.nextInt(); ArrayList<Pair> list = new ArrayList<>(); ArrayList<ArrayList<Integer>> lis = new ArrayList<>(); ArrayList<ArrayList<Pair>> l2 = new ArrayList<>(); for(int i=0;i<=n;i++){ lis.add(new ArrayList<Integer>()); l2.add(new ArrayList<Pair>()); } int ans = 0; int co[] = new int[n+1]; for(int i=1;i<n;i++){ int u = fs.nextInt(); int v = fs.nextInt(); co[u]+=1; co[v]+=1; lis.get(u).add(v); lis.get(v).add(u); list.add(new Pair(u,v)); if(co[u]==3 || co[v]==3){ ans = -1; } } if(ans!=-1){ int prev[] = new int[n+1]; Arrays.fill(prev,-1); Queue<Integer> queue = new LinkedList<>(); queue.add(1); boolean vis[] = new boolean[n+1]; while (!queue.isEmpty()) { int num = queue.remove(); vis[num] = true; for(Integer p : lis.get(num)){ if(!vis[p]){ int xo = 0; if(prev[num]==-1 && prev[p]==-1){ xo = 2; } else if(prev[num]==-1){ if(prev[p]==2){ xo = 5; } else{ xo = 2; } } else if(prev[p]==-1){ if(prev[num]==2){ xo = 5; } else{ xo = 2; } } prev[num] = xo; prev[p] = xo; l2.get(p).add(new Pair(num,xo)); l2.get(num).add(new Pair(p,xo)); vis[p] = true; queue.add(p); } } } for(Pair p : list){ int u = p.u; for(Pair p2 : l2.get(u)){ if(p2.u==p.v){ out.print(p2.v+" "); } } } } else{ out.print(ans); } out.println(); } out.close(); } static class Pair{ int u; int v; Pair(int u,int v){ this.u = u; this.v = v; } } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
78212ea2e2ec740175dbf02b2ee4f78f
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; public class Main { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); while (t-- > 0) { int n = scanner.nextInt(); int[][] inputOrder = new int[n-1][2]; Map<Integer, List<Integer>> map = new HashMap(); // Get input and Populate graph for (int i=0; i<n-1; i++) { int u = scanner.nextInt()-1; int v = scanner.nextInt()-1; inputOrder[i][0] = u; inputOrder[i][1] = v; if (map.containsKey(u)) { List<Integer> temp = map.get(u); temp.add(v); } else { List<Integer> temp = new ArrayList(); temp.add(v); map.put(u, temp); } if (map.containsKey(v)) { List<Integer> temp = map.get(v); temp.add(u); } else { List<Integer> temp = new ArrayList(); temp.add(u); map.put(v, temp); } } // Check if impossible scenario boolean impossible = false; for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) { List<Integer> valueList = entry.getValue(); if (valueList.size() > 2) { impossible = true; break; } } if (impossible) { System.out.println(-1); continue; } // Actual process int[] visited = new int[n]; Map<Integer, Map<Integer, Integer>> ans = new HashMap(); boolean isTwo = false; for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) { int key = entry.getKey(); if (visited[key] == 1) { continue; } visit(map, key, visited, isTwo, ans); visited[key] = 1; } // Print answer for (int i=0; i<n-1; i++) { int u = inputOrder[i][0]; int v = inputOrder[i][1]; int value = -1; if (ans.containsKey(u)) { Map<Integer, Integer> tempAns = ans.get(u); if (tempAns.containsKey(v)) { value = tempAns.get(v); } else { Map<Integer, Integer> tempAns2 = ans.get(v); value = tempAns2.getOrDefault(u, -1); } } else { Map<Integer, Integer> tempAns = ans.get(v); value = tempAns.getOrDefault(u, -1); } System.out.print(value + " "); } System.out.println(); } } private static void visit(Map<Integer, List<Integer>> map, int key, int[] visited, boolean isTwo, Map<Integer,Map<Integer, Integer>> ans) { List<Integer> valueList = map.get(key); if (visited[key] == 1) { return; } visited[key] = 1; for (int value : valueList) { if (visited[value] == 1) { continue; } int primeNoToAdd = isTwo ? 2 : 5; if (ans.containsKey(key)) { Map<Integer, Integer> toValue = ans.get(key); toValue.put(value, primeNoToAdd); } else { Map<Integer, Integer> toValue = new HashMap<>(); toValue.put(value, primeNoToAdd); ans.put(key, toValue); } visit(map, value, visited, !isTwo, ans); isTwo = !isTwo; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
423319bf4d92fae8228b7d71ab941dfa
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class C_Not_Assigning { static int M = 1_000_000_007; static final PrintWriter out =new PrintWriter(System.out); static final FastReader fs = new FastReader(); static boolean prime[]; public static void main (String[] args) throws java.lang.Exception { int t= fs.nextInt(); for(int i=0;i<t;i++) { int n=fs.nextInt(); ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>(); for(int j=0;j<=n;j++){ al.add(new ArrayList<Integer>()); } HashMap<Integer, Pairs> hm = new HashMap<Integer,Pairs>(); int in[]=new int[n+1]; Arrays.fill(in,0); int ans[]=new int[n-1]; int st=0; boolean ff=false; for(int j=0;j<n-1;j++){ int u=fs.nextInt(); int v=fs.nextInt(); al.get(u).add(v); al.get(v).add(u); in[u]++; in[v]++; if(hm.get(v)==null){ hm.put(v,new Pairs(u,j,-1,-1)); }else{ hm.get(v).c=u; hm.get(v).d=j; } if(hm.get(u)==null){ hm.put(u,new Pairs(v,j,-1,-1)); }else{ hm.get(u).c=v; hm.get(u).d=j; } if(in[u]>2||in[v]>2) ff=true; } for(int j=1;j<=n;j++){ if(in[j]==1) {st=j;} if(in[j]>2) ff=true; } if(ff){ out.println(-1); }else{ int v=2; Arrays.fill(in,0); for(int j=0;j<n-1;j++){ in[st]=1; int next=al.get(st).get(0); if(in[next]==1&&al.get(st).size()==2){ next=al.get(st).get(1); } int ii=-1; if(hm.get(st).a==next) ii=hm.get(st).b; else ii=hm.get(st).d; ans[ii]=v; if(v==2) v=3; else v=2; st=next; } for(int j=0;j<n-1;j++){ out.print(ans[j]+" "); } out.println(); } } out.flush(); } public static long power(long x, long y) { long temp; if (y == 0) return 1; temp = power(x, y / 2); if (y % 2 == 0) return modMult(temp,temp); else { if (y > 0) return modMult(x,modMult(temp,temp)); else return (modMult(temp,temp)) / x; } } static void sieveOfEratosthenes(int n) { prime = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; prime[0]=false; if(1<=n) prime[1]=false; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int [] arrayIn(int n) throws IOException { int arr[] = new int[n]; for(int i=0; i<n; i++) { arr[i] = nextInt(); } return arr; } } public static class Pairs { int a,b,c,d; Pairs(int value, int index,int cc,int dd) { this.a = value; this.b = index; c=cc; d=dd; } } static final Random random = new Random(); static void ruffleSort(int arr[]) { int n = arr.length; for(int i=0; i<n; i++) { int j = random.nextInt(n),temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } static long nCk(int n, int k) { return (modMult(fact(n),fastexp(modMult(fact(n-k),fact(k)),M-2))); } static long fact (long n) { long fact =1; for(int i=1; i<=n; i++) { fact = modMult(fact,i); } return fact%M; } static long modMult(long a,long b) { return a*b%M; } static long fastexp(long x, int y){ if(y==1) return x; long ans = fastexp(x,y/2); if(y%2 == 0) return modMult(ans,ans); else return modMult(ans,modMult(ans,x)); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
151f7c7c8f63214c71c7de37da052a4f
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; //import java.text.DecimalFormat; import java.util.*; public class Codeforces { static int mod=1000000007; static class Node{ int x,y; Node(int x,int y){ this.x=x; this.y=y; } } static boolean vst[]; static List<Integer> adj[]; static int in[]; static Map<Integer,Map<Integer,Integer> > map; static List<Integer> list=new ArrayList<>(); public static void main(String[] args) throws Exception { FastScanner fs=new FastScanner(); PrintWriter out=new PrintWriter(System.out); // boolean isp[]=new boolean[100005]; // soe(isp); // List<Integer> p=new ArrayList<>(); // for(int i=2;i<isp.length;i++) if(isp[i]) p.add(i); int t=fs.nextInt(); outer:while(t-->0) { int n=fs.nextInt(); vst=new boolean[n]; adj=new ArrayList[n]; for(int i=0;i<n;i++) adj[i]=new ArrayList<>(); Set<Integer> [] set=new HashSet[n]; for(int i=0;i<n;i++) set[i]=new HashSet<>(); map=new HashMap<>(); in=new int[n]; List<Integer> ans=new ArrayList<>(); list.clear(); for(int i=0;i<n-1;i++) { int u=fs.nextInt()-1, v=fs.nextInt()-1; adj[v].add(u); adj[u].add(v); in[v]++; in[u]++; list.add(u); list.add(v); } for(int i=0;i<n;i++) if(in[i]>2) { out.println(-1); continue outer; } for(int i=0;i<n;i++) { if(in[i]==1) { dfs(i,-1,0); } } // dfs(0,-1,0); for(int i=0;i<list.size();i+=2) { int u=list.get(i) , v=list.get(i+1); out.print(map.get(u).get(v)+" "); } out.println(); } out.close(); } static void dfs(int c,int p,int last) { if(vst[c]) return; vst[c]=true; if(p!=-1) { if(!map.containsKey(c)) map.put(c, new HashMap<>()); if(!map.containsKey(p)) map.put(p, new HashMap<>()); if(last==2) { last=11; map.get(p).put(c, 11); map.get(c).put(p, 11); } else { map.get(p).put(c, 2); map.get(c).put(p, 2); last=2; } } else { } for(int cur:adj[c]) { if(cur!=p) dfs(cur,c,last); } } static void find(int n,int m) { } static void soe(boolean arr[]) { Arrays.fill(arr, true); int n=arr.length; arr[0]=arr[1]=false; for(int i=2;i*i<n;i++) { if(!arr[i]) continue; for(int j=2*i;j<n;j+=i) arr[j]=false; } } static long pow(long a,long b) { if(b<0) return 1; long res=1; while(b!=0) { if((b&1)!=0) { res*=a; res%=mod; } a*=a; a%=mod; b=b>>1; } return res; } static long gcd(long a,long b) { if(b==0) return a; return gcd(b,a%b); } static long nck(int n,int k) { if(k>n) return 0; long res=1; res*=fact(n); res%=mod; res*=modInv(fact(k)); res%=mod; res*=modInv(fact(n-k)); res%=mod; return res; } static long fact(long n) { // return fact[(int)n]; long res=1; for(int i=2;i<=n;i++) { res*=i; res%=mod; } return res; } static long modInv(long n) { return pow(n,mod-2); } static void sort(int[] a) { //suffle int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n); int temp=a[i]; a[i]=a[oi]; a[oi]=temp; } //then sort Arrays.sort(a); } // Use this to input code since it is faster than a Scanner static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long[] lreadArray(int n) { long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
d1a280c7cd59d2c5fd31dbd384a83460
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; public final class A { static List<List<Pair>> adj; static class Pair{ int v; int idx; public Pair(int v, int idx) { this.v = v; this.idx = idx; } } public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int T= fs.nextInt(); while(T-- > 0){ int N = fs.nextInt(); adj = new ArrayList<>(); for(int i = 0; i < N; ++i) adj.add(new ArrayList<>()); for(int i = 0; i < N - 1; ++i){ int u = fs.nextInt() - 1; int v = fs.nextInt() - 1; adj.get(u).add(new Pair(v, i)); adj.get(v).add(new Pair(u, i)); } ss(N); } } static void ss(int N){ for(int i = 0; i < N; ++i){ if(adj.get(i).size() >= 3){ System.out.println(-1); return; } } int[] edges = new int[N - 1]; for(int i= 0; i < adj.get(0).size(); ++i){ Pair nbrs = adj.get(0).get(i); edges[nbrs.idx] = (i % 2 == 0 ? 2 : 5); solve(nbrs.v, edges, 0, edges[nbrs.idx]); } StringBuilder sb = new StringBuilder(); for(int i = 0; i < (N - 1); ++i){ sb.append(String.valueOf(edges[i]) + " "); } System.out.println(sb.toString()); } static void solve(int src, int[] edges, int par, int prev){ for(Pair nbrs: adj.get(src)){ if(nbrs.v != par){ edges[nbrs.idx] = (prev == 2 ? 5 : 2); solve(nbrs.v, edges, src, edges[nbrs.idx]); } } } static final Random random=new Random(); static final int mod=1_000_000_007; static long add(long a, long b) { return (a+b)%mod; } static long sub(long a, long b) { return ((a-b)%mod+mod)%mod; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static long mul(long a, long b) { return (a*b)%mod; } static long exp(long base, long exp) { if (exp==0) return 1; long half=exp(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials=new long[2_000_001]; static long[] invFactorials=new long[2_000_001]; static void precompFacts() { factorials[0]=invFactorials[0]=1; for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i); invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2); for (int i=invFactorials.length-2; i>=0; i--) invFactorials[i]=mul(invFactorials[i+1], i+1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k])); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
908202e73775011ac3179521031341b8
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
//created by Whiplash99 import java.io.*; import java.util.*; public class C { private static ArrayDeque<Integer>[] edge; private static HashMap<String,Integer> map; private static String getHash(int u, int v) { if(u>v) { int tmp=u; u=v; v=tmp; } return u+" "+v; } private static void DFS(int u, int p, int[] ans, int val) { for(int v:edge[u]) { if(v==p) continue; ans[map.get(getHash(u,v))]=val; DFS(v,u,ans,5-val); val=5-val; } } public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,N; int T=Integer.parseInt(br.readLine().trim()); StringBuilder sb=new StringBuilder(); while (T-->0) { N=Integer.parseInt(br.readLine().trim()); edge=new ArrayDeque[N]; for(i=0;i<N;i++) edge[i]=new ArrayDeque<>(); map=new HashMap<>(); int[] ans=new int[N-1]; int[] deg=new int[N]; for(i=0;i<N-1;i++) { String[] s=br.readLine().trim().split(" "); int u=Integer.parseInt(s[0])-1; int v=Integer.parseInt(s[1])-1; edge[u].add(v); edge[v].add(u); deg[u]++; deg[v]++; map.put(getHash(u,v),i); } for(i=0;i<N;i++) if(deg[i]>2) break; if(i<N) { sb.append(-1).append("\n"); continue; } DFS(0,0,ans,2); for(int x:ans) sb.append(x).append(" "); sb.append("\n"); } System.out.println(sb); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
3b9b3b9fdc073faf48461ed469d47923
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
/** * check out my youtube channel sh0rkyboy * https://tinyurl.com/zdxe2y4z * I do screencasts, solutions, and other fun stuff in the future */ import java.util.*; import java.io.*; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.Math.max; public class EdC { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; static ArrayList<ArrayList<Integer>> graph; public static PrintWriter out; static Map<Long, Integer> mp; public static void main(String[] largewang) throws Exception{ // TODO Auto-generated method stub sc = new MyScanner(); out = new PrintWriter(System.out); int t = sc.nextInt(); while (t-->0) { int n = sc.nextInt(); int[] degrees = new int[n+1]; graph = new ArrayList<>(); for (int j = 0;j<=n;j++){ graph.add(new ArrayList<>()); } mp = new HashMap<>(); ArrayList<Edge> arr = new ArrayList<>(); for (int j = 0;j<n-1;j++){ int v1 = sc.nextInt(); int v2 = sc.nextInt(); graph.get(v1).add(v2); graph.get(v2).add(v1); degrees[v1]++; degrees[v2]++; arr.add(new Edge(v1, v2)); } if (n == 2){ out.println("2"); } else if (n == 3){ out.println("2 3"); } else{ int threecount = 0; int one = 0; for (int j = 1;j<=n;j++){ if (degrees[j] >= 3) { threecount++; } if (degrees[j] == 1) { one = j; } } if (threecount > 0){ out.println(-1); } else { dfs(one, -1, 3); for (Edge e : arr) { out.print(mp.get(e.v1*100001L + e.v2) + " "); } out.println(); } } } out.close(); } public static void dfs(int v, int p, int prevNum) { for (int child : graph.get(v)) { if (child == p) continue; long t1 = 100001L*child + v; long t2 = 100001L*v + child; mp.put(t1, 5-prevNum); mp.put(t2, 5-prevNum); dfs(child, v, 5-prevNum); } } static class Edge{ private int v1; private int v2; public Edge(int v1, int v2) { super(); this.v1 = v1; this.v2 = v2; } } public static void sort(int[] array){ ArrayList<Integer> copy = new ArrayList<>(); for (int i : array) copy.add(i); Collections.sort(copy); for(int i = 0;i<array.length;i++) array[i] = copy.get(i); } static String[] readArrayString(int n){ String[] array = new String[n]; for(int j =0 ;j<n;j++) array[j] = sc.next(); return array; } static int[] readArrayInt(int n){ int[] array = new int[n]; for(int j = 0;j<n;j++) array[j] = sc.nextInt(); return array; } static int[] readArrayInt1(int n){ int[] array = new int[n+1]; for(int j = 1;j<=n;j++){ array[j] = sc.nextInt(); } return array; } static long[] readArrayLong(int n){ long[] array = new long[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextLong(); return array; } static double[] readArrayDouble(int n){ double[] array = new double[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextDouble(); return array; } static int minIndex(int[] array){ int minValue = Integer.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(long[] array){ long minValue = Long.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(double[] array){ double minValue = Double.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } public static int power(long x, long y, long mod){ long ans = 1; while(y>0){ if (y%2==1) ans = (ans*x)%mod; x = (x*x)%mod; y/=2; } return (int)(ans); } static void verdict(boolean a){ out.println(a ? "YES" : "NO"); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } //StringJoiner sj = new StringJoiner(" "); //sj.add(strings) //sj.toString() gives string of those stuff w spaces or whatever that sequence is
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
a89242eb9d5c1f07b1d4a453ee33b3f8
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
/* Setting up my ambitions Check 'em one at a time, yeah, I made it Now it's time for ignition I'm the start, heat it up They follow, burning up a chain reaction, oh-oh-oh Go fire it up, oh, oh, no Assemble the crowd now, now Line 'em up on the ground No leaving anyone behind */ import static java.lang.Math.*; import java.util.*; import java.io.*; import java.math.*; public class x1627C { static ArrayDeque<Edge>[] edges; public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); outer:while(T-->0) { st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); edges = new ArrayDeque[N]; for(int i=0; i < N; i++) edges[i] = new ArrayDeque<Edge>(); for(int i=1; i < N; i++) { st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken())-1; int b = Integer.parseInt(st.nextToken())-1; edges[a].add(new Edge(b, i-1)); edges[b].add(new Edge(a, i-1)); } //must be line int head = -1; for(int v=0; v < N; v++) { if(edges[v].size() >= 3) { sb.append("-1\n"); continue outer; } if(edges[v].size() == 1) head = v; } int[] res = new int[N-1]; int weight = 2; int prev = -1; int curr = head; while(true) { if(edges[curr].size() == 1 && prev != -1) break; //get next for(Edge e: edges[curr]) if(e.to != prev) { prev = curr; curr = e.to; res[e.id] = weight; break; } weight ^= 1; } for(int v=0; v < N-1; v++) sb.append(res[v]+" "); sb.append("\n"); } System.out.print(sb); } public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception { int[] arr = new int[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); return arr; } } class Edge { public int to; public int id; public Edge(int a, int b) { to = a; id = b; } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
3b7b98dcfa9aeec519a9032a94d15699
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; /** * * @author eslam */ public class Solution { // Beginning of the solution static Kattio input = new Kattio(); static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); static ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>(); static ArrayList<LinkedList<Integer>> allprem = new ArrayList<>(); static ArrayList<LinkedList<String>> allprems = new ArrayList<>(); static ArrayList<Long> luc = new ArrayList<>(); static long mod = (long) (1e9 + 7); static int grid[][] = {{0, 0, 1, -1, 1, 1, -1, -1}, {1, -1, 0, 0, 1, -1, 1, -1}}; static long dp[][][]; static double cmp = 1e-7; static final double pi = 3.14159265359; static int[] ans; public static void main(String[] args) throws IOException { // Kattio input = new Kattio("input"); // BufferedWriter log = new BufferedWriter(new FileWriter(f)); int test = input.nextInt(); loop: for (int co = 1; co <= test; co++) { int n = input.nextInt(); ArrayList<Integer> a[] = new ArrayList[n + 1]; TreeMap<pair, Integer> edges = new TreeMap<>(cmpPair()); ans = new int[n - 1]; for (int i = 0; i <= n; i++) { a[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int x = input.nextInt(); int y = input.nextInt(); a[x].add(y); a[y].add(x); edges.put(new pair(Math.max(x, y), Math.min(x, y)), i); } for (int i = 0; i <= n; i++) { if (a[i].size() > 2) { log.write("-1\n"); continue loop; } } dfs(1, a, new boolean[n + 1], true, edges); for (int i = 0; i < n - 1; i++) { log.write(ans[i] + " "); } log.write("\n"); } log.flush(); } static void dfs(int node, ArrayList<Integer> g[], boolean vi[], boolean ca, TreeMap<pair, Integer> edges) { vi[node] = true; for (Integer ch : g[node]) { if (!vi[ch]) { if (ca) { ans[edges.get(new pair(Math.max(node, ch), Math.min(node, ch)))] = 2; } else { ans[edges.get(new pair(Math.max(node, ch), Math.min(node, ch)))] = 5; } dfs(ch, g, vi, !ca, edges); ca = !ca; } } } static long f(long x) { return (long) ((x * (x + 1) / 2) % mod); } static long Sub(long x, long y) { long z = x - y; if (z < 0) { z += mod; } return z; } static long add(long a, long b) { a += b; if (a >= mod) { a -= mod; } return a; } static long mul(long a, long b) { return (long) ((long) a * b % mod); } static long powlog(long base, long power) { if (power == 0) { return 1; } long x = powlog(base, power / 2); x = mul(x, x); if ((power & 1) == 1) { x = mul(x, base); } return x; } static long modinv(long x) { return fast_pow(x, mod - 2, mod); } static long Div(long x, long y) { return mul(x, modinv(y)); } static void floodFill(int r, int c, int a[][], boolean vi[][], int w[][], int d) { vi[r][c] = true; for (int i = 0; i < 4; i++) { int nr = grid[0][i] + r; int nc = grid[1][i] + c; if (isValid(nr, nc, a.length, a[0].length)) { if (Math.abs(a[r][c] - a[nr][nc]) <= d && !vi[nr][nc]) { floodFill(nr, nc, a, vi, w, d); } } } } static boolean isdigit(char ch) { return ch >= '0' && ch <= '9'; } static boolean lochar(char ch) { return ch >= 'a' && ch <= 'z'; } static boolean cachar(char ch) { return ch >= 'A' && ch <= 'Z'; } static class Pa { long x; long y; public Pa(long x, long y) { this.x = x; this.y = y; } } static long sqrt(long v) { long max = (long) 4e9; long min = 0; long ans = 0; while (max >= min) { long mid = (max + min) / 2; if (mid * mid > v) { max = mid - 1; } else { ans = mid; min = mid + 1; } } return ans; } static long cbrt(long v) { long max = (long) 3e6; long min = 0; long ans = 0; while (max >= min) { long mid = (max + min) / 2; if (mid * mid > v) { max = mid - 1; } else { ans = mid; min = mid + 1; } } return ans; } static void prefixSum2D(long arr[][]) { for (int i = 0; i < arr.length; i++) { prefixSum(arr[i]); } for (int i = 0; i < arr[0].length; i++) { for (int j = 1; j < arr.length; j++) { arr[j][i] += arr[j - 1][i]; } } } public static long baseToDecimal(String w, long base) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(base, l); r = r + x; l++; } return r; } static int bs(int v, ArrayList<Integer> a) { int max = a.size() - 1; int min = 0; int ans = 0; while (max >= min) { int mid = (max + min) / 2; if (a.get(mid) >= v) { ans = a.size() - mid; max = mid - 1; } else { min = mid + 1; } } return ans; } static Comparator<tri> cmpTri() { Comparator<tri> c = new Comparator<tri>() { @Override public int compare(tri o1, tri o2) { if (o1.x > o2.x) { return 1; } else if (o1.x < o2.x) { return -1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { if (o1.z > o2.z) { return 1; } else if (o1.z < o2.z) { return -1; } else { return 0; } } } } }; return c; } static Comparator<pair> cmpPair2() { Comparator<pair> c = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { if (o1.x > o2.x) { return -1; } else if (o1.x < o2.x) { return 1; } else { return 0; } } } }; return c; } static Comparator<pair> cmpPair() { Comparator<pair> c = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.x > o2.x) { return -1; } else if (o1.x < o2.x) { return 1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { return 0; } } } }; return c; } static class rec { long x1; long x2; long y1; long y2; public rec(long x1, long y1, long x2, long y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public long getArea() { return (x2 - x1) * (y2 - y1); } } static long sumOfRange(int x1, int y1, int x2, int y2, long a[][]) { return (a[x2][y2] - a[x1 - 1][y2] - a[x2][y1 - 1]) + a[x1 - 1][y1 - 1]; } public static int[][] bfs(int i, int j, String w[]) { Queue<pair> q = new ArrayDeque<>(); q.add(new pair(i, j)); int dis[][] = new int[w.length][w[0].length()]; for (int k = 0; k < w.length; k++) { Arrays.fill(dis[k], -1); } dis[i][j] = 0; while (!q.isEmpty()) { pair p = q.poll(); int cost = dis[p.x][p.y]; for (int k = 0; k < 4; k++) { int nx = p.x + grid[0][k]; int ny = p.y + grid[1][k]; if (isValid(nx, ny, w.length, w[0].length())) { if (dis[nx][ny] == -1 && w[nx].charAt(ny) == '.') { q.add(new pair(nx, ny)); dis[nx][ny] = cost + 1; } } } } return dis; } public static void graphRepresintion(ArrayList<Integer>[] a, int q) throws IOException { for (int i = 0; i < a.length; i++) { a[i] = new ArrayList<>(); } while (q-- > 0) { int x = input.nextInt(); int y = input.nextInt(); a[x].add(y); a[y].add(x); } } public static boolean isValid(int i, int j, int n, int m) { return (i > -1 && i < n) && (j > -1 && j < m); } // present in the left and right indices public static int[] swap(int data[], int left, int right) { // Swap the data int temp = data[left]; data[left] = data[right]; data[right] = temp; // Return the updated array return data; } // Function to reverse the sub-array // starting from left to the right // both inclusive public static int[] reverse(int data[], int left, int right) { // Reverse the sub-array while (left < right) { int temp = data[left]; data[left++] = data[right]; data[right--] = temp; } // Return the updated array return data; } // Function to find the next permutation // of the given integer array public static boolean findNextPermutation(int data[]) { // If the given dataset is empty // or contains only one element // next_permutation is not possible if (data.length <= 1) { return false; } int last = data.length - 2; // find the longest non-increasing suffix // and find the pivot while (last >= 0) { if (data[last] < data[last + 1]) { break; } last--; } // If there is no increasing pair // there is no higher order permutation if (last < 0) { return false; } int nextGreater = data.length - 1; // Find the rightmost successor to the pivot for (int i = data.length - 1; i > last; i--) { if (data[i] > data[last]) { nextGreater = i; break; } } // Swap the successor and the pivot data = swap(data, nextGreater, last); // Reverse the suffix data = reverse(data, last + 1, data.length - 1); // Return true as the next_permutation is done return true; } // public static pair[] dijkstra(int node, ArrayList<pair> a[]) { // PriorityQueue<tri> q = new PriorityQueue<>(new Comparator<tri>() { // @Override // public int compare(tri o1, tri o2) { // if (o1.y > o2.y) { // return 1; // } else if (o1.y < o2.y) { // return -1; // } else { // return 0; // } // } // }); // q.add(new tri(node, 0, -1)); // pair distance[] = new pair[a.length]; // while (!q.isEmpty()) { // tri p = q.poll(); // int cost = p.y; // if (distance[p.x] != null) { // continue; // } // distance[p.x] = new pair(p.z, cost); // ArrayList<pair> nodes = a[p.x]; // for (pair node1 : nodes) { // if (distance[node1.x] == null) { // tri pa = new tri(node1.x, cost + node1.y, p.x); // q.add(pa); // } // } // } // return distance; // } public static String revs(String w) { String ans = ""; for (int i = w.length() - 1; i > -1; i--) { ans += w.charAt(i); } return ans; } public static boolean isPalindrome(String w) { for (int i = 0; i < w.length() / 2; i++) { if (w.charAt(i) != w.charAt(w.length() - i - 1)) { return false; } } return true; } public static void getPowerSet(Queue<Integer> a) { int n = a.poll(); if (!a.isEmpty()) { getPowerSet(a); } int s = powerSet.size(); for (int i = 0; i < s; i++) { ArrayList<Integer> ne = new ArrayList<>(); ne.add(n); for (int j = 0; j < powerSet.get(i).size(); j++) { ne.add(powerSet.get(i).get(j)); } powerSet.add(ne); } ArrayList<Integer> p = new ArrayList<>(); p.add(n); powerSet.add(p); } public static int getlo(int va) { int v = 1; while (v <= va) { if ((va&v) != 0) { return v; } v <<= 1; } return 0; } static long fast_pow(long a, long p, long mod) { long res = 1; while (p > 0) { if (p % 2 == 0) { a = (a * a) % mod; p /= 2; } else { res = (res * a) % mod; p--; } } return res; } public static int countPrimeInRange(int n, boolean isPrime[]) { int cnt = 0; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = i * 2; j <= n; j += i) { isPrime[j] = false; } } } for (int i = 2; i <= n; i++) { if (isPrime[i]) { cnt++; } } return cnt; } public static void create(long num) { luc.add(num); if (num > power(10, 9)) { return; } create(num * 10 + 4); create(num * 10 + 7); } public static long ceil(long a, long b) { return (a + b - 1) / b; } public static long round(long a, long b) { if (a < 0) { return (a - b / 2) / b; } return (a + b / 2) / b; } public static void allPremutationsst(LinkedList<String> l, boolean visited[], ArrayList<String> st) { if (l.size() == st.size()) { allprems.add(l); } for (int i = 0; i < st.size(); i++) { if (!visited[i]) { visited[i] = true; LinkedList<String> nl = new LinkedList<>(); for (String x : l) { nl.add(x); } nl.add(st.get(i)); allPremutationsst(nl, visited, st); visited[i] = false; } } } public static void allPremutations(LinkedList<Integer> l, boolean visited[], int a[]) { if (l.size() == a.length) { allprem.add(l); } for (int i = 0; i < a.length; i++) { if (!visited[i]) { visited[i] = true; LinkedList<Integer> nl = new LinkedList<>(); for (Integer x : l) { nl.add(x); } nl.add(a[i]); allPremutations(nl, visited, a); visited[i] = false; } } } public static int binarySearch(long[] a, long value) { int l = 0; int r = a.length - 1; while (l <= r) { int m = (l + r) / 2; if (a[m] == value) { return m; } else if (a[m] > value) { r = m - 1; } else { l = m + 1; } } return -1; } public static void reverse(int l, int r, char ch[]) { for (int i = 0; i < r / 2; i++) { char c = ch[i]; ch[i] = ch[r - i - 1]; ch[r - i - 1] = c; } } public static long logK(long v, long k) { int ans = 0; while (v > 1) { ans++; v /= k; } return ans; } public static long power(long a, long p) { long res = 1; while (p > 0) { if (p % 2 == 0) { a = (a * a); p /= 2; } else { res = (res * a); p--; } } return res; } public static long get(long max, long x) { if (x == 1) { return max; } int cnt = 0; while (max > 0) { cnt++; max /= x; } return cnt; } public static int numOF0(long v) { long x = 1; int cnt = 0; while (x <= v) { if ((x & v) == 0) { cnt++; } x <<= 1; } return cnt; } public static int log2(double n) { int cnt = 0; while (n > 1) { n /= 2; cnt++; } return cnt; } public static int[] bfs(int node, ArrayList<Integer> a[]) { Queue<Integer> q = new LinkedList<>(); q.add(node); int distances[] = new int[a.length]; Arrays.fill(distances, -1); distances[node] = 0; while (!q.isEmpty()) { int parent = q.poll(); ArrayList<Integer> nodes = a[parent]; int cost = distances[parent]; for (Integer node1 : nodes) { if (distances[node1] == -1) { q.add(node1); distances[node1] = cost + 1; } } } return distances; } public static void primeFactors(int n, HashMap<Integer, ArrayList<Integer>> h, int ind) { boolean ca = true; while (n % 2 == 0) { if (ca) { if (h.get(2) == null) { h.put(2, new ArrayList<>()); } h.get(2).add(ind); ca = false; } n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { ca = true; while (n % i == 0) { if (ca) { if (h.get(i) == null) { h.put(i, new ArrayList<>()); } h.get(i).add(ind); ca = false; } n /= i; } if (n < i) { break; } } if (n > 2) { if (h.get(n) == null) { h.put(n, new ArrayList<>()); } h.get(n).add(ind); } } // end of solution public static BigInteger ff(long n) { if (n <= 1) { return BigInteger.ONE; } long t = n - 1; BigInteger b = new BigInteger(t + ""); BigInteger ans = new BigInteger(n + ""); while (t > 1) { ans = ans.multiply(b); b = b.subtract(BigInteger.ONE); t--; } return ans; } public static long factorial(long n) { if (n <= 1) { return 1; } long t = n - 1; while (t > 1) { n = mod((mod(n, mod) * mod(t, mod)), mod); t--; } return n; } public static long rev(long n) { long t = n; long ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans; } public static boolean isPalindrome(int n) { int t = n; int ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans == n; } static class tri { int x, y; long z; public tri(int x, int y, long z) { this.x = x; this.y = y; this.z = z; } @Override public String toString() { return x + " " + y + " " + z; } } static boolean isPrime(long num) { if (num == 1) { return false; } if (num == 2) { return true; } if (num % 2 == 0) { return false; } if (num == 3) { return true; } for (long i = 3; i * i <= num; i += 2) { if (num % i == 0) { return false; } } return true; } public static void prefixSum(long[] a) { for (int i = 1; i < a.length; i++) { a[i] = a[i] + a[i - 1]; } } public static void suffixSum(long[] a) { for (int i = a.length - 2; i > -1; i--) { a[i] = a[i] + a[i + 1]; } } static long mod(long a, long b) { long r = a % b; return r < 0 ? r + b : r; } public static long binaryToDecimal(String w) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(2, l); r = r + x; l++; } return r; } public static String decimalAnyBase(long n, long base) { String w = ""; while (n > 0) { w = n % base + w; n /= base; } return w; } public static String decimalToBinary(long n) { String w = ""; while (n > 0) { w = n % 2 + w; n /= 2; } return w; } public static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } public static void print(long[] a) throws IOException { for (int i = 0; i < a.length; i++) { log.write(a[i] + " "); } log.write("\n"); } public static void read(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = input.nextInt(); } } static class gepair { long x; long y; public gepair(long x, long y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pair { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pai { long x; int y; public pai(long x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } public static long LCM(long x, long y) { return x / GCD(x, y) * y; } public static long GCD(long x, long y) { if (y == 0) { return x; } return GCD(y, x % y); } public static void simplifyTheFraction(int a, int b) { long GCD = GCD(a, b); System.out.println(a / GCD + " " + b / GCD); } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(problemName + ".out"); r = new BufferedReader(new FileReader(problemName)); } // returns null if no more input String nextLine() { String str = ""; try { str = r.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(r.readLine()); } return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
81d705bbeb71d9ceefdb991b09e97463
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
/* || श्री राम समर्थ || || जय जय रघुवीर समर्थ || */ import java.io.*; import java.util.*; import static java.util.Arrays.sort; public class CodeforcesTemp { static Reader scan = new Reader(); static FastPrinter out = new FastPrinter(); static List<Integer>[] li; static Map<Pair,Integer> mp; public static void main(String[] args) throws IOException { int tt = scan.nextInt(); // int tt = 1; StringBuilder sb = new StringBuilder(); outer: for (int tc = 1; tc <= tt; tc++) { int n = scan.nextInt(); li = new List[n + 1]; for (int i = 0; i <=n ; i++) { li[i]=new ArrayList<>(); } int[][] arr=new int[n][2]; mp=new HashMap<>(); for (int i = 0; i < n-1; i++) { int x = scan.nextInt(); int y = scan.nextInt(); li[x].add(y); li[y].add(x); arr[i][0]=x;arr[i][1]=y; } for (int i = 1; i <= n; i++) { if (li[i].size() >= 3) { sb.append("-1"); sb.append("\n"); continue outer; } } int[] vis=new int[n+1]; int leaf=dfs(1,vis); vis=new int[n+1]; dfs2(leaf,2,vis); for (int i = 0; i < n-1; i++) { int x=arr[i][0]; int y=arr[i][1]; if(mp.containsKey(new Pair(x,y))){ sb.append(mp.get(new Pair(x,y))); }else { sb.append(mp.get(new Pair(y,x))); } sb.append(" "); } sb.append("\n"); } out.println(sb.toString()); out.flush(); out.close(); } private static void dfs2(int v, int s,int[] vis) { vis[v]=1; for (int i = 0; i < li[v].size(); i++) { int v2=li[v].get(i); if(vis[v2]==1)continue; else{ mp.put(new Pair(v,v2),s); if(s==2)dfs2(v2,5,vis); else dfs2(v2,2,vis); } } } private static int dfs(int v ,int[] vis) { if(li[v].size()==1)return v; vis[v]=1; for (int i = 0; i < li[v].size(); i++) { int v2=li[v].get(i); if(vis[v2]==1)continue; else return dfs(v2,vis); } return -1; } static class Pair { long a, b; public Pair(long a, long b) { this.a = a; this.b = b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair p = ( Pair) o; return a == p.a && b == p.b; } @Override public int hashCode() { return Objects.hash(a, b); } } static class Reader { private final InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public Reader(InputStream in) { this.in = in; } public Reader() { this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("not number")); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("not number")); } } } } throw new ArithmeticException( String.format(" overflows long.")); } n = n * 10 + digit; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(long length) { long[] array = new long[(int) length]; for (int i = 0; i < length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = this.nextInt(); return array; } public Integer[] nextIntegerArray(int length) { Integer[] array = new Integer[length]; for (int i = 0; i < length; i++) array[i] = this.nextInt(); return array; } public int[][] nextIntArrayMulti(int length, int width) { int[][] arrays = new int[width][length]; for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) arrays[j][i] = this.nextInt(); } return arrays; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width) { long[][] mat = new long[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width) { int[][] mat = new int[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width) { double[][] mat = new double[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width) { char[][] mat = new char[height][width]; for (int h = 0; h < height; h++) { String s = this.next(); for (int w = 0; w < width; w++) { mat[h][w] = s.charAt(w); } } return mat; } } static class FastPrinter extends PrintWriter { public FastPrinter(PrintStream stream) { super(stream); } public FastPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printArray(int[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(int[] array) { this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n - 1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(long[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(long[] array) { this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n - 1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map) { this.printArray(array, " ", map); } public void printMatrix(int[][] arr) { for (int i = 0; i < arr.length; i++) { this.printArray(arr[i]); } } public void printCharMatrix(char[][] arr, int n, int m) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { this.print(arr[i][j] + " "); } this.println(); } } } static Random __r = new Random(); static int randInt(int min, int max) { return __r.nextInt(max - min + 1) + min; } static void reverse(int[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(long[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(double[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(char[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(char[] arr, int i, int j) { while (i < j) { char temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; i++; j--; } } static void reverse(int[] arr, int i, int j) { while (i < j) { int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; i++; j--; } } static void reverse(long[] arr, int i, int j) { while (i < j) { long temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; i++; j--; } } static void shuffle(int[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(long[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } private static int getlowest(int l) { if (l >= 1000000000) return 1000000000; if (l >= 100000000) return 100000000; if (l >= 10000000) return 10000000; if (l >= 1000000) return 1000000; if (l >= 100000) return 100000; if (l >= 10000) return 10000; if (l >= 1000) return 1000; if (l >= 100) return 100; if (l >= 10) return 10; return 1; } static void shuffle(double[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void rsort(int[] a) { shuffle(a); sort(a); } static void rsort(long[] a) { shuffle(a); sort(a); } static void rsort(double[] a) { shuffle(a); sort(a); } static int[] copy(int[] a) { int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static long[] copy(long[] a) { long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static double[] copy(double[] a) { double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static char[] copy(char[] a) { char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
dccd86ae44d977054bb71d83fedcb55d
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
/* Author:-crazy_coder- */ import java.io.*; import java.util.*; public class cp{ static long mod=998244353; static int ans=0; static int[] par=new int[100005]; static int[] rank=new int[100005]; static BufferedReader br=new BufferedReader (new InputStreamReader(System.in)); static PrintWriter pw=new PrintWriter(System.out); public static void main(String[] args)throws Exception{ int T=Integer.parseInt(br.readLine()); // int t=1; // comp(); // int T=1; while(T-->0) { solve(); } pw.flush(); } static int base; public static void solve()throws Exception { String[] str=br.readLine().split(" "); int n=Integer.parseInt(str[0]); // int x=Integer.parseInt(str[1]); ArrayList<Integer>[] adjList=new ArrayList[n+1]; for(int i=0;i<=n;i++)adjList[i]=new ArrayList<>(); int[] cnt=new int[n+1]; HashMap<PPair,Integer> map=new HashMap<>(); for(int i=1;i<n;i++) { str=br.readLine().split(" "); int u=Integer.parseInt(str[0]); int v=Integer.parseInt(str[1]); adjList[u].add(v); adjList[v].add(u); map.put(new PPair(u,v),i); map.put(new PPair(v,u),i); cnt[u]++;cnt[v]++; } int st=0; for(int i=1;i<=n;i++) { if(cnt[i]>2) { pw.println(-1); return; }else if(cnt[i]==1) { st=i; } } Queue<Integer> q=new ArrayDeque<>(); q.add(st); boolean[] visited=new boolean[n+1]; int[] ans=new int[n]; int wt=2; while(q.size()>0) { int rem=q.remove(); visited[rem]=true; for(int i=0;i<adjList[rem].size();i++) { int c=adjList[rem].get(i); if(visited[c]==false) { PPair p=new PPair(rem,c); // if(map.containsKey(p))System.out.println("roshan"); // System.out.println("Kumar"); int idx=map.get(p); ans[idx]=wt; wt=5-wt; q.add(c); } } } for(int i=1;i<n;i++) { pw.print(ans[i]+" "); } pw.println(); } public static class PPair { int u,v,hashCode; PPair(int u,int v) { this.u=u; this.v=v; this.hashCode = Objects.hash(u, v); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PPair that = (PPair) o; return u == that.u && v == that.v; } @Override public int hashCode() { return this.hashCode; } } /*********************************************nge********************************************* */ public static int[] nextGreaterElement(int[] arr,int n) { // 1 indexing int[] nge=new int[n+1]; Stack<Pair> st=new Stack<>(); for(int i=n;i>0;i--) { while(st.size()>0&&st.peek().val<=arr[i])st.pop(); if(st.size()==0) { nge[i]=n+1; }else { nge[i]=st.peek().idx; } st.push(new Pair(arr[i],i)); } return nge; } public static int powerOf2(long n ) { int ans=0; while(n%2==0) { n/=2; ans++; } return ans; } public static long NCR(int n,int r){ if(r==0||r==n)return 1; return (fac[n]*invfact[r]%mod)*invfact[n-r]%mod; } static long[] fac=new long[100]; static long[] invfact=new long[100]; public static void comp(){ fac[0]=1; invfact[0]=1; for(int i=1;i<100;i++){ fac[i]=(fac[i-1]*i)%mod; invfact[i]=modInverse(fac[i]); } } public static long modInverse(long n){ return power(n,mod-2); } public static long power(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; } //*************************************DSU************************************ */ public static void initialize(int n){ for(int i=1;i<=n;i++){ par[i]=i; rank[i]=1; } } public static void union(int x,int y){ int lx=find(x); int ly=find(y); if(lx!=ly){ if(rank[lx]>rank[ly]){ par[ly]=lx; }else if(rank[lx]<rank[ly]){ par[lx]=ly; }else{ par[lx]=ly; rank[ly]++; } } } public static int find(int x){ if(par[x]==x){ return x; } int temp=find(par[x]); par[x]=temp; return temp; } //************************************DSU END********************************** */ public static boolean isPresent(ArrayList<Long> zero,long val){ for(long x:zero){ if(x==val)return true; } return false; } public static class Pair implements Comparable<Pair>{ int val; int idx; Pair(int val,int idx){ this.val=val; this.idx=idx; } public int compareTo(Pair o){ return this.val-o.val; } } public static int countDigit(int x){ return (int)Math.log10(x)+1; } //****************************function to find all factor************************************************* public static ArrayList<Long> findAllFactors(long num){ ArrayList<Long> factors = new ArrayList<Long>(); for(long i = 1; i <= num/i; ++i) { if(num % i == 0) { //if i is a factor, num/i is also a factor factors.add(i); factors.add(num/i); } } //sort the factors Collections.sort(factors); return factors; } //*************************** function to find GCD of two number******************************************* public static long gcd(long a,long b){ if(b==0)return a; return gcd(b,a%b); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
72f65653e09236095a8966c49108ca56
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Map.Entry; import java.util.StringTokenizer; import java.util.stream.Collectors; public class R766C { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int t = Integer.parseInt(st.nextToken()); while (t-- > 0) { st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int[][] arr = new int[n - 1][2]; Map<Integer, List<Integer>> connectedVertices = new HashMap<>(); Map<Integer, Integer> vertexConnectionCounts = new HashMap<>(); for (int i = 0; i < n - 1; i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); arr[i][0] = a; arr[i][1] = b; addToConnectionsList(connectedVertices, a, b); addToConnectionsList(connectedVertices, b, a); addToConnectionsCount(vertexConnectionCounts, a, b); addToConnectionsCount(vertexConnectionCounts, b, a); } solve(connectedVertices, vertexConnectionCounts, arr); } } static class Vertex { int small; int large; public Vertex(int small, int large) { super(); this.small = small; this.large = large; } @Override public int hashCode() { return Objects.hash(large, small); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Vertex other = (Vertex) obj; return large == other.large && small == other.small; } @Override public String toString() { return "Vertex [small=" + small + ", large=" + large + "]"; } // implement equals and tostring } private static void addToConnectionsList(Map<Integer, List<Integer>> connectedVertices, int x, int y) { List<Integer> aConnections = connectedVertices.getOrDefault(x, new ArrayList<>()); aConnections.add(y); connectedVertices.put(x, aConnections); } private static void addToConnectionsCount(Map<Integer, Integer> vertexConnectionCounts, int x, int y) { int count = vertexConnectionCounts.getOrDefault(x, 0); count++; vertexConnectionCounts.put(x, count); } private static void solve(Map<Integer, List<Integer>> connectedVertices, Map<Integer, Integer> vertexConnectionCounts, int[][] arr) { int leaf = -1; for (Entry<Integer, Integer> entry : vertexConnectionCounts.entrySet()) { Integer key = entry.getKey(); Integer val = entry.getValue(); if (val > 2) { System.out.println(-1); return; } if (val == 1) { leaf = key; } } Map<Vertex, Integer> vertexSizes = new HashMap<>(); int prev = -1; boolean isTwo = false; while (true) { int previousVertex = prev; List<Integer> list = connectedVertices.get(leaf).stream().filter(val -> !Objects.equals(val, previousVertex)).collect(Collectors.toList()); if (list.isEmpty()) break; int next = list.get(0); int small = Math.min(leaf, next); int large = Math.max(leaf, next); Vertex vertex = new Vertex(small, large); vertexSizes.put(vertex, isTwo ? 2 : 3); isTwo = !isTwo; prev = leaf; leaf = next; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < arr.length; i++) { int first = arr[i][0]; int second = arr[i][1]; int small = Math.min(first, second); int large = Math.max(first, second); Vertex vertex = new Vertex(small, large); int size = vertexSizes.get(vertex); builder.append(size); builder.append(" "); } System.out.println(builder.toString()); } } /* 3 2 1 2 4 1 3 4 3 2 1 7 1 2 1 3 3 4 3 5 6 2 7 2 */
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
090a3e0946cfd60fb1b06d3f59be97ac
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
//package kg.my_algorithms.Codeforces; /* If you can't Calculate, then Stimulate */ /* 1) Physical Strength 2) Mental Strength 3) Emotional Strength */ import java.util.*; import java.io.*; public class Solution { private static final FastReader fr = new FastReader(); private static HashSet<Pair> twos; private static HashSet<Pair> fives; public static void main(String[] args) throws IOException { BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); StringBuilder sb = new StringBuilder(); int testCases = fr.nextInt(); for(int testCase=0;testCase<testCases;testCase++){ int n = fr.nextInt(); List<List<Integer>> tree = new ArrayList<>(); int[] degree = new int[n]; List<Pair> edges = new ArrayList<>(); int max = 0; for(int i=0;i<n;i++) tree.add(new ArrayList<>()); for(int i=0;i<n-1;i++){ int u = fr.nextInt()-1; int v = fr.nextInt()-1; degree[v]++; degree[u]++; edges.add(new Pair(u,v)); tree.get(u).add(v); tree.get(v).add(u); max = Math.max(max,Math.max(degree[v],degree[u])); } if(max>=3) { sb.append("-1\n"); continue; } twos = new HashSet<>(); fives = new HashSet<>(); dfs(tree,tree.get(0).get(0),0,2); twos.add(new Pair(0,tree.get(0).get(0))); if(tree.get(0).size()>1){ dfs(tree,tree.get(0).get(1),0,5); fives.add(new Pair(tree.get(0).get(1),0)); } for(Pair p: edges){ if(twos.contains(new Pair(p.u,p.v))|| twos.contains(new Pair(p.v,p.u))) sb.append("2 "); else sb.append("5 "); } sb.append("\n"); } output.write(sb.toString()); output.flush(); } private static void dfs(List<List<Integer>> tree, int node, int parent, int prev){ for(int child: tree.get(node)){ if(child == parent) continue; if(prev==2) { fives.add(new Pair(node,child)); dfs(tree,child,node,5); } else{ twos.add(new Pair(node,child)); dfs(tree,child,node,2); } } } } class Pair{ int u; int v; public Pair(int u, int v) { this.u = u; this.v = v; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair pair = (Pair) o; return u == pair.u && v == pair.v; } @Override public int hashCode() { return Objects.hash(u, v); } } //Fast Input 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 { if(st.hasMoreTokens()){ str = st.nextToken("\n"); } else{ str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
213ab490b647a6bd3e71cde79f897829
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
// package faltu; import java.util.*; import java.util.Map.Entry; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; public class Main { // ***********************MATHS--STARTS************************************************* // private static ArrayList<Long> get_divisor(long x) { ArrayList<Long>a=new ArrayList<Long>(); for(long i=1;i*i<=x;i++) { if(x%i==0) { a.add((long) i); if(x/i!=i)a.add(x/i); } } return a; } static long[] sieve; static long[] smallestPrime; public static void sieve() { int n=4000000+1; sieve=new long[n]; smallestPrime=new long[n]; sieve[0]=1; sieve[1]=1; for(int i=2;i<n;i++){ sieve[i]=i; smallestPrime[i]=i; } for(int i=2;i*i<n;i++){ if(sieve[i]==i){ for(int j=i*i;j<n;j+=i){ if(sieve[j]==j)sieve[j]=1; if(smallestPrime[j]==j||smallestPrime[j]>i)smallestPrime[j]=i; } } } } static long nCr(long n,long r,long MOD) { if(n<r)return 0; if(r==0)return 1; return fact[(int) n]*mod_inv(fact[(int) r],MOD)%MOD*mod_inv(fact[(int) (n-r)],MOD)%MOD; } static long[]fact; static void computeFact(long n,long MOD) { fact=new long[(int)n+1]; fact[0]=1; for(int i=1;i<=n;i++)fact[i]=(fact[i-1]*i%MOD)%MOD; } static long bin_expo(long a,long b,long MOD) { if(b == 0)return 1; long ans = bin_expo(a,b/2,MOD); ans = (ans*ans)%MOD; if(b % 2!=0){ ans = (ans*a)%MOD; } return ans%MOD; } static long mod_add(long a, long b, long m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;} static long mod_mul(long a, long b, long m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;} static long mod_sub(long a, long b, long m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;} static long mod_inv(long n,long p) {return bin_expo(n,p-2,p);} static long gcd(long a, long b){if (a == 0) {return b;}return gcd(b % a, a); } static int gcd(int a, int b){if (a == 0) {return b; }return gcd(b % a, a); } static long lcm(long a,long b){return (a / gcd(a, b)) * b;} static long min(long x,long y) {return Math.min(x, y);}static long max(long x,long y) {return Math.max(x, y);} static int min(int x,int y) {return Math.min(x, y);}static int max(int x,int y) {return Math.max(x, y);} static ArrayList<String>powof2s; static void powof2S() { long i=1; while(i<(long)2e18) { powof2s.add(String.valueOf(i)); i*=2; } } static long power(long a, long b){ a %=MOD;long out = 1; while (b > 0) { if((b&1)!=0)out = out * a % MOD; a = a * a % MOD; b >>= 1; a*=a; } return out; } static boolean coprime(int a, long l){return (gcd(a, l) == 1);} // ****************************MATHS-ENDS***************************************************** // ***********************BINARY-SEARCH STARTS*********************************************** public static int upperBound(long[] arr, long m, int l, int r) { while(l<=r) { int mid=(l+r)/2; if(arr[mid]<=m) l=mid+1; else r=mid-1; } return l; } public static int lowerBound(long[] a, long m, int l, int r) { while(l<=r) { int mid=(l+r)/2; if(a[mid]<m) l=mid+1; else r=mid-1; } return l; } public static int lowerBound(ArrayList<Integer> ar,int k){ int s=0,e=ar.size(); while (s!=e){ int mid = s+e>>1; if (ar.get(mid) <k)s=mid+1; else e=mid; } if(s==ar.size())return -1; return s; } public static int upperBound(ArrayList<Integer> ar,int k){ int s=0,e=ar.size(); while (s!=e){ int mid = s+e>>1; if (ar.get(mid) <=k)s=mid+1; else e=mid; } if(s==ar.size())return -1; return s; } public static long getClosest(long val1, long val2,long target){if (target - val1 >= val2 - target)return val2; else return val1;} static void ruffleSort(long[] a) { int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { long oi=r.nextInt(n), temp=a[i]; a[i]=a[(int)oi]; a[(int)oi]=temp; } Arrays.sort(a); } static void ruffleSort(int[] a){ int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n), temp=a[i]; a[i]=a[oi]; a[oi]=temp; } Arrays.sort(a); } int ceilIndex(int input[], int T[], int end, int s){ int start = 0; int middle; int len = end; while(start <= end){ middle = (start + end)/2; if(middle < len && input[T[middle]] < s && s <= input[T[middle+1]]){ return middle+1; }else if(input[T[middle]] < s){ start = middle+1; }else{ end = middle-1; } } return -1; } static int lowerLimitBinarySearch(ArrayList<Long> v,long k) { int n =v.size(); int first = 0,second = n; while(first <second) { int mid = first + (second-first)/2; if(v.get(mid) > k) { second = mid; }else { first = mid+1; } } if(first < n && v.get(first) < k) { first++; } return first; //1 index } public static int searchindex(long arr[], long t){int index = Arrays.binarySearch(arr, t);return (index < 0) ? -1 : index;} public static long[] sort(long[] a) {ArrayList<Long> al = new ArrayList<>();for(int i=0;i<a.length;i++) al.add(a[i]);Collections.sort(al);for(int i=0;i<a.length;i++) a[i]=al.get(i);return a;} public static int[] sort(int[] a) {ArrayList<Integer> al = new ArrayList<>();for(int i=0;i<a.length;i++) al.add(a[i]);Collections.sort(al);for(int i=0;i<a.length;i++) a[i]=al.get(i);return a;} // *******************************BINARY-SEARCH ENDS*********************************************** // *********************************GRAPHS-STARTS**************************************************** // *******----SEGMENT TREE IMPLEMENT---***** // -------------START--------------- void buildTree (int[] arr,int[] tree,int start,int end,int treeNode){ if(start==end){ tree[treeNode]=arr[start]; return; } buildTree(arr,tree,start,end,2*treeNode); buildTree(arr,tree,start,end,2*treeNode+1); tree[treeNode]=tree[treeNode*2]+tree[2*treeNode+1]; } void updateTree(int[] arr,int[] tree,int start,int end,int treeNode,int idx,int value){ if(start==end){ arr[idx]=value; tree[treeNode]=value; return; } int mid=(start+end)/2; if(idx>mid)updateTree(arr,tree,mid+1,end,2*treeNode+1,idx,value); else updateTree(arr,tree,start,mid,2*treeNode,idx,value); tree[treeNode]=tree[2*treeNode]+tree[2*treeNode+1]; } long query(int[]arr,int[]tree,int start,int end,int treeNode,int qleft,int qright) { if(start>=qleft&&end<=qright)return tree[treeNode]; if(start>qright||end<qleft)return 0; int mid=(start+end)/2; long valLeft=query(arr,tree,start,mid-1,treeNode*2,qleft,qright); long valRight=query(arr,tree,mid+1,end,treeNode*2+1,qleft,qright); return valLeft+valRight; } // -------------ENDS--------------- //***********************DSU IMPLEMENT START************************* static int parent[]; static int rank[]; static int[]Size; static void makeSet(int n){ parent=new int[n]; rank=new int[n]; Size=new int[n]; for(int i=0;i<n;i++){ parent[i]=i; rank[i]=0; Size[i]=1; } } static void union(int u,int v){ u=findpar(u); v=findpar(v); if(rank[u]<rank[v]) { parent[u]=v; Size[v]+=Size[u]; } else if(rank[v]<rank[u]) { parent[v]=u; Size[u]+=Size[v]; } else{ parent[v]=u; rank[u]++; Size[u]+=Size[v]; } } private static int findpar(int node){ if(node==parent[node])return node; return parent[node]=findpar(parent[node]); } // *********************DSU IMPLEMENT ENDS************************* // ****__________PRIMS ALGO______________________**** private static int prim(ArrayList<node>[] adj,int N,int node) { int key[] = new int[N+1]; int parent[] = new int[N+1]; boolean mstSet[] = new boolean[N+1]; for(int i = 0;i<N;i++) { key[i] = 100000000; mstSet[i] = false; } PriorityQueue<node> pq = new PriorityQueue<node>(N, new node()); key[node] = 0; parent[node] = -1; pq.add(new node( node,key[node])); for(int i = 0;i<N-1;i++) { int u = pq.poll().getV(); mstSet[u] = true; for(node it: adj[u]) { if(mstSet[it.getV()] == false && it.getW() < key[it.getV()]) { parent[it.getV()] = u; key[it.getV()] = (int) it.getW(); pq.add(new node(it.getV(), key[it.getV()])); } } } int sum=0; for(int i=1;i<N;i++) { System.out.println(key[i]); sum+=key[i]; } System.out.println(sum); return sum; } // ****____________DIJKSTRAS ALGO___________**** static int[]dist; static int dijkstra(int u,int n,ArrayList<node>adj[]) { dist=new int[n]; Arrays.fill(dist,Integer.MAX_VALUE); dist[u]=0; PriorityQueue<node>pq=new PriorityQueue<node>(new node()); pq.add(new node(u,0)); while(!pq.isEmpty()) { node v=pq.poll(); for(node it:adj[v.getV()]) { if(dist[it.getV()]>it.getW()+dist[v.getV()]) { dist[it.getV()]=(int) (it.getW()+dist[v.getV()]); pq.add(new node(it.getV(),dist[it.getV()])); } } } int sum=0; for(int i=1;i<n;i++){ System.out.println(dist[i]); sum+=dist[i]; } return sum; } private static void setGraph(int n,int m){ vis=new boolean[n+1]; indeg=new int[n+1]; // adj=new ArrayList<ArrayList<Integer>>(); // for(int i=0;i<=n;i++)adj.add(new ArrayList<>()); // for(int i=0;i<m;i++){ // int u=s.nextInt(),v=s.nextInt(); // adj.get(u).add(v); // adj.get(v).add(u); // } adj=new ArrayList[n+1]; // backadj=new ArrayList[n+1]; for(int i=0;i<=n;i++){ adj[i]=new ArrayList<Integer>(); // backadj[i]=new ArrayList<Integer>(); } for(int i=0;i<m;i++){ int u=s.nextInt(),v=s.nextInt(); edges[i][0]=u;edges[i][1]=v; adj[u].add(v); adj[v].add(u); // backadj[v].add(u); indeg[v]++; indeg[u]++; if(indeg[u]>=3||indeg[v]>=3)checker=true; } // weighted adj // adj=new ArrayList[n+1]; // for(int i=0;i<=n;i++){ // adj[i]=new ArrayList<node>(); // } // for(int i=0;i<m;i++){ // int u=s.nextInt(),v=s.nextInt(); // long w=s.nextInt(); // adj[u].add(new node(v,w)); //// adj[v].add(new node(u,w)); // } } // *********************************GRAPHS-ENDS**************************************************** static int[][] dirs8 = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}}; static int[][] dirs4 = {{1,0},{-1,0},{0,1},{0,-1}}; //d-u-r-l static long MOD=(long) (1e9+7); static int prebitsum[][]; static boolean[] vis; static int[]indeg; // static ArrayList<ArrayList<Integer>>adj; static ArrayList<Integer> adj[]; static ArrayList<Integer> backadj[]; static FastReader s = new FastReader(System.in); public static void main(String[] args) throws IOException { // sieve(); // computeFact((int)1e7+1,MOD); // prebitsum=new int[2147483648][31]; // presumbit(prebitsum); // powof2S(); // // try { int tt = s.nextInt(); // int tt=1; for(int i=1;i<=tt;i++) { solver(); } // catch(Exception e) {return;} } static boolean checker; static HashMap<String,Integer>w; static int[][]edges; private static void solver() { checker=false; int leaf=-1; int n=s.nextInt(); edges=new int[n-1][2]; setGraph(n, n-1); if(checker==true) { System.out.println(-1); return; } for(int i=1;i<=n;i++) { if(adj[i].size()==1)leaf=i; } w=new HashMap<String, Integer>(); vis[leaf]=true; dfs(leaf,2); StringBuilder res=new StringBuilder(); for (int[] a : edges) { int ans = w.getOrDefault(a[0] + "-" + a[1], 0) + w.getOrDefault(a[1] + "-" + a[0], 0); res.append(ans + " "); } System.out.println(res); } private static void dfs(int u, int weight) { for(int v:adj[u]) { if(vis[v]==false) { w.put(v+"-"+u, weight); weight=weight==2?3:2; vis[v]=true; dfs(v,weight); } } } /* *********************BITS && TOOLS &&DEBUG STARTS***********************************************/ static boolean issafe(int i, int j, int r,int c, int sx, int sy, int d,boolean[][]vis){ if (i < 0 || j < 0 || i >= r || j >= c||((Math.abs(i-sx)+Math.abs(j-sy))<=d)||vis[i][j]==true)return false; else return true; } static void presumbit(int[][]prebitsum) { for(int i=1;i<=200000;i++) { int z=i; int j=0; while(z>0) { if((z&1)==1) { prebitsum[i][j]+=(prebitsum[i-1][j]+1); }else { prebitsum[i][j]=prebitsum[i-1][j]; } z=z>>1; j++; } } } static void countOfSetBit(long[]a) { for(int j=30;j>=0;j--) { int cnt=0; for(long i:a) { if((i&1<<j)==1)cnt++; } // printing the current no set bit in all array element System.out.println(cnt); } } public static String revStr(String str){String input = str;StringBuilder input1 = new StringBuilder();input1.append(input);input1.reverse();return input1.toString();} static void printA(long[] x) {for(int i=0;i<x.length;i++)System.out.print(x[i]+" ");System.out.println();} static void pc2d(boolean[][] vis) { int n=vis.length; int m=vis[0].length; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { System.out.print(vis[i][j]+" "); } System.out.println(); } } static void pi2d(char[][] a) { int n=a.length; int m=a[0].length; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { System.out.print(a[i][j]+" "); } System.out.println(); } } static void p1d(int[]a) { for(int i=0;i<a.length;i++)System.out.print(a[i]+" "); System.out.println(); } // *****************BITS && TOOLS &&DEBUG ENDS*********************************************** } // **************************I/O************************* class FastReader { public BufferedReader reader; public StringTokenizer tokenizer; public FastReader(InputStream stream) {reader = new BufferedReader(new InputStreamReader(stream), 32768);tokenizer = null;} public String next() {while (tokenizer == null || !tokenizer.hasMoreTokens()) {try {tokenizer = new StringTokenizer(reader.readLine());} catch (IOException e) {throw new RuntimeException(e);}}return tokenizer.nextToken();} public int nextInt(){ return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() {String str = "";try {str = reader.readLine();}catch (IOException e) {e.printStackTrace();}return str;} } class dsu{ int n; static int parent[]; static int rank[]; static int[]Size; public dsu(int n) {this.n=n;this.parent=new int[n];this.rank=new int[n];this.Size=new int[n]; for(int i=0;i<n;i++){parent[i]=i;rank[i]=0;Size[i]=1;} } static int findpar(int node) {if(node==parent[node])return node;return parent[node]=findpar(parent[node]);} static void union(int u,int v){ u=findpar(u);v=findpar(v); if(u!=v) { if(rank[u]<rank[v]) {parent[u]=v;Size[v]+=Size[u];} else if(rank[v]<rank[u]) {parent[v]=u;Size[u]+=Size[v];} else{parent[v]=u;rank[u]++;Size[u]+=Size[v];} } } } class pair{ int x;int y; long u,v; public pair(int x,int y){this.x=x;this.y=y;} public pair(long u,long v) {this.u=u;this.v=v;} } class node implements Comparator<node>{ private int v; private long w; node(int _v, long _w) { v = _v; w = _w; } node() {} int getV() { return v; } long getW() { return w; } @Override public int compare(node node1, node node2) { if (node1.w < node2.w) return -1; if (node1.w > node2.w) return 1; return 0; } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
c63b2408581d33bec970fd2d4c261549
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class NotAssigning { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pr=new PrintWriter(System.out); int t=Integer.parseInt(br.readLine()); while(t!=0){ solve(br,pr); t--; } pr.flush(); pr.close(); } public static void solve(BufferedReader br,PrintWriter pr) throws IOException{ int n=Integer.parseInt(br.readLine()); int[] degree=new int[n]; boolean valid=true; Map<Integer, List<Integer>> neighbors=new HashMap<>(); List<int[]> edges=new ArrayList<>(); for(int i=0;i<n-1;i++){ String[] temp=br.readLine().split(" "); int u=Integer.parseInt(temp[0])-1; int v=Integer.parseInt(temp[1])-1; if(neighbors.containsKey(u)==false){ neighbors.put(u,new ArrayList<>()); } if(neighbors.containsKey(v)==false){ neighbors.put(v,new ArrayList<>()); } neighbors.get(u).add(v); neighbors.get(v).add(u); degree[u]++; degree[v]++; edges.add(new int[]{u,v}); if(degree[u]>2||degree[v]>2){ valid=false; } } if(!valid){ pr.println(-1); return; } Queue<int[]> queue=new LinkedList<>(); queue.add(new int[]{0,-1}); Set<Integer> visited=new HashSet<>(); visited.add(0); Map<Integer,Map<Integer,Integer>> weights=new HashMap<>(); while(queue.size()!=0){ int levelCount=queue.size(); for(int i=0;i<levelCount;i++){ int[] current=queue.poll(); int lastWeight=current[1]; List<Integer> neighbor=neighbors.get(current[0]); for(int j=0;j<neighbor.size();j++){ int next=neighbor.get(j); if(visited.contains(next)==false){ visited.add(next); int weight=lastWeight==-1?(j==0?2:3):lastWeight==2?3:2; queue.add(new int[]{next,weight}); if(weights.containsKey(current[0])==false){ weights.put(current[0],new HashMap<>()); } if(weights.containsKey(next)==false){ weights.put(next,new HashMap<>()); } weights.get(current[0]).put(next,weight); weights.get(next).put(current[0],weight); } } } } for(int[] edge:edges){ int u=edge[0]; int v=edge[1]; pr.print(weights.get(u).get(v)+" "); } pr.print('\n'); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
d8d447f329c59e280b7965ee28a47c81
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; public class C_Not_Assigning { static FastReader sc; static void solve() { StringBuilder res = new StringBuilder(); int n = sc.nextInt(); boolean f = false; int[] num = new int[n + 1]; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i <= n; i++) { adj.add(new ArrayList<>()); } int[][] arr = new int[n - 1][2]; for (int i = 0; i < n - 1; i++) { int l = sc.nextInt(), r = sc.nextInt(); arr[i][0] = l; arr[i][1] = r; adj.get(l).add(r); adj.get(r).add(l); } int c = 0, tmp = 0; for (int i = 1; i <= n; i++) { if (adj.get(i).size() == 2) c++; else if (adj.get(i).size() == 1) tmp = i; } if (c != n - 2) { print(-1); return; } Map<String, Integer> map = new HashMap<>(); boolean[] visited = new boolean[n + 1]; visited[tmp] = true; dfs(adj, map, tmp, visited, 2); for (int[] a : arr) { int ans = map.getOrDefault(a[0] + ":" + a[1], 0) + map.getOrDefault(a[1] + ":" + a[0], 0); res.append(ans + " "); } print(res); } static void dfs(List<List<Integer>> adj, Map<String, Integer> map, int i, boolean[] vis, int pre) { int tmp = -1; for (int a : adj.get(i)) { if (!vis[a]) { map.put(i + ":" + a, pre); pre = pre == 2 ? 3 : 2; vis[a] = true; dfs(adj, map, a, vis, pre); } } } public static void main(String[] args) throws IOException { sc = new FastReader(); int tt = sc.nextInt(); while (tt-- > 0) { solve(); } } static <E> void debug(E a) { System.err.println(a); } static void debug(int... a) { System.err.println(Arrays.toString(a)); } static int maxOf(int... array) { return Arrays.stream(array).max().getAsInt(); } static int minOf(int... array) { return Arrays.stream(array).parallel().reduce(Math::min).getAsInt(); } static <E> void print(E res) { System.out.println(res); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } long[] readLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = nextLong(); return res; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
cf53c91b8c3fdf3f3b937fdf3b30af6e
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } int MAX = Integer.MAX_VALUE/2; public static void main(String... args) throws Exception{ FastReader in = new FastReader(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); Solution sol = new Solution(); int t = in.nextInt(); while(t-->0){ sol.solve(in, out); } out.flush(); } private boolean isPoss(int x, int y, int n, int m){ if(x<0 || y<0 || x>=n || y>=m) return false; return true; } boolean debug = true; // boolean debug = false; private void solve(FastReader in, BufferedWriter out) throws Exception{ int n = in.nextInt(); HashMap<Integer, List<Integer>> tree = new HashMap<>(); List<String> query = new ArrayList<>(); for(int i=0;i<n-1;i++){ int u = in.nextInt(); int v = in.nextInt(); tree.computeIfAbsent(u, (k)->new ArrayList<>()).add(v); tree.computeIfAbsent(v, (k)->new ArrayList<>()).add(u); if(u>v){ int temp = u; u = v; v = temp; } query.add(u+" "+v); } int root=0; for(int u: tree.keySet()){ if(tree.get(u).size()>=3){ out.write("-1\n"); return; }else if(tree.get(u).size()==1){ root = u; } } HashMap<String, Integer> assign = new HashMap<>(); dfs(root, tree, assign, -1, 2); for(String q: query){ out.write(assign.get(q)+" "); } out.write("\n"); } private void dfs(int u, HashMap<Integer, List<Integer>> tree, HashMap<String, Integer> assign, int p, int a){ for(int v: tree.get(u)){ if(v == p) continue; calc(assign, u, v, a); dfs(v, tree, assign, u, getA(a)); } } private void calc(HashMap<String, Integer> assign, int u, int v, int a){ if(u>v){ int temp = u; u = v; v = temp; } String key = u+" "+v; assign.put(key, a); } private int getA(int a){ if(a==2) return 5; if(a==5) return 2; return 0; } } /* ------ [2,6,4,6] [3,7,6,1] 3 6 6 6 2 7 4 1 ------------------------- 3 2 3 6 2 7 3 7 2 6 ------------------------- 2 3 ------------------------- */
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
984c734d2bb51bb61908d2c7b3c2750d
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
//package com.company; import java.util.*; import java.io.*; public class NotAssigning { public static class Edge { int node; int edge; public Edge(int node, int edge) { this.node = node; this.edge = edge; } } public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testcases = Integer.parseInt(br.readLine()); while(--testcases >= 0) { int nodes = Integer.parseInt(br.readLine()); int[] degree = new int[nodes]; ArrayList<ArrayList<Edge>> connect = new ArrayList<>(); for(int i = 0; i < nodes; i++) { connect.add(new ArrayList<>()); } for(int i = 0; i < nodes - 1 ; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int n1 = Integer.parseInt(st.nextToken()) - 1; int n2 = Integer.parseInt(st.nextToken()) - 1; degree[n1]++; degree[n2]++; connect.get(n1).add(new Edge(n2, i)); connect.get(n2).add(new Edge(n1, i)); } boolean im = false; int current = 0; for(int i = 0; i < nodes; i++) { if(degree[i] >= 3) { System.out.println(-1); im = true; break; } else if(degree[i] == 1) { current = i; } } if(im) continue; int[] ans = new int[nodes - 1]; int before = -1; for(int i = 0; i < nodes - 1; i++) { for(Edge next : connect.get(current)) { if(next.node == before) continue; ans[next.edge] = 2 + i%2; before = current; current = next.node; break; } } StringBuilder s = new StringBuilder(); for(int i = 0; i < nodes - 1; i++) { s.append(ans[i]); if(i != nodes - 2) s.append(" "); } System.out.println(s); } br.close(); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
3c5ea9c7b2bf9ecc81fae3c54065ce2b
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.lang.*; import java.io.InputStreamReader; import static java.lang.Math.*; import static java.lang.System.out; import java.util.*; import java.io.File; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigInteger; public class Main { /* 10^(7) = 1s. * ceilVal = (a+b-1) / b */ static final int mod = 1000000007; static final long temp = 998244353; static final long MOD = 1000000007; static final long M = (long)1e9+7; static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair ob) { return (int)(first - ob.first); } } static class Tuple implements Comparable<Tuple> { int first, second,third; public Tuple(int first, int second, int third) { this.first = first; this.second = second; this.third = third; } public int compareTo(Tuple o) { return (int)(o.third - this.third); } } public static class DSU { int[] parent; int[] rank; //Size of the trees is used as the rank public DSU(int n) { parent = new int[n]; rank = new int[n]; Arrays.fill(parent, -1); Arrays.fill(rank, 1); } public int find(int i) //finding through path compression { return parent[i] < 0 ? i : (parent[i] = find(parent[i])); } public boolean union(int a, int b) //Union Find by Rank { a = find(a); b = find(b); if(a == b) return false; //if they are already connected we exit by returning false. // if a's parent is less than b's parent if(rank[a] < rank[b]) { //then move a under b parent[a] = b; } //else if rank of j's parent is less than i's parent else if(rank[a] > rank[b]) { //then move b under a parent[b] = a; } //if both have the same rank. else { //move a under b (it doesnt matter if its the other way around. parent[b] = a; rank[a] = 1 + rank[a]; } return true; } } static class Reader { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) throws IOException { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] longReadArray(int n) throws IOException { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static int gcd(int a, int b) { if(b == 0) return a; else return gcd(b,a%b); } public static long lcm(long a, long b) { return (a / LongGCD(a, b)) * b; } public static long LongGCD(long a, long b) { if(b == 0) return a; else return LongGCD(b,a%b); } public static long LongLCM(long a, long b) { return (a / LongGCD(a, b)) * b; } //Count the number of coprime's upto N public static long phi(long n) //euler totient/phi function { long ans = n; // for(long i = 2;i*i<=n;i++) // { // if(n%i == 0) // { // while(n%i == 0) n/=i; // ans -= (ans/i); // } // } // // if(n > 1) // { // ans -= (ans/n); // } for(long i = 2;i<=n;i++) { if(isPrime(i)) { ans -= (ans/i); } } return ans; } public static long fastPow(long x, long n) { if(n == 0) return 1; else if(n%2 == 0) return fastPow(x*x,n/2); else return x*fastPow(x*x,(n-1)/2); } public static long powMod(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) { res = (res * x) % p; } y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return powMod(n, p - 2, p); } // Returns nCr % p using Fermat's little theorem. public static long nCrModP(long n, long r,long p) { if (n<r) return 0; if (r == 0) return 1; long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[(int)(n)] * modInverse(fac[(int)(r)], p) % p * modInverse(fac[(int)(n - r)], p) % p) % p; } public static long fact(long n) { long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (long i = 1; i <= n; i++) fac[(int)(i)] = fac[(int)(i - 1)] * i; return fac[(int)(n)]; } public static long nCr(long n, long k) { long ans = 1; for(long i = 0;i<k;i++) { ans *= (n-i); ans /= (i+1); } return ans; } //Modular Operations for Addition and Multiplication. public static long perfomMod(long x) { return ((x%M + M)%M); } public static long addMod(long a, long b) { return perfomMod(perfomMod(a)+perfomMod(b)); } public static long subMod(long a, long b) { return perfomMod(perfomMod(a)-perfomMod(b)); } public static long mulMod(long a, long b) { return perfomMod(perfomMod(a)*perfomMod(b)); } public static boolean isPrime(long n) { if(n == 1) { return false; } //check only for sqrt of the number as the divisors //keep repeating so only half of them are required. So,sqrt. for(int i = 2;i*i<=n;i++) { if(n%i == 0) { return false; } } return true; } public static List<Integer> SieveList(int n) { boolean prime[] = new boolean[(int)(n+1)]; Arrays.fill(prime, true); List<Integer> l = new ArrayList<>(); for (int p = 2; p*p<=n; p++) { if (prime[p] == true) { for(int i = p*p; i<=n; i += p) { prime[i] = false; } } } for (int p = 2; p<=n; p++) { if (prime[p] == true) { l.add(p); } } return l; } public static int countDivisors(int x) { int c = 0; for(int i = 1;i*i<=x;i++) { if(x%i == 0) { if(x/i != i) { c+=2; } else { c++; } } } return c; } public static long log2(long n) { long ans = (long)(log(n)/log(2)); return ans; } public static boolean isPow2(long n) { return (n != 0 && ((n & (n-1))) == 0); } public static boolean isSq(int x) { long s = (long)Math.round(Math.sqrt(x)); return s*s==x; } /* * * >= <= 0 1 2 3 4 5 6 7 5 5 5 6 6 6 7 7 lower_bound for 6 at index 3 (>=) upper_bound for 6 at index 6(To get six reduce by one) (<=) */ public static int LowerBound(int a[], int x) { int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } public static int UpperBound(int a[], int x) { int l=-1, r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } public static void Sort(long[] a) { List<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); Collections.reverse(l); //Use to Sort decreasingly for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void ssort(char[] a) { List<Character> l = new ArrayList<>(); for (char i : a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static HashMap<String,Integer> map; public static String getVal(int x, int y) { return min(x,y) + " " + max(x,y); } public static void dfs(List<Integer>[] gr, int node, int parent, int[] ans, int val) { for(int it : gr[node]) { if(it == parent) continue; ans[map.get(getVal(node,it))] = val; dfs(gr,it,node,ans,5 - val); val = 5-val; } } public static void main(String[] args) throws Exception { Reader sc = new Reader(); PrintWriter fout = new PrintWriter(System.out); int tt = sc.nextInt(); dx: while(tt-- > 0) { int n = sc.nextInt(); int[] ans = new int[n-1]; int[] deg = new int[n]; map = new HashMap<>(); List<Integer>[] gr = new ArrayList[n]; for(int i = 0;i<n;i++) gr[i] = new ArrayList<>(); for(int i = 0;i<n-1;i++) { int x = sc.nextInt()-1, y = sc.nextInt()-1; gr[x].add(y); gr[y].add(x); deg[x]++; deg[y]++; map.put(getVal(x,y),i); } boolean ok = true; for(int i = 0;i<n;i++) { if(deg[i] > 2) { ok = false; break; } } if(ok == false) { fout.println(-1); continue dx; } dfs(gr,0,0,ans,2); for(int it : ans) fout.print(it + " "); fout.println(); } fout.close(); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
a0b0075d5692fb209eef6f5074887749
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; /** * * @Har_Har_Mahadev */ /** * Main , Solution , Remove Public */ public class C { private static ArrayList<Integer>[] adj; private static int[] ans; private static HashMap<String, Integer> map; public static void process() throws IOException { int n = sc.nextInt(); adj = new ArrayList[n+1]; for(int i = 0; i<=n; i++)adj[i] = new ArrayList<Integer>(); map = new HashMap<String, Integer>(); for(int i = 0; i+1<n; i++) { int u = sc.nextInt(), v = sc.nextInt(); int a = min(u, v); int b = max(u, v); map.put(a+" "+b, i); adj[a].add(b); adj[b].add(a); } int root = -1; for(int i = 1; i<=n; i++) { if(adj[i].size() > 2) { System.out.println(-1); return; } if(adj[i].size() == 1)root = i; } ans = new int[n-1]; dfs(root, -1, 0); for(int e : ans) { if(e == 0) System.out.print(2+" "); else System.out.print(3+" "); } System.out.println(); } private static void dfs(int root, int par, int col) { for(int child : adj[root]) { if(child == par)continue; int index = map.get(min(root, child) + " "+ max(root, child)); ans[index] = col; dfs(child, root, col^1); } } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353; private static int N = 0; private static void google(int tt) { System.out.print("Case #" + (tt) + ": "); } static FastScanner sc; static FastWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new FastWriter(System.out); } else { sc = new FastScanner("input.txt"); out = new FastWriter("output.txt"); } long s = System.currentTimeMillis(); int t = 1; t = sc.nextInt(); int TTT = 1; while (t-- > 0) { // google(TTT++); process(); } out.flush(); // tr(System.currentTimeMillis()-s+"ms"); } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if (!oj) System.err.println(Arrays.deepToString(o)); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } /* @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair key = (Pair) o; return x == key.x && y == key.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } */ } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long sqrt(long z) { long sqz = (long) Math.sqrt(z); while (sqz * 1L * sqz < z) { sqz++; } while (sqz * 1L * sqz > z) { sqz--; } return sqz; } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } public static long gcd(long a, long b) { if (a > b) a = (a + b) - (b = a); if (a == 0L) return b; return gcd(b % a, a); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static int lower_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = -1; while (low <= high) { mid = (low + high) / 2; if (arr[mid] > x) { high = mid - 1; } else { ans = mid; low = mid + 1; } } return ans; } public static int upper_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = arr.length; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) { ans = mid; high = mid - 1; } else { low = mid + 1; } } return ans; } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void reverseArray(int[] a) { int n = a.length; int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long arr[] = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } //custom multiset (replace with HashMap if needed) public static void push(TreeMap<Integer, Integer> map, int k, int v) { //map[k] += v; if (!map.containsKey(k)) map.put(k, v); else map.put(k, map.get(k) + v); } public static void pull(TreeMap<Integer, Integer> map, int k, int v) { //assumes map[k] >= v //map[k] -= v int lol = map.get(k); if (lol == v) map.remove(k); else map.put(k, lol - v); } // compress Big value to Time Limit public static int[] compress(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for (int x : arr) ls.add(x); Collections.sort(ls); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int boof = 1; //min value for (int x : ls) if (!map.containsKey(x)) map.put(x, boof++); int[] brr = new int[arr.length]; for (int i = 0; i < arr.length; i++) brr[i] = map.get(arr[i]); return brr; } // Fast Writer public static class FastWriter { private static final int BUF_SIZE = 1 << 13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter() { out = null; } public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) innerflush(); return this; } public FastWriter write(char c) { return write((byte) c); } public FastWriter write(char[] s) { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if (x == Integer.MIN_VALUE) { return write((long) x); } if (ptr + 12 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if (x == Long.MIN_VALUE) { return write("" + x); } if (ptr + 21 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if (x < 0) { write('-'); x = -x; } x += Math.pow(10, -precision) / 2; // if(x < 0){ x = 0; } write((long) x).write("."); x -= (long) x; for (int i = 0; i < precision; i++) { x *= 10; write((char) ('0' + (int) x)); x -= (int) x; } return this; } public FastWriter writeln(char c) { return write(c).writeln(); } public FastWriter writeln(int x) { return write(x).writeln(); } public FastWriter writeln(long x) { return write(x).writeln(); } public FastWriter writeln(double x, int precision) { return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for (int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for (long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte) '\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for (char[] line : map) write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c) { return writeln(c); } public FastWriter println(int x) { return writeln(x); } public FastWriter println(long x) { return writeln(x); } public FastWriter println(double x, int precision) { return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } // Fast Inputs static class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] readArray(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readArrayLong(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public int[][] readArrayMatrix(int N, int M, int Index) { if (Index == 0) { int[][] res = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = (int) nextLong(); } return res; } int[][] res = new int[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = (int) nextLong(); } return res; } public long[][] readArrayMatrixLong(int N, int M, int Index) { if (Index == 0) { long[][] res = new long[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = nextLong(); } return res; } long[][] res = new long[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] readArrayDouble(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
7dbf20e52bf67eaf60cc40f9532842b2
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class C_NotAssigning_1400 { public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); boolean[] visited = new boolean[n]; ArrayList<Edge>[] adj = new ArrayList[n]; for(int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for(int i = 0; i < n-1; i++) { int a = sc.nextInt()-1; int b = sc.nextInt()-1; adj[a].add(new Edge(b, i)); adj[b].add(new Edge(a, i)); } int start = -1; boolean flag = false; for(int i = 0; i < n; i++) { //start from leaf node if(adj[i].size() == 1) { start = i; } else if(adj[i].size() > 2) { flag = true; } } int[] weights = new int[n-1]; Queue<Integer> que = new LinkedList<>(); que.offer(start); visited[start] = true; int curDist = 0; while(!que.isEmpty()) { int cur = que.poll(); for(Edge e : adj[cur]) { if(!visited[e.to]) { visited[e.to] = true; que.offer(e.to); if(curDist%2 == 0) { weights[e.index] = 2; } else { weights[e.index] = 3; } } } curDist++; } if(flag) { System.out.println(-1); } else { StringBuilder sb = new StringBuilder(); for(int i = 0; i < n-1; i++){ sb.append(weights[i] + " "); } System.out.println(sb.toString().trim()); } } out.close(); } static class Edge{ public int to; public int index; Edge(int to, int index){ this.to = to; this.index = index; } } public static PrintWriter out; public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
d2f5dcf125334f9ec5ec487f903178d9
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args)throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(System.out); int t=Integer.parseInt(br.readLine()); while(t-->0) { int n=Integer.parseInt(br.readLine()); boolean exists=true; Edge edge[][]=new Edge[n+1][2]; for(int i=0;i<n-1;i++) { String s[]=(br.readLine()).split(" "); int u=Integer.parseInt(s[0]); int v=Integer.parseInt(s[1]); if(edge[u][0]==null) { edge[u][0]=new Edge(v,i); } else if(edge[u][1]==null) { edge[u][1]=new Edge(v,i); } else { exists=false; } if(edge[v][0]==null) { edge[v][0]=new Edge(u,i); } else if(edge[v][1]==null) { edge[v][1]=new Edge(u,i); } else { exists=false; } } if(!exists) { pw.println(-1); continue; } int head=0; for(int i=1;i<=n;i++) { if(edge[i][1]==null) { head=i; break; } } int wt[]=new int[n-1]; int prev=2; while(true) { Edge edge1; edge1=edge[head][0]; if(edge1==null) { break; } if(wt[edge1.edgeNum]!=0) { edge1=edge[head][1]; if(edge1==null || wt[edge1.edgeNum]!=0) { break; } } if(prev==2) { wt[edge1.edgeNum]=3; prev=3; } else { wt[edge1.edgeNum]=2; prev=2; } head=edge1.node; } for(int i=0;i<n-1;i++) { pw.print(wt[i]+" "); } pw.println(); } pw.flush(); } } class Edge { int node; int edgeNum; public Edge(int node,int edgeNum) { this.node=node; this.edgeNum=edgeNum; } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
80dec6a78da6ed77282cfb71bc19249a
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.io.*; public class TestClass { BufferedReader br; StringTokenizer st; public TestClass(){ // constructor 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 void sort(int[] arr){ int n = arr.length; Random rnd = new Random(); for(int i = 0; i < n; ++i){ int tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } Arrays.sort(arr); } static long gcd(long a, long b) { if(b == 0) { return a; } return gcd(b, a % b); } static class Edge { int v; int s_no; Edge(int v, int s_no) { this.v = v; this.s_no = s_no; } } public static void main(String[] args) throws Exception{ TestClass in = new TestClass(); PrintWriter out = new PrintWriter(System.out); int test = in.nextInt(); while(test-- > 0) { int n = in.nextInt(); ArrayList<Edge> graph[] = new ArrayList[n + 1]; for(int i = 0; i <= n; i++) { graph[i] = new ArrayList<>(); } int deg[] = new int[n + 1]; for(int i = 1; i < n; i++) { int u = in.nextInt(); int v = in.nextInt(); graph[u].add(new Edge(v, i)); graph[v].add(new Edge(u, i)); deg[u]++; deg[v]++; } boolean ok = true; for(int i = 1; i <= n; i++) { if(deg[i] > 2) { ok = false; break; } } if(ok) { int ans[] = new int[n]; for(int i = 1; i <= n; i++) { if(deg[i] == 1) { dfs(i, ans, graph, -1, 0); break; } } StringBuilder sb = new StringBuilder(); for(int i = 1; i < n; i++) { sb.append(ans[i] + " "); } out.println(sb.toString()); } else { out.println(-1); } } out.flush(); out.close(); } static void dfs(int u, int ans[], ArrayList<Edge> graph[], int par, int prev_ed_wt) { for(Edge e : graph[u]) { if(e.v == par) { continue; } ans[e.s_no] = ((prev_ed_wt == 2) ? 3 : 2); dfs(e.v, ans, graph, u, ans[e.s_no]); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
e0257d4c0d229aa06e31f6ca935ebdda
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.math.BigInteger; public final class A { static PrintWriter out = new PrintWriter(System.out); static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); static ArrayList<Integer> g[]; static long mod=(long) 998244353,INF=Long.MAX_VALUE; static boolean set[]; static int par[],col[],D[]; static long A[]; static int seg[]; static int dp[][]; public static void main(String args[])throws IOException { /* * star,rope,TPST * BS,LST,MS,MQ */ int T=i(); outer:while(T-->0) { int N=i(); setGraph(N); int max=0; int A[][]=new int[N][2]; int start=0; for(int i=0; i<N-1; i++) { int a=i(),b=i(); A[i][0]=a; A[i][1]=b; g[a].add(i); g[b].add(i); if(g[a].size()>2 || g[b].size()>2) { max=3; } } // print(A); // for(int i=1; i<=N; i++)System.out.println(g[i]); if(max>2)ans.append("-1\n"); else { if(N==1) { ans.append("2\n"); continue outer; } int f[]=new int[N-1]; f[0]=2; start=A[0][0]; f(A[0][0],0,A,f); f(A[0][1],0,A,f); // print(f); for(int a:f)ans.append(a+" "); ans.append("\n"); } } out.println(ans); out.close(); } static void f(int n,int last,int A[][],int f[]) { // print(f); for(int i:g[n]) { int b=A[i][0]^A[i][1]^n; // System.out.println(b+" "+n); if(f[i]==0) { //call for b f[i]=7-f[last]; f(b,i,A,f); } } } static int f(int N,int M,int x,int y) { N-=1; M-=1; N=Math.abs(N-x); M=Math.abs(M-y); int a=x+y; a=Math.min(a, x+M); a=Math.min(a, y+N); a=Math.min(a, N+M); return a; } static TreeNode start; public static void f(TreeNode root,TreeNode p,int r) { if(root==null)return; if(p!=null) { root.par=p; } if(root.val==r)start=root; f(root.left,root,r); f(root.right,root,r); } public static HashSet<Integer> st; public static int i=0; public static HashMap<Integer,Integer> mp=new HashMap<>(); public static TreeNode buildTree(int[] preorder, int[] inorder) { for(int i=0; i<preorder.length; i++)mp.put(inorder[i],i); TreeNode head=new TreeNode(); f(preorder,inorder,0,inorder.length-1,head); return head; } public static void f(int pre[],int in[],int l,int r,TreeNode root) { // System.out.println(pre[i]); root.val=pre[i]; int it=mp.get(pre[i++]);// // System.out.println(it); if(it-1>=l) { TreeNode left=new TreeNode(); root.left=left; f(pre,in,l,it-1,left); } if(it+1<=r) { TreeNode right=new TreeNode(); root.right=right; f(pre,in,it+1,r,right); } } static int right(int A[],int Limit,int l,int r) { while(r-l>1) { int m=(l+r)/2; if(A[m]<Limit)l=m; else r=m; } return l; } static int left(int A[],int a,int l,int r) { while(r-l>1) { int m=(l+r)/2; if(A[m]<a)l=m; else r=m; } return l; } static int f(int k,int x,int N) { int l=x-1,r=N; while(r-l>1) { int m=(l+r)/2; int a=ask(1,0,N-1,x,m); if(a<k) { l=m; } else r=m; } //System.out.println("-------"); if(r==N)return -1; return r; } static void build(int v,int tl,int tr,int A[]) { if(tl==tr) { seg[v]=A[tl]; return; } int tm=(tl+tr)/2; build(v*2,tl,tm,A); build(v*2+1,tm+1,tr,A); seg[v]=Math.max(seg[v*2],seg[v*2+1]); } static void update(int v,int tl,int tr,int index,int a) { if(index==tl && tl==tr) seg[v]=a; else { int tm=(tl+tr)/2; if(index<=tm)update(2*v,tl,tm,index,a); else update(2*v+1,tm+1,tr,index,a); seg[v]=Math.max(seg[v*2],seg[v*2+1]); } } static int ask(int v,int tl,int tr,int l,int r) { if(l>r)return -1; if(l==tl && tr==r)return seg[v]; int tm=(tl+tr)/2; return Math.max(ask(v*2,tl,tm,l,Math.min(tm, r)),ask(2*v+1,tm+1,tr,Math.max(tm+1, l),r)); } // static int query(long a,TreeNode root) // { // long p=1L<<30; // TreeNode temp=root; // while(p!=0) // { // System.out.println(a+" "+p); // if((a&p)!=0) // { // temp=temp.right; // // } // else temp=temp.left; // p>>=1; // } // return temp.index; // } // static void delete(long a,TreeNode root) // { // long p=1L<<30; // TreeNode temp=root; // while(p!=0) // { // if((a&p)!=0) // { // temp.right.cnt--; // temp=temp.right; // } // else // { // temp.left.cnt--; // temp=temp.left; // } // p>>=1; // } // } // static void insert(long a,TreeNode root,int i) // { // long p=1L<<30; // TreeNode temp=root; // while(p!=0) // { // if((a&p)!=0) // { // temp.right.cnt++; // temp=temp.right; // } // else // { // temp.left.cnt++; // temp=temp.left; // } // p>>=1; // } // temp.index=i; // } // static TreeNode create(int p) // { // // TreeNode root=new TreeNode(0); // if(p!=0) // { // root.left=create(p-1); // root.right=create(p-1); // } // return root; // } static boolean f(long A[],long m,int N) { long B[]=new long[N]; for(int i=0; i<N; i++) { B[i]=A[i]; } for(int i=N-1; i>=0; i--) { if(B[i]<m)return false; if(i>=2) { long extra=Math.min(B[i]-m, A[i]); long x=extra/3L; B[i-2]+=2L*x; B[i-1]+=x; } } return true; } static int f(int l,int r,long A[],long x) { while(r-l>1) { int m=(l+r)/2; if(A[m]>=x)l=m; else r=m; } return r; } static boolean f(long m,long H,long A[],int N) { long s=m; for(int i=0; i<N-1;i++) { s+=Math.min(m, A[i+1]-A[i]); } return s>=H; } static boolean f(int i,int j,long last,boolean win[]) { if(i>j)return false; if(A[i]<=last && A[j]<=last)return false; long a=A[i],b=A[j]; //System.out.println(a+" "+b); if(a==b) { return win[i] | win[j]; } else if(a>b) { boolean f=false; if(b>last)f=!f(i,j-1,b,win); return win[i] | f; } else { boolean f=false; if(a>last)f=!f(i+1,j,a,win); return win[j] | f; } } static long ask(long l,long r) { System.out.println("? "+l+" "+r); return l(); } static long f(long N,long M) { long s=0; if(N%3==0) { N/=3; s=N*M; } else { long b=N%3; N/=3; N++; s=N*M; N--; long a=N*M; if(M%3==0) { M/=3; a+=(b*M); } else { M/=3; M++; a+=(b*M); } s=Math.min(s, a); } return s; } static int ask(StringBuilder sb,int a) { System.out.println(sb+""+a); return i(); } static void swap(char X[],int i,int j) { char x=X[i]; X[i]=X[j]; X[j]=x; } static int min(int a,int b,int c) { return Math.min(Math.min(a, b), c); } static long and(int i,int j) { System.out.println("and "+i+" "+j); return l(); } static long or(int i,int j) { System.out.println("or "+i+" "+j); return l(); } static int len=0,number=0; static void f(char X[],int i,int num,int l) { if(i==X.length) { if(num==0)return; //update our num if(isPrime(num))return; if(l<len) { len=l; number=num; } return; } int a=X[i]-'0'; f(X,i+1,num*10+a,l+1); f(X,i+1,num,l); } static boolean is_Sorted(int A[]) { int N=A.length; for(int i=1; i<=N; i++)if(A[i-1]!=i)return false; return true; } static boolean f(StringBuilder sb,String Y,String order) { StringBuilder res=new StringBuilder(sb.toString()); HashSet<Character> set=new HashSet<>(); for(char ch:order.toCharArray()) { set.add(ch); for(int i=0; i<sb.length(); i++) { char x=sb.charAt(i); if(set.contains(x))continue; res.append(x); } } String str=res.toString(); return str.equals(Y); } static boolean all_Zero(int f[]) { for(int a:f)if(a!=0)return false; return true; } static long form(int a,int l) { long x=0; while(l-->0) { x*=10; x+=a; } return x; } static int count(String X) { HashSet<Integer> set=new HashSet<>(); for(char x:X.toCharArray())set.add(x-'0'); return set.size(); } static int f(long K) { long l=0,r=K; while(r-l>1) { long m=(l+r)/2; if(m*m<K)l=m; else r=m; } return (int)l; } // static void build(int v,int tl,int tr,long A[]) // { // if(tl==tr) // { // seg[v]=A[tl]; // } // else // { // int tm=(tl+tr)/2; // build(v*2,tl,tm,A); // build(v*2+1,tm+1,tr,A); // seg[v]=Math.min(seg[v*2], seg[v*2+1]); // } // } static int [] sub(int A[],int B[]) { int N=A.length; int f[]=new int[N]; for(int i=N-1; i>=0; i--) { if(B[i]<A[i]) { B[i]+=26; B[i-1]-=1; } f[i]=B[i]-A[i]; } for(int i=0; i<N; i++) { if(f[i]%2!=0)f[i+1]+=26; f[i]/=2; } return f; } static int[] f(int N) { char X[]=in.next().toCharArray(); int A[]=new int[N]; for(int i=0; i<N; i++)A[i]=X[i]-'a'; return A; } static int max(int a ,int b,int c,int d) { a=Math.max(a, b); c=Math.max(c,d); return Math.max(a, c); } static int min(int a ,int b,int c,int d) { a=Math.min(a, b); c=Math.min(c,d); return Math.min(a, c); } static HashMap<Integer,Integer> Hash(int A[]) { HashMap<Integer,Integer> mp=new HashMap<>(); for(int a:A) { int f=mp.getOrDefault(a,0)+1; mp.put(a, f); } return mp; } static long mul(long a, long b) { return ( a %mod * 1L * b%mod )%mod; } static void swap(int A[],int a,int b) { int t=A[a]; A[a]=A[b]; A[b]=t; } static int find(int a) { if(par[a]<0)return a; return par[a]=find(par[a]); } static void union(int a,int b) { a=find(a); b=find(b); if(a!=b) { if(par[a]>par[b]) //this means size of a is less than that of b { int t=b; b=a; a=t; } par[a]+=par[b]; par[b]=a; } } static boolean isSorted(int A[]) { for(int i=1; i<A.length; i++) { if(A[i]<A[i-1])return false; } return true; } static boolean isDivisible(StringBuilder X,int i,long num) { long r=0; for(; i<X.length(); i++) { r=r*10+(X.charAt(i)-'0'); r=r%num; } return r==0; } static int lower_Bound(int A[],int low,int high, int x) { if (low > high) if (x >= A[high]) return A[high]; int mid = (low + high) / 2; if (A[mid] == x) return A[mid]; if (mid > 0 && A[mid - 1] <= x && x < A[mid]) return A[mid - 1]; if (x < A[mid]) return lower_Bound( A, low, mid - 1, x); return lower_Bound(A, mid + 1, high, x); } static String f(String A) { String X=""; for(int i=A.length()-1; i>=0; i--) { int c=A.charAt(i)-'0'; X+=(c+1)%2; } return X; } static void sort(long[] a) //check for long { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static String swap(String X,int i,int j) { char ch[]=X.toCharArray(); char a=ch[i]; ch[i]=ch[j]; ch[j]=a; return new String(ch); } static int sD(long n) { if (n % 2 == 0 ) return 2; for (int i = 3; i * i <= n; i += 2) { if (n % i == 0 ) return i; } return (int)n; } static void setGraph(int N) { par=new int[N+1]; D=new int[N+1]; g=new ArrayList[N+1]; set=new boolean[N+1]; col=new int[N+1]; for(int i=0; i<=N; i++) { col[i]=-1; g[i]=new ArrayList<>(); // D[i]=Integer.MAX_VALUE; } } static long pow(long a,long b) { //long mod=1000000007; long pow=1; long x=a; while(b!=0) { if((b&1)!=0)pow=(pow*x)%mod; x=(x*x)%mod; b/=2; } return pow; } static long toggleBits(long x)//one's complement || Toggle bits { int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1; return ((1<<n)-1)^x; } static int countBits(long a) { return (int)(Math.log(a)/Math.log(2)+1); } static long fact(long N) { long n=2; if(N<=1)return 1; else { for(int i=3; i<=N; i++)n=(n*i)%mod; } return n; } static int kadane(int A[]) { int lsum=A[0],gsum=A[0]; for(int i=1; i<A.length; i++) { lsum=Math.max(lsum+A[i],A[i]); gsum=Math.max(gsum,lsum); } return gsum; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static boolean isPrime(long N) { if (N<=1) return false; if (N<=3) return true; if (N%2 == 0 || N%3 == 0) return false; for (int i=5; i*i<=N; i=i+6) if (N%i == 0 || N%(i+2) == 0) return false; return true; } static void print(char A[]) { for(char c:A)System.out.print(c+" "); System.out.println(); } static void print(boolean A[]) { for(boolean c:A)System.out.print(c+" "); System.out.println(); } static void print(int A[]) { for(int a:A)System.out.print(a+" "); System.out.println(); } static void print(long A[]) { for(long i:A)System.out.print(i+ " "); System.out.println(); } static void print(boolean A[][]) { for(boolean a[]:A)print(a); } static void print(long A[][]) { for(long a[]:A)print(a); } static void print(int A[][]) { for(int a[]:A)print(a); } static void print(ArrayList<Integer> A) { for(int a:A)System.out.print(a+" "); System.out.println(); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static int[] input(int N){ int A[]=new int[N]; for(int i=0; i<N; i++) { A[i]=in.nextInt(); } return A; } static long[] inputLong(int N) { long A[]=new long[N]; for(int i=0; i<A.length; i++)A[i]=in.nextLong(); return A; } static long GCD(long a,long b) { if(b==0) { return a; } else return GCD(b,a%b ); } } class segNode { long pref,suff,sum,max; segNode(long a,long b,long c,long d) { pref=a; suff=b; sum=c; max=d; } } //class TreeNode //{ // int cnt,index; // TreeNode left,right; // TreeNode(int c) // { // cnt=c; // index=-1; // } // TreeNode(int c,int index) // { // cnt=c; // this.index=index; // } //} class post implements Comparable<post> { long x,y,d,t; post(long a,long b,long c) { x=a; y=b; d=c; } public int compareTo(post X) { if(X.t==this.t) { return 0; } else { long xt=this.t-X.t; if(xt>0)return 1; return -1; } } } class TreeNode { int val; TreeNode left, right,par; TreeNode() {} TreeNode(int item) { val = item; left =null; right = null; par=null; } } class edge { int a,wt; edge(int a,int w) { this.a=a; wt=w; } } //Code For FastReader //Code For FastReader //Code For FastReader //Code For FastReader class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st==null || !st.hasMoreElements()) { try { st=new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
74c43d5c76dcffa62b5f9c2c8ef2abbb
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
//import java.io.IOException; import java.io.*; import java.util.*; public class NotAssigning { static InputReader inputReader=new InputReader(System.in); static int n=(int)(1e5); static TreeSet<Integer>treeSet=new TreeSet<>(); static boolean isprime[]=new boolean[n+1]; static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static void solve() throws IOException { int n=inputReader.nextInt(); List<Integer>graph[]=new List[n+1]; for (int i=0;i<=n;i++) { graph[i]=new ArrayList<>(); } HashMap<List<Integer>,Integer>indexmap=new HashMap<>(); for (int i=0;i<n-1;i++) { int u=inputReader.nextInt(); int v=inputReader.nextInt(); List<Integer>list=new ArrayList<>(Arrays.asList(u,v)); Collections.sort(list); indexmap.put(list,i); graph[u].add(v); graph[v].add(u); } for (int i=0;i<=n;i++) { if (graph[i].size()>2) { out.println(-1); return; } } int leaf=-1; for (int i=1;i<=n;i++) { if (graph[i].size()==1) { leaf=i; break; } } boolean visited[]=new boolean[n+1]; visited[leaf]=true; int answer[]=new int[n-1]; List<Integer>list=new ArrayList<>(Arrays.asList(leaf,graph[leaf].get(0))); Collections.sort(list); int ind=indexmap.get(list); answer[ind]=2; dfs(graph[leaf].get(0),2,graph,visited,indexmap,answer); for (int ele:answer) { out.print(ele+" "); } out.println(); } static void dfs(int u,int prev,List<Integer> graph[],boolean visited[],HashMap<List<Integer>,Integer>indexmap,int answer[]) { visited[u]=true; int now=2; if (prev==2) { now=3; } for (int next:graph[u]) { if (!visited[next]) { List<Integer>list=new ArrayList<>(Arrays.asList(next,u)); Collections.sort(list); int ind=indexmap.get(list); answer[ind]=now; dfs(next,now,graph,visited,indexmap,answer); } } } static PrintWriter out=new PrintWriter((System.out)); public static void main(String args[])throws IOException { Arrays.fill(isprime,true); for (int i=2;i*i<=n;i++) { for (int j=2;j<=n;j++) { isprime[j]=false; } } for (int i=2;i<=n;i++) { if (isprime[i]==true) { treeSet.add(i); } } int t=inputReader.nextInt(); while (t-->0) { solve(); } long s = System.currentTimeMillis(); // out.println(System.currentTimeMillis()-s+"ms"); out.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
9703a110f5222334ce1ae049b35779db
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; public class Hiking { static PrintWriter pw = new PrintWriter(System.out); static Scanner sc = new Scanner(System.in); static ArrayList<Integer> []graph; static HashMap<pair, Integer> hm; static int []ans; static boolean []vis; public static void solve(int node,boolean f) { vis[node]=true; for(int x:graph[node]) { if(!vis[x]) { pair p=new pair(Math.min(x, node), Math.max(x, node)); if(f) { ans[hm.get(p)]=2; } else ans[hm.get(p)]=3; f=!f; solve(x, f); } } } public static void main(String [] args) throws IOException, InterruptedException { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); graph=new ArrayList[n+1]; vis=new boolean[n+1]; for(int i=1;i<=n;i++)graph[i]=new ArrayList<>(); ans=new int[n-1]; hm=new HashMap<>(); for(int i=0;i<n-1;i++) { int u=sc.nextInt(),v=sc.nextInt(); pair p=new pair(Math.min(u, v), Math.max(u, v)); hm.put(p, i); graph[u].add(v); graph[v].add(u); } boolean f=false; int node=-1; for(int i=1;i<=n;i++) { f|=graph[i].size()>=3; if(graph[i].size()==1) node=i; } if(f) { pw.println(-1); continue; } solve(node, true); for(int i:ans)pw.print(i+" "); pw.println(); } pw.flush(); } static class pair implements Comparable<pair> { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } 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 Integer(x).hashCode() * 31 + new Integer(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return this.z - other.z; } return this.y - other.y; } else { return this.x - other.x; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws IOException { br = new BufferedReader(new FileReader(file)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String readAllLines(BufferedReader reader) throws IOException { StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line); content.append(System.lineSeparator()); } return content.toString(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } 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 Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
d442744aebb61fdd2ae9b68de267b111
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; @SuppressWarnings("unchecked") public class NotAssigning{ static List<Integer> adj[]; static Map<String, Integer> prime; static boolean vis[]; static void dfs(int u, int val){ vis[u]=true; for(int v: adj[u]){ if(vis[v]) continue; prime.put(u+":"+v, val); prime.put(v+":"+u, val); dfs(v, val == 2? 3: 2); } } static String solve(int n, List<int[]> edges){ prime = new HashMap<>(); adj = new ArrayList[n]; vis = new boolean[n]; Arrays.setAll(adj, idx -> new ArrayList<>()); boolean isPossible=true; List<Integer> start = new ArrayList<>(); for(int edge[]: edges){ int u=edge[0], v=edge[1]; adj[u].add(v); adj[v].add(u); } for(int i=0; i<n; i++){ int size=adj[i].size(); if(size == 1) start.add(i); if(size > 2) isPossible=false; } if(!isPossible) return "-1"; for(int u: start){ if(vis[u]) continue; dfs(u, 3); } StringBuilder sb = new StringBuilder(); for(int edge[]: edges){ int u=edge[0], v=edge[1]; sb.append(prime.getOrDefault(u+":"+v, 2)+ " "); } return sb.toString(); } public static void main(String args[])throws IOException{ Scanner sc = new Scanner(System.in); int tests = sc.nextInt(); StringBuilder sb = new StringBuilder(); while(tests --> 0){ int n = sc.nextInt(); List<int[]> edges = new ArrayList<>(); for(int i=1; i<n; i++){ int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; edges.add(new int[]{u, v}); } String res = solve(n, edges); sb.append(res+"\n"); } System.out.println(sb.toString()); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
527be0e84df7744021a163596e1917fb
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.lang.*; public class Solution{ static class Graph{ public static class Vertex{ HashMap<Integer,Integer> nb= new HashMap<>(); // for neighbours of each vertex } public static HashMap<Integer,Vertex> vt; // for vertices(all) public Graph(){ vt= new HashMap<>(); } public static int numVer(){ return vt.size(); } public static boolean contVer(int ver){ return vt.containsKey(ver); } public static void addVer(int ver){ Vertex v= new Vertex(); vt.put(ver,v); } public static void addEdge(int ver1, int ver2, int weight){ if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){ return; } Vertex v1= vt.get(ver1); Vertex v2= vt.get(ver2); v1.nb.put(ver2,weight); // if previously there is an edge, then this replaces that edge v2.nb.put(ver1,weight); } public static void delEdge(int ver1, int ver2){ if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){ return; } vt.get(ver1).nb.remove(ver2); vt.get(ver2).nb.remove(ver1); } public static void delVer(int ver){ if(!vt.containsKey(ver)){ return; } Vertex v1= vt.get(ver); ArrayList<Integer> arr= new ArrayList<>(v1.nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int s= arr.get(i); vt.get(s).nb.remove(ver); } vt.remove(ver); } static boolean done[]; static int parent[]; static ArrayList<Integer>vals= new ArrayList<>(); public static boolean isCycle(int i){ Stack<Integer>stk= new Stack<>(); stk.push(i); while(!stk.isEmpty()){ int x= stk.pop(); vals.add(x); // System.out.print("current="+x+" stackinit="+stk); if(!done[x]){ done[x]=true; } else if(done[x] ){ return true; } ArrayList<Integer>ar= new ArrayList<>(vt.get(x).nb.keySet()); for (int j = 0; j <ar.size() ; j++) { if(parent[x]!=ar.get(j)){ parent[ar.get(j)]=x; stk.push(ar.get(j)); } } // System.out.println(" stackfin="+stk); } return false; } static int[]level; static int[] curr; static int[] fin; public static void dfs(int src){ done[src]=true; level[src]=0; Queue<Integer>q= new LinkedList<>(); q.add(src); while(!q.isEmpty()){ int x= q.poll(); ArrayList<Integer>arr= new ArrayList<>(vt.get(x).nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int v= arr.get(i); if(!done[v]){ level[v]=level[x]+1; done[v]=true; q.offer(v); } } } } static int oc[]; static int ec[]; public static void dfs1(int src){ Queue<Integer>q= new LinkedList<>(); q.add(src); done[src]= true; // int count=0; while(!q.isEmpty()){ int x= q.poll(); // System.out.println("x="+x); int even= ec[x]; int odd= oc[x]; if(level[x]%2==0){ int val= (curr[x]+even)%2; if(val!=fin[x]){ // System.out.println("bc"); even++; vals.add(x); } } else{ int val= (curr[x]+odd)%2; if(val!=fin[x]){ // System.out.println("bc"); odd++; vals.add(x); } } ArrayList<Integer>arr= new ArrayList<>(vt.get(x).nb.keySet()); // System.out.println(arr); for (int i = 0; i <arr.size() ; i++) { int v= arr.get(i); if(!done[v]){ done[v]=true; oc[v]=odd; ec[v]=even; q.add(v); } } } } static long popu[]; static long happy[]; static long count[]; // total people crossing that pos static long sum[]; // total sum of happy people including that. public static void bfs(int x){ done[x]=true; long total= popu[x]; // long smile= happy[x]; ArrayList<Integer>nbrs= new ArrayList<>(vt.get(x).nb.keySet()); for (int i = 0; i <nbrs.size() ; i++) { int r= nbrs.get(i); if(!done[r]){ bfs(r); total+=count[r]; // smile+=sum[r]; } } count[x]=total; // sum[x]=smile; } public static void bfs1(int x){ done[x]=true; // long total= popu[x]; long smile= 0; ArrayList<Integer>nbrs= new ArrayList<>(vt.get(x).nb.keySet()); for (int i = 0; i <nbrs.size() ; i++) { int r= nbrs.get(i); if(!done[r]){ bfs1(r); // total+=count[r]; smile+=happy[r]; } } // count[x]=total; sum[x]=smile; } } static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } static class disjointSet{ HashMap<Integer, Node> mp= new HashMap<>(); public static class Node{ int data; Node parent; int rank; } public void create(int val){ Node nn= new Node(); nn.data=val; nn.parent=nn; nn.rank=0; mp.put(val,nn); } public int findparent(int val){ return findparentn(mp.get(val)).data; } public Node findparentn(Node n){ if(n==n.parent){ return n; } Node rr= findparentn(n.parent); n.parent=rr; return rr; } public void union(int val1, int val2){ // can also be used to check cycles Node n1= findparentn(mp.get(val1)); Node n2= findparentn(mp.get(val2)); if(n1.data==n2.data) { return; } if(n1.rank<n2.rank){ n1.parent=n2; } else if(n2.rank<n1.rank){ n2.parent=n1; } else { n2.parent=n1; n1.rank++; } } } static class Pair implements Comparable<Pair>{ int x; int y; // smallest form only public Pair(int x, int y){ this.x=x; this.y=y; } @Override public int compareTo(Pair x){ if(this.x>x.x){ return 1; } else if(this.x==x.x){ if(this.y>x.y){ return 1; } else if(this.y==x.y){ return 0; } else{ return -1; } } return -1; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return x == pair.x && y == pair.y; } @Override public int hashCode() { return Objects.hash(x, y); } public String toString(){ return x+" "+y; } } public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int t= Reader.nextInt(); for (int tt = 0; tt <t ; tt++) { int n = Reader.nextInt(); Graph g = new Graph(); for (int i = 1; i <= n; i++) { g.addVer(i); } // keep adding 2, 3 HashMap<Pair, Integer> map = new HashMap<>(); for (int i = 0; i < n - 1; i++) { int x1 = Reader.nextInt(); int x2 = Reader.nextInt(); g.addEdge(x1, x2, 100); map.put(new Pair(x1, x2), i); } int ans[] = new int[n - 1]; boolean poss = true; int root = -1; for (int i = 1; i <= n; i++) { if (g.vt.get(i).nb.size() >= 3) { poss = false; } if (g.vt.get(i).nb.size() == 1) { root = i; } } if(!poss){ out.append(-1+"\n"); continue; } Stack<Integer> stk = new Stack<>(); stk.add(root); boolean done[] = new boolean[n + 1]; done[root] = true; int curr=2; while (!stk.isEmpty()) { int num= stk.pop(); done[num]=true; for (int i:g.vt.get(num).nb.keySet()) { if(!done[i]){ stk.add(i); int ind=1; if(map.containsKey(new Pair(num,i))) { ind = map.get(new Pair(num, i)); } else{ ind= map.get(new Pair(i,num)); } ans[ind]=curr; if(curr==2){ curr=3; } else{ curr=2; } } } } for (int i = 0; i <n-1 ; i++) { out.append(ans[i]+" "); } out.append("\n"); } out.flush(); out.close(); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
01d7bfbda8e935df71cc2849cd741b87
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; @SuppressWarnings("unchecked") public class NotAssigning{ static List<Integer> adj[]; static Map<String, Integer> prime; static boolean vis[]; static void dfs(int u, int val){ vis[u]=true; for(int v: adj[u]){ if(vis[v]) continue; prime.put(u+":"+v, val); prime.put(v+":"+u, val); dfs(v, val == 2? 3: 2); } } static String solve(int n, List<int[]> edges){ prime = new HashMap<>(); adj = new ArrayList[n]; vis = new boolean[n]; Arrays.setAll(adj, idx -> new ArrayList<>()); boolean isPossible=true; List<Integer> start = new ArrayList<>(); for(int edge[]: edges){ int u=edge[0], v=edge[1]; adj[u].add(v); adj[v].add(u); } for(int i=0; i<n; i++){ int size=adj[i].size(); if(size == 1) start.add(i); if(size > 2) isPossible=false; } if(!isPossible) return "-1"; for(int u: start){ if(vis[u]) continue; dfs(u, 3); } StringBuilder sb = new StringBuilder(); for(int edge[]: edges){ int u=edge[0], v=edge[1]; sb.append(prime.getOrDefault(u+":"+v, 2)+ " "); } return sb.toString(); } public static void main(String args[])throws IOException{ Scanner sc = new Scanner(System.in); int tests = sc.nextInt(); StringBuilder sb = new StringBuilder(); while(tests --> 0){ int n = sc.nextInt(); List<int[]> edges = new ArrayList<>(); for(int i=1; i<n; i++){ int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; edges.add(new int[]{u, v}); } String res = solve(n, edges); sb.append(res+"\n"); } System.out.println(sb.toString()); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
3797514f338d18282ba08bc2d54dba5b
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static class DSU { private int[] parent; private int totalGroup; public DSU(int n) { parent = new int[n]; totalGroup = n; for (int i = 0; i < n; i++) { parent[i] = i; } } public boolean union(int a, int b) { int parentA = findParent(a); int parentB = findParent(b); if (parentA == parentB) { return false; } totalGroup--; if (parentA < parentB) { this.parent[parentB] = parentA; } else { this.parent[parentA] = parentB; } return true; } public int findParent(int a) { if (parent[a] != a) { parent[a] = findParent(parent[a]); } return parent[a]; } public int getTotalGroup() { return totalGroup; } } public static void main(String[] args) throws Exception { int tc = io.nextInt(); for (int i = 0; i < tc; i++) { solve(); } io.close(); } private static void solve() throws Exception { int n = io.nextInt(); int[][] edges = new int[n - 1][2]; Map<Integer, List<Integer>> map = new HashMap<>(); for (int i = 0; i < n - 1; i++) { edges[i][0] = io.nextInt(); edges[i][1] = io.nextInt(); map.computeIfAbsent(edges[i][0], k -> new ArrayList<>()).add(edges[i][1]); map.computeIfAbsent(edges[i][1], k -> new ArrayList<>()).add(edges[i][0]); } Map<String, Integer> path = new HashMap<>(); int root = edges[0][0]; if (dfs(-1, root, map, path)) { for (int[] edge : edges) { io.print(path.get(edge[0] + " " + edge[1]) + " "); } io.println(); } else { io.println(-1); } } static boolean dfs(int parent, int curr, Map<Integer, List<Integer>> map, Map<String, Integer> path) { if (map.get(curr).size() > 2) return false; if (parent != -1) { int parentPath = path.getOrDefault(parent + " " + curr, 2); for (int child : map.get(curr)) { if (child == parent) continue; path.put(curr + " " + child, parentPath == 2 ? 5 : 2); path.put(child + " " + curr, parentPath == 2 ? 5 : 2); if (!dfs(curr, child, map, path)) { return false; } } } else { List<Integer> childs = map.get(curr); path.put(curr + " " + childs.get(0), 2); path.put(childs.get(0) + " " + curr, 2); if (!dfs(curr, childs.get(0), map, path)) { return false; } if (childs.size() == 2) { path.put(curr + " " + childs.get(1), 5); path.put(childs.get(1) + " " + curr, 5); if (!dfs(curr, childs.get(1), map, path)) { return false; } } } return true; } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(a.length); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } //-----------PrintWriter for faster output--------------------------------- public static FastIO io = new FastIO(); //-----------MyScanner class for faster input---------- static class FastIO extends PrintWriter { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar, numChars; // standard input public FastIO() { this(System.in, System.out); } public FastIO(InputStream i, OutputStream o) { super(o); stream = i; } // file input public FastIO(String i, String o) throws IOException { super(new FileWriter(o)); stream = new FileInputStream(i); } // throws InputMismatchException() if previously detected end of file private int nextByte() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars == -1) return -1; // end of file } return buf[curChar++]; } // to read in entire lines, replace c <= ' ' // with a function that checks whether c is a line break public String next() { int c; do { c = nextByte(); } while (c <= ' '); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > ' '); return res.toString(); } public String nextLine() { int c; do { c = nextByte(); } while (c < '\n'); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n'); return res.toString(); } public int nextInt() { int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10 * res + c - '0'; c = nextByte(); } while (c > ' '); return res * sgn; } public long nextLong() { int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10 * res + c - '0'; c = nextByte(); } while (c > ' '); return res * sgn; } public double nextDouble() { return Double.parseDouble(next()); } } //-------------------------------------------------------- }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
6d6d363921699df369ac13512a99ec6d
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
// package codeforces; import java.io.*; import java.util.*; public class practice { static FastScanner fs = new FastScanner(); public static void main(String[] args) { int t = 1; t = fs.nextInt(); for(int i=1;i<=t;i++) { solve(t); } } public static void dfs(int u, boolean visited[], ArrayList<ArrayList<Integer>> g[], int ans[], int x) { visited[u] = true; for(ArrayList<Integer> v:g[u]) { if(!visited[v.get(0)]) { ans[v.get(1)]=x; dfs(v.get(0),visited,g,ans,x^1); } } return; } @SuppressWarnings("unused") public static void solve(int tt) { int n = fs.nextInt(); @SuppressWarnings("unchecked") ArrayList<ArrayList<Integer>> g[] = new ArrayList[n]; for(int i=0;i<n;i++)g[i]=new ArrayList<ArrayList<Integer>>(); int ans[] = new int[n]; boolean visited[] = new boolean[n]; int deg[] = new int[n]; for(int i=0;i<n;i++)deg[i]=0; for(int i=0;i<n-1;i++) { int u = fs.nextInt() - 1;int v = fs.nextInt() - 1; ArrayList<Integer> L1=new ArrayList<Integer>(); L1.add(v);L1.add(i); g[u].add(L1); ArrayList<Integer> L2=new ArrayList<Integer>(); L2.add(u);L2.add(i); g[v].add(L2); deg[u]++; deg[v]++; } // degree must be <=2 cause if greater than that then sum will be always non prime // there will be exactly 2 leafs, we start dfs from one of them int leaf=-1; boolean notcool=false; for(int i=0;i<n;i++) { if(deg[i]>2) { System.out.println(-1); return; } } for(int i=0;i<n;i++) { if(deg[i]==1) { leaf=i; break; } } dfs(leaf,visited,g,ans,2); for(int i=0;i<n-1;i++)System.out.print(ans[i]+" "); System.out.println(); return; } public static int [] sortarray(int a[]) { ArrayList<Integer> L = new ArrayList<Integer>(); for(int i:a) { L.add(i); } Collections.sort(L); for(int i=0;i<L.size();i++)a[i]=L.get(i); return a; } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } ArrayList<Integer> readList(int n) { ArrayList<Integer> a = new ArrayList<Integer>(); int x; for(int i=0;i<n;i++) { x=fs.nextInt(); a.add(x); } return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
256c0f56b34a5708d3b0b33b98dcddda
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Practice { static Scanner scn = new Scanner(System.in); static StringBuilder sb = new StringBuilder(); public static void main(String[] ScoobyDoobyDo) { p = new HashSet<>(); int t = scn.nextInt(); for(int tests = 0; tests < t; tests++) solve(); System.out.println(sb); } public static void solve() { int n = scn.nextInt(); graph = new ArrayList<>(); map = new HashMap<>(); vis = new boolean[n + 1]; for(int i = 0; i <= n; i++) graph.add(new ArrayList<>()); List<int[]> input = new ArrayList<>(); for(int i = 1; i < n; i++) { int x = scn.nextInt(), y = scn.nextInt(); int min = min(x, y); int max = max(x, y); input.add(new int[] {min, max}); graph.get(x).add(y); graph.get(y).add(x); } int start = 1; for(int i = 1; i <= n; i++) { if(graph.get(i).size() >= 3) { sb.append(-1 + "\n"); return; } if(graph.get(i).size() == 1) start = i; } dfs(start, 5); List<Integer> answer = new ArrayList<>(); for(int i = 0; i + 1 < n; i++) { int x = input.get(i)[0], y = input.get(i)[1]; int get = map.get(x + "=" + y); sb.append(get + " "); } sb.append("\n"); } static HashMap<String, Integer> map; static List<List<Integer>> graph; static boolean[] vis; public static void dfs(int i, int x) { if(vis[i]) return; vis[i] = true; for(int k : graph.get(i)) { if(vis[k]) continue; int min = min(i, k); int max = max(i, k); map.put(min + "=" + max, x); dfs(k, (x == 2 ? 5 : 2)); } } static HashSet<Integer> p; public static void sieve(int n) { boolean[] prime = new boolean[n + 1]; for(int i = 2; i * i <= n; i++) { for(int j = 2 * i; j <= n; j += i) { prime[j] = true; } } for(int i = 2; i <= n; i++) if(!prime[i]) p.add(i); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
fc70a14e9c0ae5fc2ab157178eed6f20
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import java.util.InputMismatchException; import java.io.IOException; import java.util.Queue; import java.util.LinkedList; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Sparsh Sanchorawala */ 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); CNotAssigning solver = new CNotAssigning(); solver.solve(1, in, out); out.close(); } static class CNotAssigning { public void solve(int testNumber, InputReader s, PrintWriter w) { int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); Edge[] edges = new Edge[n - 1]; ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < n; i++) adj[i] = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { edges[i] = new Edge(s.nextInt() - 1, s.nextInt() - 1); adj[edges[i].u].add(i); adj[edges[i].v].add(i); } boolean valid = true; for (int i = 0; i < n; i++) if (adj[i].size() > 2) valid = false; if (!valid) { w.println(-1); continue; } int st = -1; for (int i = 0; i < n; i++) if (adj[i].size() == 1) st = i; Queue<Integer> q = new LinkedList<>(); int[] vis = new int[n]; Arrays.fill(vis, -1); vis[st] = 0; q.add(st); while (!q.isEmpty()) { int x = q.poll(); for (int i : adj[x]) { Edge e = edges[i]; int y = e.other(x); if (vis[y] == -1) { e.w = 2 + vis[x]; vis[y] = vis[x] ^ 1; q.add(y); } } } for (int i = 0; i < n - 1; i++) w.print(edges[i].w + " "); w.println(); } } class Edge { int u; int v; int w; Edge(int u, int v) { this.u = u; this.v = v; this.w = 0; } int other(int x) { return x == u ? v : u; } } } 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\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
046425023fe8b47d4ce835ca32cc71a3
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; /** * @author Naitik * */ public class Main { static FastReader sc=new FastReader(); static int dp[]; static boolean v[]; // static int mod=998244353;; static int mod=1000000007; static int max; static int bit[]; //static long fact[]; // static long A[]; static HashMap<Integer,Integer> map; //static StringBuffer sb=new StringBuffer(""); //static HashMap<Integer,Integer> map; static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) { // StringBuffer sb=new StringBuffer(""); int ttt=1; ttt =i(); outer :while (ttt-- > 0) { int n=i(); int A[]=new int[n]; int B[]=new int[n]; int C[]=new int[n+1]; ArrayList<Integer> D[]=new ArrayList[n+1]; for(int i=0;i<D.length;i++) { D[i]=new ArrayList<Integer>(); } for(int i=0;i<n-1;i++) { int a=i(); int b=i(); A[i]=a; B[i]=b; C[a]++; C[b]++; D[a].add(b); D[b].add(a); } int node=1; for(int i=1;i<=n;i++) { if(C[i]>2) { out.println("-1"); continue outer; } if(C[i]==1) { node=i; } } HashMap<Pair,Integer> map=new HashMap<Main.Pair, Integer>(); dfs(D, node, -1, map, 0); for(int i=0;i<n-1;i++) { out.print(map.get(new Pair(min(A[i],B[i]),max(A[i],B[i])))+" "); } out.println(); } //System.out.println(sb.toString()); out.close(); //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 } private static void dfs(ArrayList<Integer> [] A, int i, int par,HashMap<Pair,Integer> map,int f) { map.put(new Pair(min(par,i),max(par,i)), f==0?2:11); // System.out.println(par+" "+i); for(int child : A[i]) { if(child != par) { dfs(A, child, i,map,f^1); } } } static class Pair implements Comparable<Pair> { int x; int y; int z; Pair(int x,int y){ this.x=x; this.y=y; // this.z=z; } @Override public int compareTo(Pair o) { if(this.x>o.x) return 1; else if(this.x<o.x) return -1; else { if(this.y>o.y) return 1; else if(this.y<o.y) return -1; else return 0; } } public int hashCode() { final int temp = 14; int ans = 1; ans =x*31+y*13; return ans; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null) { return false; } if (this.getClass() != o.getClass()) { return false; } Pair other = (Pair)o; if (this.x != other.x || this.y!=other.y) { return false; } return true; } // /* FOR TREE MAP PAIR USE */ // public int compareTo(Pair o) { // if (x > o.x) { // return 1; // } // if (x < o.x) { // return -1; // } // if (y > o.y) { // return 1; // } // if (y < o.y) { // return -1; // } // return 0; // } } static int find(int A[],int a) { if(A[a]==a) return a; return A[a]=find(A, A[a]); } //static int find(int A[],int a) { // if(A[a]==a) // return a; // return find(A, A[a]); //} //FENWICK TREE static void update(int i, int x){ for(; i < bit.length; i += (i&-i)) bit[i] += x; } static int sum(int i){ int ans = 0; for(; i > 0; i -= (i&-i)) ans += bit[i]; return ans; } //END static void add(int v) { if(!map.containsKey(v)) { map.put(v, 1); } else { map.put(v, map.get(v)+1); } } static void remove(int v) { if(map.containsKey(v)) { map.put(v, map.get(v)-1); if(map.get(v)==0) map.remove(v); } } public static int upper(int A[],int k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { ans=mid; l=mid+1; } else { u=mid-1; } } return ans; } public static int lower(int A[],int k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { l=mid+1; } else { ans=mid; u=mid-1; } } return ans; } static int[] copy(int A[]) { int B[]=new int[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static long[] copy(long A[]) { long B[]=new long[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static long sum(int A[]) { long sum=0; for(int i : A) { sum+=i; } return sum; } static long sum(long A[]) { long sum=0; for(long i : A) { sum+=i; } return sum; } static void reverse(long A[]) { int n=A.length; long B[]=new long[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void reverse(int A[]) { int n=A.length; int B[]=new int[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void input(int A[],int B[]) { for(int i=0;i<A.length;i++) { A[i]=sc.nextInt(); B[i]=sc.nextInt(); } } static int[][] input(int n,int m){ int A[][]=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { A[i][j]=i(); } } return A; } static char[][] charinput(int n,int m){ char A[][]=new char[n][m]; for(int i=0;i<n;i++) { String s=s(); for(int j=0;j<m;j++) { A[i][j]=s.charAt(j); } } return A; } static int nextPowerOf2(int n) { n--; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n++; return n; } static int highestPowerof2(int x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } static long highestPowerof2(long x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } static int max(int A[]) { int max=Integer.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static int min(int A[]) { int min=Integer.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long max(long A[]) { long max=Long.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static long min(long A[]) { long min=Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long [] prefix(long A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] prefix(int A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] suffix(long A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static long [] suffix(int A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static void fill(int dp[]) { Arrays.fill(dp, -1); } static void fill(int dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(int dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(int dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static void fill(long dp[]) { Arrays.fill(dp, -1); } static void fill(long dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(long dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(long dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static int min(int a,int b) { return Math.min(a, b); } static int min(int a,int b,int c) { return Math.min(a, Math.min(b, c)); } static int min(int a,int b,int c,int d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static int max(int a,int b) { return Math.max(a, b); } static int max(int a,int b,int c) { return Math.max(a, Math.max(b, c)); } static int max(int a,int b,int c,int d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long min(long a,long b) { return Math.min(a, b); } static long min(long a,long b,long c) { return Math.min(a, Math.min(b, c)); } static long min(long a,long b,long c,long d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static long max(long a,long b) { return Math.max(a, b); } static long max(long a,long b,long c) { return Math.max(a, Math.max(b, c)); } static long max(long a,long b,long c,long d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long power(long x, long y, long p) { if(y==0) return 1; if(x==0) return 0; long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long power(long x, long y) { if(y==0) return 1; if(x==0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y = y >> 1; x = (x * x); } return res; } static void print(int A[]) { for(int i : A) { out.print(i+" "); } out.println(); } static void print(long A[]) { for(long i : A) { System.out.print(i+" "); } System.out.println(); } static long mod(long x) { return ((x%mod + mod)%mod); } static String reverse(String s) { StringBuffer p=new StringBuffer(s); p.reverse(); return p.toString(); } static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static void sort(long[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static String sort(String s) { Character ch[]=new Character[s.length()]; for(int i=0;i<s.length();i++) { ch[i]=s.charAt(i); } Arrays.sort(ch); StringBuffer st=new StringBuffer(""); for(int i=0;i<s.length();i++) { st.append(ch[i]); } return st.toString(); } static HashMap<Integer,Integer> hash(int A[]){ HashMap<Integer,Integer> map=new HashMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static HashMap<Long,Integer> hash(long A[]){ HashMap<Long,Integer> map=new HashMap<Long, Integer>(); for(long i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Integer,Integer> tree(int A[]){ TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Long,Integer> tree(long A[]){ TreeMap<Long,Integer> map=new TreeMap<Long, Integer>(); for(long i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static boolean prime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
aae33d669824b676148c428a22734add
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.lang.Math; public class Main { public static void dfs(int x, int y, int prime, Map<Integer, Map<Integer, Integer>> map, List<List<Integer>> list) { for (int i = 0; i < list.get(x).size(); i++) { if (list.get(x).get(i) == y) continue; addEdge(x, list.get(x).get(i), prime, map); addEdge(list.get(x).get(i), x, prime, map); if (prime == 3) dfs(list.get(x).get(i), x, 2, map, list); else dfs(list.get(x).get(i), x, 3, map, list); } } public static void addEdge(int v, int u, int color, Map<Integer, Map<Integer, Integer>> map) { if (!map.containsKey(v)) map.put(v, new HashMap<>()); map.get(v).put(u, color); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int step = in.nextInt(); for(; step > 0; step--) { boolean check = true; int n = in.nextInt(); List<List<Integer>> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(new ArrayList<>()); List<Integer> edges = new ArrayList<>(); Map<Integer, Map<Integer, Integer>> paint = new HashMap<>(); for (int i = 1; i < n; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; list.get(b).add(a); list.get(a).add(b); edges.add(b); edges.add(a); } for (List<Integer> i : list) if (i.size() > 2) { System.out.println(-1); check = false; break; } for (int j = 0; j < n; j++) if (list.get(j).size() == 1) { dfs(j, -1, 2, paint, list); break; } if (check) { for (int i = 0; i < edges.size(); i += 2) System.out.print(paint.get(edges.get(i + 1)).get(edges.get(i)) + " "); System.out.println(); } } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
6810a0e0cb9184666148aa39cdd0b682
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class c { public static void main(String[] args){ FastScanner sc = new FastScanner(); int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); ArrayList<ArrayList<Edge>> graph = new ArrayList<>(); for(int i=0; i<n; i++){ graph.add(new ArrayList<Edge>()); } for(int i=0; i<n-1; i++){ int u = sc.nextInt(); int v = sc.nextInt(); Edge e = new Edge(u-1, v-1, i+1); Edge e2 = new Edge(v-1, u-1, i+1); graph.get(u-1). add(e); graph.get(v-1).add(e2); } int edges[] = new int[n]; int indegree1count = 0; int indegree2count = 0; for(ArrayList<Edge> list : graph){ if(list.size() == 1){ indegree1count++; } else if(list.size() == 2){ indegree2count++; } } if(indegree1count == 2 && indegree1count+indegree2count==n){ for(int i=0; i<graph.size(); i++){ ArrayList<Edge> list = graph.get(i); if(list.size() == 1){ dfs(graph, edges, false, -1, i) ; } } for(int i=1; i<edges.length; i++){ System.out.print(edges[i] + " "); } System.out.println(); } else{ System.out.println(-1); } } } public static void dfs(ArrayList<ArrayList<Edge>> graph, int[] edges, boolean isprev2, int parent, int current){ for(Edge e : graph.get(current)){ if(e.v == parent){ continue; } edges[e.id] = isprev2 ? 5 : 2; dfs(graph, edges, !isprev2, current, e.v); } } } class Edge { int u; int v; int id; public Edge(int u, int v, int id) { this.u = u; this.v = v; this.id = id; } } class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
ef350b081b9fd841eeee9800f9fa5b26
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class C { /** * Template @author William Fiset, william.alexandre.fiset@gmail.com * */ static InputReader in = new InputReader(System.in); private static StringBuilder sb = new StringBuilder(); static PrintWriter out = new PrintWriter(System.out); private static void dfs(ArrayList<ArrayList<Integer>> adj, ArrayList<ArrayList<Edge>> edges, Edge e) { if (e.val == -1) { e.val = 2; } for (Edge x : edges.get(e.u)) { if (x.val == -1) { x.val = e.val == 2 ? 3 : 2; dfs(adj, edges, x); } } for (Edge x : edges.get(e.v)) { if (x.val == -1) { x.val = e.val == 2 ? 3 : 2; dfs(adj, edges, x); } } } static class InputReader { private static final int DEFAULT_BUFFER_SIZE = 1 << 16; private static final InputStream DEFAULT_STREAM = System.in; private static final int MAX_DECIMAL_PRECISION = 21; private int c; private byte[] buf; private int bufferSize, bufIndex, numBytesRead; private InputStream stream; private static final byte EOF = -1; private static final byte NEW_LINE = 10; private static final byte SPACE = 32; private static final byte DASH = 45; private static final byte DOT = 46; private char[] charBuffer; private static byte[] bytes = new byte[58]; private static int[] ints = new int[58]; private static char[] chars = new char[128]; static { char ch = ' '; int value = 0; byte _byte = 0; for (int i = 48; i < 58; i++) { bytes[i] = _byte++; } for (int i = 48; i < 58; i++) { ints[i] = value++; } for (int i = 32; i < 128; i++) { chars[i] = ch++; } } private static final double[][] doubles = { {0.0d, 0.00d, 0.000d, 0.0000d, 0.00000d, 0.000000d, 0.0000000d, 0.00000000d, 0.000000000d, 0.0000000000d, 0.00000000000d, 0.000000000000d, 0.0000000000000d, 0.00000000000000d, 0.000000000000000d, 0.0000000000000000d, 0.00000000000000000d, 0.000000000000000000d, 0.0000000000000000000d, 0.00000000000000000000d, 0.000000000000000000000d}, {0.1d, 0.01d, 0.001d, 0.0001d, 0.00001d, 0.000001d, 0.0000001d, 0.00000001d, 0.000000001d, 0.0000000001d, 0.00000000001d, 0.000000000001d, 0.0000000000001d, 0.00000000000001d, 0.000000000000001d, 0.0000000000000001d, 0.00000000000000001d, 0.000000000000000001d, 0.0000000000000000001d, 0.00000000000000000001d, 0.000000000000000000001d}, {0.2d, 0.02d, 0.002d, 0.0002d, 0.00002d, 0.000002d, 0.0000002d, 0.00000002d, 0.000000002d, 0.0000000002d, 0.00000000002d, 0.000000000002d, 0.0000000000002d, 0.00000000000002d, 0.000000000000002d, 0.0000000000000002d, 0.00000000000000002d, 0.000000000000000002d, 0.0000000000000000002d, 0.00000000000000000002d, 0.000000000000000000002d}, {0.3d, 0.03d, 0.003d, 0.0003d, 0.00003d, 0.000003d, 0.0000003d, 0.00000003d, 0.000000003d, 0.0000000003d, 0.00000000003d, 0.000000000003d, 0.0000000000003d, 0.00000000000003d, 0.000000000000003d, 0.0000000000000003d, 0.00000000000000003d, 0.000000000000000003d, 0.0000000000000000003d, 0.00000000000000000003d, 0.000000000000000000003d}, {0.4d, 0.04d, 0.004d, 0.0004d, 0.00004d, 0.000004d, 0.0000004d, 0.00000004d, 0.000000004d, 0.0000000004d, 0.00000000004d, 0.000000000004d, 0.0000000000004d, 0.00000000000004d, 0.000000000000004d, 0.0000000000000004d, 0.00000000000000004d, 0.000000000000000004d, 0.0000000000000000004d, 0.00000000000000000004d, 0.000000000000000000004d}, {0.5d, 0.05d, 0.005d, 0.0005d, 0.00005d, 0.000005d, 0.0000005d, 0.00000005d, 0.000000005d, 0.0000000005d, 0.00000000005d, 0.000000000005d, 0.0000000000005d, 0.00000000000005d, 0.000000000000005d, 0.0000000000000005d, 0.00000000000000005d, 0.000000000000000005d, 0.0000000000000000005d, 0.00000000000000000005d, 0.000000000000000000005d}, {0.6d, 0.06d, 0.006d, 0.0006d, 0.00006d, 0.000006d, 0.0000006d, 0.00000006d, 0.000000006d, 0.0000000006d, 0.00000000006d, 0.000000000006d, 0.0000000000006d, 0.00000000000006d, 0.000000000000006d, 0.0000000000000006d, 0.00000000000000006d, 0.000000000000000006d, 0.0000000000000000006d, 0.00000000000000000006d, 0.000000000000000000006d}, {0.7d, 0.07d, 0.007d, 0.0007d, 0.00007d, 0.000007d, 0.0000007d, 0.00000007d, 0.000000007d, 0.0000000007d, 0.00000000007d, 0.000000000007d, 0.0000000000007d, 0.00000000000007d, 0.000000000000007d, 0.0000000000000007d, 0.00000000000000007d, 0.000000000000000007d, 0.0000000000000000007d, 0.00000000000000000007d, 0.000000000000000000007d}, {0.8d, 0.08d, 0.008d, 0.0008d, 0.00008d, 0.000008d, 0.0000008d, 0.00000008d, 0.000000008d, 0.0000000008d, 0.00000000008d, 0.000000000008d, 0.0000000000008d, 0.00000000000008d, 0.000000000000008d, 0.0000000000000008d, 0.00000000000000008d, 0.000000000000000008d, 0.0000000000000000008d, 0.00000000000000000008d, 0.000000000000000000008d}, {0.9d, 0.09d, 0.009d, 0.0009d, 0.00009d, 0.000009d, 0.0000009d, 0.00000009d, 0.000000009d, 0.0000000009d, 0.00000000009d, 0.000000000009d, 0.0000000000009d, 0.00000000000009d, 0.000000000000009d, 0.0000000000000009d, 0.00000000000000009d, 0.000000000000000009d, 0.0000000000000000009d, 0.00000000000000000009d, 0.000000000000000000009d} }; public InputReader() { this(DEFAULT_STREAM, DEFAULT_BUFFER_SIZE); } public InputReader(int bufferSize) { this(DEFAULT_STREAM, bufferSize); } public InputReader(InputStream stream) { this(stream, DEFAULT_BUFFER_SIZE); } public InputReader(InputStream stream, int bufferSize) { if (stream == null || bufferSize <= 0) { throw new IllegalArgumentException(); } buf = new byte[bufferSize]; charBuffer = new char[128]; this.bufferSize = bufferSize; this.stream = stream; } private byte read() throws IOException { if (numBytesRead == EOF) { throw new IOException(); } if (bufIndex >= numBytesRead) { bufIndex = 0; numBytesRead = stream.read(buf); if (numBytesRead == EOF) { return EOF; } } return buf[bufIndex++]; } private void doubleCharBufferSize() { char[] newBuffer = new char[charBuffer.length << 1]; for (int i = 0; i < charBuffer.length; i++) { newBuffer[i] = charBuffer[i]; } charBuffer = newBuffer; } private int readJunk(int token) throws IOException { if (numBytesRead == EOF) { return EOF; } do { while (bufIndex < numBytesRead) { if (buf[bufIndex] > token) { return 0; } bufIndex++; } numBytesRead = stream.read(buf); if (numBytesRead == EOF) { return EOF; } bufIndex = 0; } while (true); } public byte nextByte() throws IOException { return (byte) nextInt(); } public int nextInt() throws IOException { if (readJunk(DASH - 1) == EOF) { throw new IOException(); } int sgn = 1, res = 0; c = buf[bufIndex]; if (c == DASH) { sgn = -1; bufIndex++; } do { while (bufIndex < numBytesRead) { if (buf[bufIndex] > SPACE) { res = (res << 3) + (res << 1); res += ints[buf[bufIndex++]]; } else { bufIndex++; return res * sgn; } } numBytesRead = stream.read(buf); if (numBytesRead == EOF) { return res * sgn; } bufIndex = 0; } while (true); } public int[] nextIntArray(int n) throws IOException { int[] ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = nextInt(); } return ar; } public void close() throws IOException { stream.close(); } public long nextLong() throws IOException { if (readJunk(DASH - 1) == EOF) { throw new IOException(); } int sgn = 1; long res = 0L; c = buf[bufIndex]; if (c == DASH) { sgn = -1; bufIndex++; } do { while (bufIndex < numBytesRead) { if (buf[bufIndex] > SPACE) { res = (res << 3) + (res << 1); res += ints[buf[bufIndex++]]; } else { bufIndex++; return res * sgn; } } numBytesRead = stream.read(buf); if (numBytesRead == EOF) { return res * sgn; } bufIndex = 0; } while (true); } public String nextString() throws IOException { if (numBytesRead == EOF) { return null; } if (readJunk(SPACE) == EOF) { return null; } for (int i = 0;;) { while (bufIndex < numBytesRead) { if (buf[bufIndex] > SPACE) { if (i == charBuffer.length) { doubleCharBufferSize(); } charBuffer[i++] = (char) buf[bufIndex++]; } else { bufIndex++; return new String(charBuffer, 0, i); } } // Reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) { return new String(charBuffer, 0, i); } bufIndex = 0; } } } public static void main(String args[]) throws Exception { int t = in.nextInt(); while (t-- != 0) { solve(); } out.print(sb.toString()); out.close(); } static void solve() throws IOException { int n, l, k; n = in.nextInt(); ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); ArrayList<ArrayList<Edge>> edges = new ArrayList<>(); for (int i = 0; i < n; i++) { adj.add(new ArrayList<>()); edges.add(new ArrayList<>()); } Edge[] hehe = new Edge[n - 1]; for (int i = 0; i < n - 1; i++) { int u, v; u = in.nextInt() - 1; v = in.nextInt() - 1; Edge e = new Edge(u, v); adj.get(u).add(v); adj.get(v).add(u); edges.get(u).add(e); edges.get(v).add(e); hehe[i] = e; } boolean can = true; for (int i = 0; i < n; i++) { if (adj.get(i).size() > 2) { can = false; } } if (!can) { sb.append(-1).append("\n"); return; } else { dfs(adj, edges, edges.get(0).get(0)); for (Edge e : hehe) { sb.append(e.val).append(" "); } sb.append("\n"); } } static class Edge { int u, v; int val; public Edge(int uu, int vv) { this.val = -1; u = uu; v = vv; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
3d7e565d5bff675f5f70b06dd92b844e
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Iterator; public class Main { public Main() { } public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Main.InputReader in = new Main.InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Main.TaskC solver = new Main.TaskC(); int testCount = Integer.parseInt(in.next()); for(int i = 1; i <= testCount; ++i) { solver.solve(i, in, out); } out.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar; private int snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (this.snumChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.snumChars) { this.curChar = 0; try { this.snumChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.snumChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for(c = this.read(); this.isSpaceChar(c); c = this.read()) { } int sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; do { res *= 10; res += c - 48; c = this.read(); } while(!this.isSpaceChar(c)); return res * sgn; } public String readString() { int c; for(c = this.read(); this.isSpaceChar(c); c = this.read()) { } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = this.read(); } while(!this.isSpaceChar(c)); return res.toString(); } public String next() { return this.readString(); } public boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } static class TaskC { static int[] ans; static boolean solExists; static ArrayList<Main.TaskC.node>[] tree; TaskC() { } public void solve(int testNumber, Main.InputReader in, PrintWriter out) { solExists = true; int n = in.nextInt(); ans = new int[n]; tree = new ArrayList[n + 1]; int leafNode; for(leafNode = 0; leafNode < n + 1; ++leafNode) { tree[leafNode] = new ArrayList(); } int i; for(leafNode = 0; leafNode < n - 1; ++leafNode) { i = in.nextInt(); int v = in.nextInt(); tree[i].add(new Main.TaskC.node(v, leafNode)); tree[v].add(new Main.TaskC.node(i, leafNode)); } leafNode = -1; for(i = 1; i <= n; ++i) { if (tree[i].size() == 1) { leafNode = i; break; } } dfs(leafNode, leafNode, 2); if (solExists) { for(i = 0; i < n - 1; ++i) { out.print(ans[i] + " "); } out.println(); } else { out.println("-1"); } } static void dfs(int curr, int parent, int prevValue) { int ct = 0; Iterator var4 = tree[curr].iterator(); while(var4.hasNext()) { Main.TaskC.node n = (Main.TaskC.node)var4.next(); if (n.v != parent) { int currAns = prevValue == 2 ? 3 : 2; ans[n.edgeNo] = currAns; dfs(n.v, curr, currAns); ++ct; } } if (ct > 1) { solExists = false; } } static class node { int v; int edgeNo; node(int v, int edgeNo) { this.v = v; this.edgeNo = edgeNo; } } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
ae64213a1ef01d5d97ab597be208482e
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.StringTokenizer; public class Main { static FastReader fr; static int arrForIndexSort[]; static Integer map1[]; static Integer map2[]; static int globalVal; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair{ int first; int second; Pair(int first, int second){ this.first = first; this.second = second; } @Override public boolean equals(Object b) { Pair a = (Pair)b; if(this.first == a.first && this.second==a.second) { return true; } return false; } } class PairSorter implements Comparator<Main.Pair>{ public int compare(Pair a, Pair b) { if(a.first!=b.first) { return a.first-b.first; } return a.second-b.second; } } static class DoublePair{ double first; double second; DoublePair(double first, double second){ this.first = first; this.second = second; } @Override public boolean equals(Object b) { Pair a = (Pair)b; if(this.first == a.first && this.second==a.second) { return true; } return false; } } class DoublePairSorter implements Comparator<Main.DoublePair>{ public int compare(DoublePair a, DoublePair b) { if(a.second>b.second) { return 1; } else if(a.second<b.second) { return -1; } return 0; } } class IndexSorter implements Comparator<Integer>{ public int compare(Integer a, Integer b) { //desc if(arrForIndexSort[b]==arrForIndexSort[a]) { return b-a; } return arrForIndexSort[b]-arrForIndexSort[a]; } } class ListSorter implements Comparator<List>{ public int compare(List a, List b) { return b.size()-a.size(); } } static class DisjointSet{ int[] dsu; public DisjointSet(int n) { makeSet(n); } public void makeSet(int n) { dsu = new int[n+1]; //*** 1 Based indexing *** for(int i=1;i<=n;i++) { dsu[i] = -1; } } public int find(int i) { while(dsu[i] > 0) { i = dsu[i]; } return i; } public void union(int i, int j) { int iRep = find(i); int jRep = find(j); if(iRep == jRep) { return; } if(dsu[iRep]>dsu[jRep]) { dsu[jRep] += dsu[iRep]; dsu[iRep] = jRep; } else { dsu[iRep] += dsu[jRep]; dsu[jRep] = iRep; } } } public static void main(String[] args) { fr = new FastReader(); int T = 1; T = fr.nextInt(); int t1 = T; while (T-- > 0) { solve(t1-T); } } /* Thinks to remember * Keep it Simple (Golden Rule) * Think Reverse * Dont get stuck on one approach * Check corner case * On error, check->edge case, implementation and question, which one to choose when two values are equal for greedy */ public static void solve(int testcase) { int n = fr.nextInt(); int[] degree = new int[n+1]; ArrayList<Pair> adjacencyList[] = new ArrayList[n+1]; Pair[] edgeList = new Pair[n-1]; for(int i=0;i<=n;i++) { adjacencyList[i] = new ArrayList<Pair>(); } for(int i=0;i<n-1;i++) { int a = fr.nextInt(); int b = fr.nextInt(); degree[a]++; degree[b]++; adjacencyList[a].add(new Pair(b, -1)); adjacencyList[b].add(new Pair(a, -1)); edgeList[i] = new Pair(a,b); } int first = -1; boolean flag = false; for(int i=1;i<=n;i++) { if(degree[i]==1) { first = i; } if(degree[i]>2) { flag = true; } } if(flag || first == -1) { System.out.println(-1); } else { boolean isVisited[] = new boolean[n+1]; globalVal = 2; DFS(first, adjacencyList, isVisited); StringBuilder sb = new StringBuilder(); for(int i=0;i<n-1;i++) { int a = edgeList[i].first; int b = edgeList[i].second; int val = 0; if(adjacencyList[a].get(0).first == b) { val = adjacencyList[a].get(0).second; }else { val = adjacencyList[a].get(1).second; } sb.append(val).append(" "); } System.out.println(sb.toString()); } } public static void DFS(int node, ArrayList<Pair> adjacencyList[], boolean[] isVisited) { isVisited[node] = true; for(Pair pair: adjacencyList[node]) { int a = pair.first; if(!isVisited[a]) { pair.second = globalVal; if(adjacencyList[a].get(0).first == node) { adjacencyList[a].get(0).second = globalVal; }else { adjacencyList[a].get(1).second = globalVal; } if(globalVal == 2) { globalVal = 3; } else { globalVal = 2; } DFS(a, adjacencyList, isVisited); } } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
c029c10bd2260eb45b9c6c81edafb630
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Comparator; import java.util.StringTokenizer; public class C { public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); FastPrintStream out = new FastPrintStream(System.out); int t = sc.nextInt(); for (int i = 0; i < t; i++) { int n = sc.nextInt(); ArrayList<Edge>[] e = new ArrayList[n]; for (int j = 0; j < n; j++) { e[j] = new ArrayList<>(); } for (int j = 0; j < n - 1; j++) { int u = sc.nextInt() - 1, v = sc.nextInt() - 1; e[u].add(new Edge(v, j)); e[v].add(new Edge(u, j)); } solve(n, e, out); } out.flush(); } private static void solve(int n, ArrayList<Edge>[] e, FastPrintStream out) { boolean[] color = new boolean[n - 1]; if (!color(0, false, e, -1, color)) { out.println(-1); return; } for (int i = 0; i < n - 1; i++) { out.print(color[i] ? "2 " : "5 "); } out.println(); } private static boolean color(int v, boolean color, ArrayList<Edge>[] e, int p, boolean[] colors) { if (e[v].size() > 2) { return false; } if (v == 0) { for (Edge edge : e[0]) { colors[edge.index] = color; if (!color(edge.to, !color, e, 0, colors)) { return false; } color = !color; } return true; } for (Edge edge : e[v]) { if (edge.to == p) { continue; } colors[edge.index] = color; if (!color(edge.to, !color, e, v, colors)) { return false; } } return true; } static class Edge { private int to; private int index; Edge(int to, int index) { this.to = to; this.index = index; } } static int[] readIntArray(int n, FastScanner sc) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } return a; } static int[] sorted(int[] array) { ArrayList<Integer> list = new ArrayList<>(array.length); for (int val : array) { list.add(val); } list.sort(Comparator.naturalOrder()); return list.stream().mapToInt(val -> val).toArray(); } static int[] sortedReverse(int[] array) { ArrayList<Integer> list = new ArrayList<>(array.length); for (int val : array) { list.add(val); } list.sort(Comparator.reverseOrder()); return list.stream().mapToInt(val -> val).toArray(); } static long[] sort(long[] array) { ArrayList<Long> list = new ArrayList<>(array.length); for (long val : array) { list.add(val); } list.sort(Comparator.naturalOrder()); return list.stream().mapToLong(val -> val).toArray(); } static long[] sortedReverse(long[] array) { ArrayList<Long> list = new ArrayList<>(array.length); for (long val : array) { list.add(val); } list.sort(Comparator.reverseOrder()); return list.stream().mapToLong(val -> val).toArray(); } private static class FastPrintStream { private final BufferedWriter writer; public FastPrintStream(PrintStream out) { writer = new BufferedWriter(new OutputStreamWriter(out)); } public void print(char c) { try { writer.write(Character.toString(c)); } catch (IOException e) { e.printStackTrace(); } } public void print(int val) { try { writer.write(Integer.toString(val)); } catch (IOException e) { e.printStackTrace(); } } public void print(long val) { try { writer.write(Long.toString(val)); } catch (IOException e) { e.printStackTrace(); } } public void print(double val) { try { writer.write(Double.toString(val)); } catch (IOException e) { e.printStackTrace(); } } public void print(String val) { try { writer.write(val); } catch (IOException e) { e.printStackTrace(); } } public void println(char c) { print(c + "\n"); } public void println(int val) { print(val + "\n"); } public void println(long val) { print(val + "\n"); } public void println(double val) { print(val + "\n"); } public void println(String str) { print(str + "\n"); } public void println() { print("\n"); } public void flush() { try { writer.flush(); } catch (IOException e) { e.printStackTrace(); } } } private static class FastScanner { private final BufferedReader br; private StringTokenizer st; public FastScanner(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } 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 byte nextByte() { return Byte.parseByte(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
5d0fe923ddedf55941bc8e1fce808948
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class problemC { public static void main(String[] args)throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); for(int i=0; i<t; i++) { int n = Integer.parseInt(br.readLine()); ArrayList<Integer>[] edges = new ArrayList[n]; for(int j=0; j<n; j++) edges[j] = new ArrayList<>(); for(int j=0; j<n-1; j++) { StringTokenizer st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken())-1; int b = Integer.parseInt(st.nextToken())-1; edges[a].add(b); edges[b].add(a); edges[a].add(j); edges[b].add(j); } boolean work = true; for(int j=0; j<n; j++) if(edges[j].size()>=6) { work = false; break; } if(!work) { out.write(-1+"\n"); } else { int[] ans = new int[n-1]; LinkedList<Integer> list = new LinkedList<>(); for(int j=0; j<n; j++) { if(edges[j].size()==2) { list.add(j); break; } } int last = 3; while(!list.isEmpty()) { int curr = list.removeFirst(); ArrayList<Integer> al = edges[curr]; int s = al.size(); for(int j=0; j<s; j+=2) { int tar = al.get(j); int index = al.get(j+1); if(ans[index]==0) { if(last==3) { ans[index]= 2; last = 2; } else { ans[index]= 3; last = 3; } list.add(tar); } } } for(int j=0; j<n-1; j++) out.write(ans[j]+" "); out.write("\n"); } } out.flush(); out.close(); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
1dddd0e4a9590ac18d339cfa9b6c57b2
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; ////*************************************************************************** /* public class E_Gardener_and_Tree implements Runnable{ public static void main(String[] args) throws Exception { new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start(); } public void run(){ WRITE YOUR CODE HERE!!!! JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!! } } */ /////************************************************************************** public class C_Not_Assigning{ public static void main(String[] args) { FastScanner s= new FastScanner(); //PrintWriter out=new PrintWriter(System.out); //end of program //out.println(answer); //out.close(); StringBuilder res = new StringBuilder(); int t=s.nextInt(); int p=0; while(p<t){ int n=s.nextInt(); ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(n+4); for(int i=0;i<=n;i++){ ArrayList<Integer> obj3 = new ArrayList<Integer>(); list.add(obj3); } HashMap<String,Integer> map = new HashMap<String,Integer>(); for(int i=0;i<n-1;i++){ int a=s.nextInt(); int b=s.nextInt(); list.get(a).add(b); list.get(b).add(a); String str=a+"*"+b; map.put(str,i); String str2=b+"*"+a; map.put(str2,i); } int leaf=-1; for(int i=1;i<=n;i++){ if(list.get(i).size()==1){ leaf=i; break; } } long child[]= new long[n+1]; dfs1(list,child,leaf,0); long max=0; for(int i=1;i<=n;i++){ max=Math.max(max,child[i]); } if(max>1){ res.append("-1 \n"); } else{ long ans[]= new long[n-1]; dfs2(list,map,leaf,0,2,ans); for(int i=0;i<n-1;i++){ res.append(ans[i]+" "); } res.append(" \n"); } p++; } System.out.println(res); } private static void dfs2(ArrayList<ArrayList<Integer>> list, HashMap<String, Integer> map, int i, int parent, int number, long[] ans) { for(int j=0;j<list.get(i).size();j++){ int num=list.get(i).get(j); if(num!=parent){ String str=i+"*"+num; int index=map.get(str); ans[index]=number; int number2=0; if(number==2){ number2=5; } else{ number2=2; } dfs2(list,map,num,i,number2,ans); } } } private static void dfs1(ArrayList<ArrayList<Integer>> list, long[] child, int i, int parent) { int count=0; for(int j=0;j<list.get(i).size();j++){ int num=list.get(i).get(j); if(num!=parent){ dfs1(list,child,num,i); count++; } } child[i]=count; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } static long modpower(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // SIMPLE POWER FUNCTION=> static long power(long x, long y) { long res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = res * x; // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 } return res; } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
3f6c5077a1bbac7515b3afd9cfae6c7a
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CF1627C { static final long FAC = (long) 1e9; static private long f(int x, int y) { return FAC * x + y; } public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String[] buffer; buffer = reader.readLine().split(" "); int T = Integer.parseInt(buffer[0]); while (T-- > 0) { buffer = reader.readLine().split(" "); int n = Integer.parseInt(buffer[0]); boolean[] vis = new boolean[n]; int[] deg = new int[n]; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) { adj.add(new ArrayList<>()); } Map<Long, Integer> edges = new HashMap<>(); for (int i = 1; i < n; i++) { buffer = reader.readLine().split(" "); int x = Integer.parseInt(buffer[0]) - 1; int y = Integer.parseInt(buffer[1]) - 1; deg[x]++; deg[y]++; adj.get(x).add(y); adj.get(y).add(x); edges.put(f(x, y), i - 1); edges.put(f(y, x), i - 1); } int cur = 0, root = 0; boolean impossible = false; for (int i = 0; i < n; i++) { if (deg[i] == 1) { root = i; } if (deg[i] > 2) { impossible = true; break; } } if (impossible) { System.out.println(-1); continue; } int[] vals = new int[n - 1]; int[] primes = new int[n]; primes[root] = 2; List<Integer> queue = new ArrayList<>(); queue.add(root); while (cur != queue.size()) { int x = queue.get(cur++); vis[x] = true; for (int y: adj.get(x)) { if (!vis[y]) { queue.add(y); vals[edges.get(f(x, y))] = primes[x]; primes[y] = (primes[x] == 2) ? 5 : 2; } } } StringBuilder ans = new StringBuilder(); for (int i = 0; i < n - 1; i++) { ans.append(vals[i]); ans.append(" "); } System.out.println(ans); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
7a43ffae909b71fb8d9a6e21e0b28407
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); //int a = 1; int t; t = in.nextInt(); //t = 1; while (t > 0) { //out.print("Case #"+(a++)+": "); solver.call(in,out); t--; } out.close(); } static class TaskA { Map<Integer, ArrayList<Integer>> ans; Map<Integer,Boolean> visited; Map<Integer, List<Integer>> map; public void call(InputReader in, PrintWriter out) { int n = in.nextInt(); answer[] arr = new answer[n]; visited = new HashMap<>(); ans = new HashMap<>(); int u, v; map = new HashMap<>(); for (int i = 0; i < n - 1; i++) { arr[i] = new answer(in.nextInt(), in.nextInt()); u = arr[i].a; v = arr[i].b; map.putIfAbsent(u, new ArrayList<>()); map.get(u).add(v); map.putIfAbsent(v, new ArrayList<>()); map.get(v).add(u); } int a = 0; for(Integer i : map.keySet()){ if(map.get(i).size() > 2){ out.println(-1); return; } if(map.get(i).size()==1){ a = i; } } dfs(a, -1, 0); int[] ans1 = new int[n - 1]; for(int i = 0; i < n-1; i++){ u = arr[i].a; v = arr[i].b; if(ans.getOrDefault(u, null)!=null && ans.get(u).get(0)==v){ if(ans.get(u).get(1)==0){ ans1[i] = 2; } else{ ans1[i] = 5; } } else{ if(ans.get(v).get(1)==0){ ans1[i] = 2; } else{ ans1[i] = 5; } } } for(Integer i : ans1){ out.print(i+" "); } out.println(); } public void dfs(int child, int par, int c){ if(par!=-1){ ans.putIfAbsent(par, new ArrayList<>()); ans.get(par).add(child); ans.get(par).add(c); } visited.put(child, true); for(Integer i : map.get(child)){ if(!visited.getOrDefault(i, false)){ dfs(i, child, c^1); } } } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static class answer implements Comparable<answer>{ int a, b; public answer(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(answer o) { return Integer.compare(this.a, o.a); } } static class answer1 implements Comparable<answer1>{ int a, b, c; public answer1(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public int compareTo(answer1 o) { return (o.a - this.a); } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (Long i:a) l.add(i); l.sort(Collections.reverseOrder()); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static final Random random=new Random(); static void shuffleSort(int[] a) { int n = a.length; for (int i=0; i<n; i++) { int oi= random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
8acce1aa620685659673b396b9f6989c
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
//package codeforces.round766div2; import java.io.*; import java.util.*; import static java.lang.Math.*; public class C { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); solve(in.nextInt()); //solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static int n; static List<int[]>[] adj; static int[] ans; static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { n = in.nextInt(); adj = new List[n + 1]; for(int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } ans = new int[n - 1]; for(int i = 0; i < n - 1; i++) { int u = in.nextInt(), v = in.nextInt(); adj[u].add(new int[]{v, i}); adj[v].add(new int[]{u, i}); } if(adj[1].size() > 2) out.println(-1); else { boolean can = false; if(adj[1].size() == 1) { ans[adj[1].get(0)[1]] = 2; if(dfs(adj[1].get(0)[0], 1, 2)) { can = true; } } else { ans[adj[1].get(0)[1]] = 2; ans[adj[1].get(1)[1]] = 3; if(dfs(adj[1].get(0)[0] ,1, 2) && dfs(adj[1].get(1)[0], 1, 3)) { can = true; } } if(can) { for(int v : ans) out.print(v + " "); out.println(); } else out.println(-1); } } out.close(); } static boolean dfs(int curr, int par, int prev) { if(adj[curr].size() - 1 > 1) return false; for(int[] next : adj[curr]) { if(next[0] == par) continue; ans[next[1]] = prev == 2 ? 3 : 2; if(!dfs(next[0], curr, prev == 2 ? 3 : 2)) { return false; } } return true; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<Integer>[] readGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
37f5b64e9b27e52da99193d4477e96b4
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.util.*; import java.io.*; public class s1 { public static FastScanner scan; public static PrintWriter out; public static void main(String[] args) throws Exception { scan=new FastScanner(System.in); out=new PrintWriter(System.out); // int T=1; int T=scan.nextInt(); while(T-->0) { int n=scan.nextInt(); ArrayList<ArrayList<Integer>> graph=new ArrayList<>(); for(int i=0;i<n;i++) graph.add(new ArrayList<>()); HashMap<Long,Integer> which=new HashMap<>(); long MX=100_000; boolean res=true; for(int i=0;i<n-1;i++) { int a=scan.nextInt()-1,b=scan.nextInt()-1; graph.get(a).add(b); graph.get(b).add(a); which.put(a*MX+b,i); which.put(b*MX+a,i); if(graph.get(a).size()>2) res=false; if(graph.get(b).size()>2) res=false; } int start=-1; for(int i=0;i<n;i++) if(graph.get(i).size()==1) start=i; int[] num=new int[n-1]; ArrayDeque<Integer> que=new ArrayDeque<>(),par=new ArrayDeque<>(); que.add(start); par.add(-1); int color=2; while(que.size()>0) { int size=que.size(); while(size-->0) { int cur=que.poll(); int curpar=par.poll(); ArrayList<Integer> neigh=graph.get(cur); for(int next:neigh) { if(next==curpar) continue; int edge=which.get(cur*MX+next); num[edge]=color; que.add(next); par.add(cur); } } if(color==2) color=3; else color=2; } if(!res) out.println(-1); else { for(int i=0;i<n-1;i++) out.print(num[i]+" "); out.println(); } } out.close(); } } class Triple { Triple(int a,int b,int c) { this.a=a; this.b=b; this.c=c; } int a,b,c; } class Pair { int a,b; Pair(int a,int b) { this.a=a; this.b=b; } } class FastScanner { private InputStream stream; private byte[] buf=new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream=stream; } 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++]; } boolean isSpaceChar(int c) { return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1; } boolean isEndline(int c) { return c=='\n'||c=='\r'||c==-1; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } 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(); } String nextLine() { int c=read(); while(isEndline(c)) c=read(); StringBuilder res=new StringBuilder(); do { res.appendCodePoint(c); c=read(); } while(!isEndline(c)); return res.toString(); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
4832a47e90d54d6d0150443d142edd67
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int mod = 1000_000_007; static long mod1 = 998244353; static boolean memory = true; static FastScanner f; static PrintWriter pw; static double eps = 1e-6; static int oo = (int) 1e9; static boolean fileIO = false; static int maxN = (int)6e5; static int n; static ArrayList<Integer>[] adj; public static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; return this.x == other.x && this.y == other.y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } } public static void solve() throws Exception { n = f.ni(); adj = new ArrayList[n + 1]; for (int i = 0; i <= n; ++i) adj[i] = new ArrayList<>(); int[] d = new int[n + 1]; Pair[] edges = new Pair[n - 1]; for (int i = 0; i + 1 < n; ++i) { int u = f.ni(); int v = f.ni(); adj[u].add(v); adj[v].add(u); ++d[u]; ++d[v]; edges[i] = new Pair(u , v); } boolean ok = true; int curr = -1; for (int i = 1; i <= n; ++i) { ok &= d[i] <= 2; if (d[i] == 1) curr = i; } if (!ok) { pn(-1); return; } boolean[] vis = new boolean[n + 1]; int[] pos = new int[n + 1]; ArrayList<Integer> dia = new ArrayList<>(); int j = 1; while (dia.size() < n) { dia.add(curr); pos[curr] = j++; vis[curr] = true; boolean found = true; for (Integer u : adj[curr]) { if (vis[u]) continue; curr = u; found = true; break; } if (!found) break; } for (int i = 0; i + 1 < n; ++i) { int u = edges[i].x; int v = edges[i].y; if (pos[u] > pos[v]) { int t = u; u = v; v = t; } if (pos[u] % 2 == 0) p(5 + " "); else p(2 + " "); } pn(""); } public static void main(String[] args) throws Exception { if (memory) new Thread(null, new Runnable() { public void run() { try { Main.run(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }, "", 1 << 28).start(); else { Main.run(); } } static void run() throws Exception { if (fileIO) { f = new FastScanner(""); File file = new File("!out.txt"); pw = new PrintWriter(file); } else { f = new FastScanner(); pw = new PrintWriter(System.out); } int t = f.ni(); while (t --> 0) { solve(); } pw.flush(); pw.close(); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String str) throws Exception { try { br = new BufferedReader(new FileReader("!a.txt")); } catch (Exception e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int ni() throws IOException { return Integer.parseInt(next()); } public long nl() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nd() throws IOException { return Double.parseDouble(next()); } } public static void pn(Object... o) { for (int i = 0; i < o.length; ++i) pw.print(o[i] + (i + 1 < o.length ? " " : "\n")); } public static void p(Object... o) { for (int i = 0; i < o.length; ++i) pw.print(o[i] + (i + 1 < o.length ? " " : "")); } public static void pni(Object... o) { for (Object obj : o) pw.print(obj + " "); pw.println(); pw.flush(); } public static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; ++i) a[i] = l.get(i); } public static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; ++i) a[i] = l.get(i); } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
6bbac4a1a0a97459e5590fc3036abb13
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.*; import java.util.*; /* polyakoff */ public class Main { static FastReader in; static PrintWriter out; static Random rand = new Random(); static final int oo = (int) 2e9 + 10; static final long OO = (long) 2e18 + 10; static final int MOD = 998244353; static final int LOGN = 20; static class To { int v, i; To(int v, int i) { this.v = v; this.i = i; } } static void solve() { int n = in.nextInt(); ArrayList<To>[] g = new ArrayList[n]; Arrays.setAll(g, i -> new ArrayList<>()); for (int i = 0; i < n - 1; i++) { int v = in.nextInt() - 1; int u = in.nextInt() - 1; g[v].add(new To(u, i)); g[u].add(new To(v, i)); } int root = -1; for (int i = 0; i < n; i++) { if (g[i].size() == 1 && root == -1) { root = i; } else if (g[i].size() > 2) { out.println(-1); return; } } int[] ans = new int[n - 1]; int v = root; for (int i = 0; i < n - 1; i++) { To to = ans[g[v].get(0).i] == 0 ? g[v].get(0) : g[v].get(1); ans[to.i] = i % 2 == 0 ? 2 : 3; v = to.v; } for (int i = 0; i < n - 1; i++) { out.print(ans[i] + " "); } out.println(); } public static void main(String[] args) { in = new FastReader(); out = new PrintWriter(System.out); int t = 1; t = in.nextInt(); while (t-- > 0) { solve(); } out.flush(); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader() { this(System.in); } FastReader(String file) throws FileNotFoundException { this(new FileInputStream(file)); } FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String line; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
fa32aef5f76ea1ea4bfedf6264f05615
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.lang.*; import java.util.*; import java.io.*; import java.math.*; public class Main { static void deal(int n,int[][] arr) { ArrayList<int[]>[] link = new ArrayList[n]; for(int i=0;i<n;i++) { link[i] = new ArrayList<>(); } // System.out.println(Arrays.deepToString(arr)); for(int i=0;i<n-1;i++) { link[arr[i][0]].add(new int[]{arr[i][1],i}); link[arr[i][1]].add(new int[]{arr[i][0],i}); } for(int i=0;i<n;i++) { if(link[i].size()>2) { out.println(-1); return; } } int[] res = new int[n-1]; int[] p = link[0].get(0); res[p[1]] = 2; LinkedList<int[]> q = new LinkedList<>(); q.addLast(new int[]{0,2}); q.addLast(new int[]{p[0],2}); while(q.size()>0) { p = q.pollFirst(); for(int[] next:link[p[0]]) { if(res[next[1]] !=0) continue; res[next[1]] = 5-p[1]; q.add(new int[]{next[0],5-p[1]}); } } StringBuilder sb = new StringBuilder(); for(int i=0;i<n-1;i++) { sb.append(res[i]); sb.append(" "); } sb.deleteCharAt(sb.length()-1); out.println(sb.toString()); } public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); for(int i=0;i<t;i++) { int n = sc.nextInt(); int[][] arr = new int[n-1][2]; for(int j=0;j<n-1;j++) { arr[j][0] = sc.nextInt()-1; arr[j][1] = sc.nextInt()-1; } deal(n,arr); } out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
ad245fe4550aa9cdd83be1a8a456c31b
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { new MainClass().main(); } } class MainClass { Scanner in = new Scanner(System.in); PrintStream out = System.out; public class Pair { public int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } } public void main() { int T = in.nextInt(); for (int t = 0; t < T; t++) { int n = in.nextInt(); int[] cnt = new int[n]; for (int i = 0; i < n; i++) { cnt[i] = 0; } ArrayList<Pair>[] g = new ArrayList[n]; for (int i = 0; i < n; i++) { g[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int u = in.nextInt() - 1, v = in.nextInt() - 1; g[u].add(new Pair(v, i)); g[v].add(new Pair(u, i)); cnt[u]++; cnt[v]++; } int st = -1; boolean bad = false; for (int i = 0; i < n; i++) { if (cnt[i] > 2) { bad = true; break; } if (cnt[i] == 1) { st = i; } } if (bad) { out.println(-1); continue; } int[] ans = new int[n - 1]; int last = -1; for (int i = 0; i < n - 1; i++) { for (Pair v : g[st]) { if (v.x != last) { ans[v.y] = (i % 2 == 0 ? 2 : 3); last = st; st = v.x; break; } } } for (int i = 0; i < n - 1; i++) { out.print(ans[i] + " "); } out.println(); } } }
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output
PASSED
51fb7a91d7488eea38dd501dd18197d0
train_109.jsonl
1642257300
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
256 megabytes
////solution at bottom import java.util.*; import java.lang.*; import java.io.*; import java.math.*; public class test { 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[][] tdiarr(int m , int n){ int[][] a = new int[m][n]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ a[i][j]=Integer.parseInt(next()); } } return a; } long[][] tdlarr(int m , int n){ long[][] a = new long[m][n]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ a[i][j]=Long.parseLong(next()); } } return a; } int[] niarr(int n) { int[] a = new int[n]; for(int i=0;i<n;i++)a[i]=Integer.parseInt(next()); return a; } long[] nlarr(int n) { long[] a = new long[n]; for(int i=0;i<n;i++)a[i]=Long.parseLong(next()); return a; } char[] ncarr(){ return next().trim().toCharArray(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nstr() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader br=new FastReader(); /* */ /////////////////////////////////////////////////////////// public static void main (String[] args) throws java.lang.Exception { try{ System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); } catch(Exception e){ } long start__time = System.currentTimeMillis(); int t=1; br=new FastReader(); t=br.ni(); in1 : for(int TC = 1; TC <= t ; TC++) { solve(); } System.out.println(sb); long end__time = System.currentTimeMillis(); long elapsed__time = end__time - start__time; System.err.println(elapsed__time); } ///end main static StringBuilder sb = new StringBuilder(); static void solve() throws Exception{ //this method is for every testcase n = br.ni(); ans = new int[n-1]; adj = new ArrayList<>(); hm = new HashMap<>(); for(int i=0;i<n;i++) adj.add(new ArrayList<>()); for(int i=0;i<n-1;i++){ int u = br.ni() - 1 , v = br.ni() - 1; String s = "" + u + " " + v; hm.put(s , i); s = "" + v + " " + u; hm.put(s , i); adj.get(u).add(v); adj.get(v).add(u); } vis = new boolean[n]; int root = -1; for(int i=0;i<n;i++){ if(adj.get(i).size() > 2){ sb.append("-1\n"); return; // break; } } for(int i=0;i<n;i++){ if(adj.get(i).size() == 1){ // sb.append("-1\n"); // return; root = i; break; } } vis = new boolean[n]; vis[root] = true; fill = 2; // System.out.println(root); DFS(root); for(int i : ans) sb.append(i+" "); sb.append("\n"); }//end solve static int n; static int[] ans; static HashMap<String , Integer> hm; static boolean[] vis; static ArrayList<ArrayList<Integer>> adj; static int fill; static void DFS(int sou){ ArrayList<Integer> al = adj.get(sou); for(int i : al){ if(vis[i])continue; ans[hm.get(""+sou+" "+i)] = fill ^ 2 ^ 5; fill = fill ^ 2 ^ 5; vis[i] = true; DFS(i); } } }//end class
Java
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
1.5 seconds
["17\n2 5 11\n-1"]
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "number theory", "trees" ]
0639fbeb3a5be67a4c0beeffe8f5d43b
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
standard output