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
|
f96b552e54c58c3b751a6e623051392d
|
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 codeforces {
static ArrayList<Integer>[]tree;
static int n;
static HashMap<pair, Integer>hm=new HashMap<pair, Integer>();
static void dfs(int x,int par,int v) {
if(par!=-1) {
hm.put(new pair(x, par), v);
hm.put(new pair(par, x), v);
}
for(int i:tree[x]) {
if(i!=par)dfs(i, x, 5-v);
}
}
public static void main(String[] args) throws Exception {
int t=sc.nextInt();
while(t-->0) {
n=sc.nextInt();
tree=new ArrayList[n];
pair[]p=new pair[n-1];
for(int i=0;i<n;i++)tree[i]=new ArrayList<Integer>();
for(int i=0;i<n-1;i++) {
int x=sc.nextInt()-1;
int y=sc.nextInt()-1;
p[i]=new pair(x, y);
tree[x].add(y);
tree[y].add(x);
}
boolean val=true;
for(int i=0;i<n;i++) {
if(tree[i].size()>2)val=false;
}
if(!val) {
pw.println(-1);
}else {
for(int i=0;i<n;i++) {
if(tree[i].size()==1) {
dfs(i,-1,2);
break;
}
}
for(pair i:p)pw.print(hm.get(i)+" ");
pw.println();
}
}
pw.close();
}
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();
}
}
static class pair implements Comparable<pair> {
long x;
long y;
public pair(long x, long 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 Long(x).hashCode() * 31 + new Long(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 long mod = 1000000007;
static Random rn = new Random();
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
}
|
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
|
a5391c0035524a0447b28ccf98b57b21
|
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 final class Main {
static PrintWriter out = new PrintWriter(System.out);
static FastReader in = new FastReader();
static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(0, 1), new Pair(1, 0), new Pair(0, -1)};
static int mod = (int) (1e9 + 7);
static int mod2 = 998244353;
public static void main(String[] args) {
int tt = i();
while (tt-- > 0) {
solve();
}
out.flush();
}
public static void solve() {
int n = i();
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 = i() - 1;
int v = i() - 1;
edges[u].add(new int[]{v, i});
edges[v].add(new int[]{u, i});
}
int root = -1;
for (int i = 0; i < n; i++) {
if(edges[i].size()>2){
out.println(-1);
return;
}
if(edges[i].size()==1 && root==-1){
root = i;
}
}
int[] ans = new int[n - 1];
dfs(root, -1, edges, ans, false);
print(ans);
}
private static void dfs(int u, int pre, List<int[]>[] edges, int[] ans, boolean color) {
for (int[] p : edges[u]) {
int v = p[0];
int eidx = p[1];
if (v == pre) {
continue;
}
if (color) {
ans[eidx] = 2;
} else {
ans[eidx] = 3;
}
dfs(v, u, edges, ans, !color);
}
}
static long sum(int[] a) {
long sum = 0;
for (int x : a) {
sum += x;
}
return sum;
}
static long[] pre(int[] a) {
long[] pre = new long[a.length + 1];
pre[0] = 0;
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
return pre;
}
static long[] post(int[] a) {
long[] post = new long[a.length + 1];
post[0] = 0;
for (int i = 0; i < a.length; i++) {
post[i + 1] = post[i] + a[a.length - 1 - i];
}
return post;
}
static long[] pre(long[] a) {
long[] pre = new long[a.length + 1];
pre[0] = 0;
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
return pre;
}
static void print(char A[]) {
for (char c : A) {
out.print(c);
}
out.println();
}
static void print(boolean A[]) {
for (boolean c : A) {
out.print(c + " ");
}
out.println();
}
static void print(int A[]) {
for (int c : A) {
out.print(c + " ");
}
out.println();
}
static void print(long A[]) {
for (long i : A) {
out.print(i + " ");
}
out.println();
}
static void print(List<Integer> A) {
for (int a : A) {
out.print(a + " ");
}
}
static int i() {
return in.nextInt();
}
static long l() {
return in.nextLong();
}
static double d() {
return in.nextDouble();
}
static String s() {
return in.nextLine();
}
static String c() {
return in.next();
}
static int[][] inputWithIdx(int N) {
int A[][] = new int[N][2];
for (int i = 0; i < N; i++) {
A[i] = new int[]{i, in.nextInt()};
}
return A;
}
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 int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
static long GCD(long a, long b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
static long LCM(int a, int b) {
return (long) a / GCD(a, b) * b;
}
static long LCM(long a, long b) {
return a / GCD(a, b) * b;
}
static void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
}
static void shuffleAndSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
}
static void shuffleAndSort(int[][] arr, Comparator<? super int[]> comparator) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int[] temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr, comparator);
}
static void shuffleAndSort(long[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
long temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
}
static boolean isPerfectSquare(double number) {
double sqrt = Math.sqrt(number);
return ((sqrt - Math.floor(sqrt)) == 0);
}
static void swap(int A[], int a, int b) {
int t = A[a];
A[a] = A[b];
A[b] = t;
}
static void swap(char A[], int a, int b) {
char t = A[a];
A[a] = A[b];
A[b] = t;
}
static long pow(long a, long b, int mod) {
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 pow(long a, long b) {
long pow = 1;
long x = a;
while (b != 0) {
if ((b & 1) != 0) {
pow *= x;
}
x = x * x;
b /= 2;
}
return pow;
}
static long modInverse(long x, int mod) {
return pow(x, mod - 2, mod);
}
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;
}
public static String reverse(String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
public static void reverse(int[] arr) {
for (int i = 0; i < arr.length / 2; i++) {
int tmp = arr[i];
arr[arr.length - 1 - i] = tmp;
arr[i] = arr[arr.length - 1 - i];
}
}
public static String repeat(char ch, int repeat) {
if (repeat <= 0) {
return "";
}
final char[] buf = new char[repeat];
for (int i = repeat - 1; i >= 0; i--) {
buf[i] = ch;
}
return new String(buf);
}
public static int[] manacher(String s) {
char[] chars = s.toCharArray();
int n = s.length();
int[] d1 = new int[n];
for (int i = 0, l = 0, r = -1; i < n; i++) {
int k = (i > r) ? 1 : Math.min(d1[l + r - i], r - i + 1);
while (0 <= i - k && i + k < n && chars[i - k] == chars[i + k]) {
k++;
}
d1[i] = k--;
if (i + k > r) {
l = i - k;
r = i + k;
}
}
return d1;
}
public static int[] kmp(String s) {
int n = s.length();
int[] res = new int[n];
for (int i = 1; i < n; ++i) {
int j = res[i - 1];
while (j > 0 && s.charAt(i) != s.charAt(j)) {
j = res[j - 1];
}
if (s.charAt(i) == s.charAt(j)) {
++j;
}
res[i] = j;
}
return res;
}
}
class Pair {
int i;
int j;
Pair(int i, int j) {
this.i = i;
this.j = j;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pair pair = (Pair) o;
return i == pair.i && j == pair.j;
}
@Override
public int hashCode() {
return Objects.hash(i, j);
}
}
class ThreePair {
int i;
int j;
int k;
ThreePair(int i, int j, int k) {
this.i = i;
this.j = j;
this.k = k;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ThreePair pair = (ThreePair) o;
return i == pair.i && j == pair.j && k == pair.k;
}
@Override
public int hashCode() {
return Objects.hash(i, j);
}
}
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;
}
}
class Node {
int val;
public Node(int val) {
this.val = val;
}
}
class ST {
int n;
Node[] st;
ST(int n) {
this.n = n;
st = new Node[4 * Integer.highestOneBit(n)];
}
void build(Node[] nodes) {
build(0, 0, n - 1, nodes);
}
private void build(int id, int l, int r, Node[] nodes) {
if (l == r) {
st[id] = nodes[l];
return;
}
int mid = (l + r) >> 1;
build((id << 1) + 1, l, mid, nodes);
build((id << 1) + 2, mid + 1, r, nodes);
st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]);
}
void update(int i, Node node) {
update(0, 0, n - 1, i, node);
}
private void update(int id, int l, int r, int i, Node node) {
if (i < l || r < i) {
return;
}
if (l == r) {
st[id] = node;
return;
}
int mid = (l + r) >> 1;
update((id << 1) + 1, l, mid, i, node);
update((id << 1) + 2, mid + 1, r, i, node);
st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]);
}
Node get(int x, int y) {
return get(0, 0, n - 1, x, y);
}
private Node get(int id, int l, int r, int x, int y) {
if (x > r || y < l) {
return new Node(0);
}
if (x <= l && r <= y) {
return st[id];
}
int mid = (l + r) >> 1;
return comb(get((id << 1) + 1, l, mid, x, y), get((id << 1) + 2, mid + 1, r, x, y));
}
Node comb(Node a, Node b) {
if (a == null) {
return b;
}
if (b == null) {
return a;
}
return new Node(a.val | b.val);
}
}
|
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
|
9a35d2e96d124f124cc1c8ed5bba01ef
|
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 static java.lang.Math.*;
import static java.util.Map.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.System.*;
public class Main
{
public void tq() throws Exception
{
st=new StringTokenizer(bq.readLine());
int tq=i();
sb=new StringBuilder(2000000);
o:
while(tq-->0)
{
int n=i();
int f[]=new int[n-1];
LinkedList<int[]> l[]=new LinkedList[n];
for(int x=0;x<n;x++)l[x]=new LinkedList<>();
int h=0;
for(int x=0;x<n-1;x++)
{
int a=i()-1;
int b=i()-1;
l[a].add(new int[]{b,x});
l[b].add(new int[]{a,x});
if(l[a].size()==3||l[b].size()==3)h=1;
}
if(h==1)
{
sl(-1);
continue o;
}
f(0,-1,l,f,2);
s(f);
}
p(sb);
}
void f(int i,int p,LinkedList<int[]> l[],int f[],int v)
{
for(int e[]:l[i])
{
int a=e[0];
int in=e[1];
if(a!=p)
{
v=5-v;
f[in]=v;
f(a,i,l,f,v);
}
}
}
long mod=1000000007l;
int max=Integer.MAX_VALUE,min=Integer.MIN_VALUE;long maxl=Long.MAX_VALUE,minl=Long.MIN_VALUE;
BufferedReader bq = new BufferedReader(new InputStreamReader(in));StringTokenizer st;StringBuilder sb;
public static void main(String[] a)throws Exception{new Main().tq();}
int di[][]={{-1,0},{1,0},{0,-1},{0,1}};
int de[][]={{-1,0},{1,0},{0,-1},{0,1},{-1,-1},{1,1},{-1,1},{1,-1}};
void f(){out.flush();}
int p(int i,int p[]){return p[i]<0?i:(p[i]=p(p[i],p));}
boolean c(int x,int y,int n,int m){return x>=0&&x<n&&y>=0&&y<m;}
int[] so(int ar[])
{
Integer r[] = new Integer[ar.length];
for (int x = 0; x < ar.length; x++) r[x] = ar[x];
sort(r);
for (int x = 0; x < ar.length; x++) ar[x] = r[x];
return ar;
}
long[] so(long ar[])
{
Long r[] = new Long[ar.length];
for (int x = 0; x < ar.length; x++) r[x] = ar[x];
sort(r);
for (int x = 0; x < ar.length; x++) ar[x] = r[x];
return ar;
}
char[] so(char ar[])
{
Character r[] = new Character[ar.length];
for (int x = 0; x < ar.length; x++) r[x] = ar[x];
sort(r);
for (int x = 0; x < ar.length; x++) ar[x] = r[x];
return ar;
}
void p(Object p) {out.print(p);}void pl(Object p) {out.println(p);}void pl() {out.println();}
void s(String s) {sb.append(s);}
void s(int s) {sb.append(s);}
void s(long s) {sb.append(s);}
void s(char s) {sb.append(s);}
void s(double s) {sb.append(s);}
void ss() {sb.append(' ');}
void sl(String s) {s(s);sb.append("\n");}
void sl(int s) {s(s);sb.append("\n");}
void sl(long s) {s(s);sb.append("\n");}
void sl(char s) {s(s);sb.append("\n");}
void sl(double s) {s(s);sb.append("\n");}
void sl() {sb.append("\n");}
int l(int v) {return 31 - Integer.numberOfLeadingZeros(v);}
long l(long v) {return 63 - Long.numberOfLeadingZeros(v);}
int sq(int a) {return (int) sqrt(a);}
long sq(long a) {return (long) sqrt(a);}
int gcd(int a, int b)
{
while (b > 0)
{
int c = a % b;
a = b;
b = c;
}
return a;
}
long gcd(long a, long b)
{
while (b > 0l)
{
long c = a % b;
a = b;
b = c;
}
return a;
}
boolean p(String s, int i, int j)
{
while (i < j) if (s.charAt(i++) != s.charAt(j--)) return false;
return true;
}
boolean[] si(int n)
{
boolean bo[] = new boolean[n + 1];
bo[0] = bo[1] = true;
for (int x = 4; x <= n; x += 2) bo[x] = true;
for (int x = 3; x * x <= n; x += 2)
{
if (!bo[x])
{
int vv = (x << 1);
for (int y = x * x; y <= n; y += vv) bo[y] = true;
}
}
return bo;
}
long mul(long a, long b, long m)
{
long r = 1l;
a %= m;
while (b > 0)
{
if ((b & 1) == 1) r = (r * a) % m;
b >>= 1;
a = (a * a) % m;
}
return r;
}
int i() throws IOException
{
if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine());
return Integer.parseInt(st.nextToken());
}
long l() throws IOException
{
if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine());
return Long.parseLong(st.nextToken());
}
String s() throws IOException
{
if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine());
return st.nextToken();
}
double d() throws IOException
{
if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine());
return Double.parseDouble(st.nextToken());
}
void s(int a[])
{
for (int e : a){sb.append(e);sb.append(' ');}
sb.append("\n");
}
void s(long a[])
{
for (long e : a){sb.append(e);sb.append(' ');}
sb.append("\n");
}
void s(char a[])
{
for (char e : a){sb.append(e);sb.append(' ');}
sb.append("\n");
}
void s(int ar[][]) {for (int a[] : ar) s(a);}
void s(long ar[][]) {for (long a[] : ar) s(a);}
void s(char ar[][]) {for (char a[] : ar) s(a);}
int[] ari(int n) throws IOException
{
int ar[] = new int[n];
if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine());
for (int x = 0; x < n; x++) ar[x] = Integer.parseInt(st.nextToken());
return ar;
}
long[] arl(int n) throws IOException
{
long ar[] = new long[n];
if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine());
for (int x = 0; x < n; x++) ar[x] = Long.parseLong(st.nextToken());
return ar;
}
char[] arc(int n) throws IOException
{
char ar[] = new char[n];
if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine());
for (int x = 0; x < n; x++) ar[x] = st.nextToken().charAt(0);
return ar;
}
double[] ard(int n) throws IOException
{
double ar[] = new double[n];
if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine());
for (int x = 0; x < n; x++) ar[x] = Double.parseDouble(st.nextToken());
return ar;
}
String[] ars(int n) throws IOException
{
String ar[] = new String[n];
if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine());
for (int x = 0; x < n; x++) ar[x] = st.nextToken();
return ar;
}
int[][] ari(int n, int m) throws IOException
{
int ar[][] = new int[n][m];
for (int x = 0; x < n; x++)ar[x]=ari(m);
return ar;
}
long[][] arl(int n, int m) throws IOException
{
long ar[][] = new long[n][m];
for (int x = 0; x < n; x++)ar[x]=arl(m);
return ar;
}
char[][] arc(int n, int m) throws IOException
{
char ar[][] = new char[n][m];
for (int x = 0; x < n; x++)ar[x]=arc(m);
return ar;
}
double[][] ard(int n, int m) throws IOException
{
double ar[][] = new double[n][m];
for (int x = 0; x < n; x++)ar[x]=ard(m);
return ar;
}
void p(int ar[])
{
sb = new StringBuilder(11 * ar.length);
for (int a : ar) {sb.append(a);sb.append(' ');}
out.println(sb);
}
void p(long ar[])
{
StringBuilder sb = new StringBuilder(20 * ar.length);
for (long a : ar){sb.append(a);sb.append(' ');}
out.println(sb);
}
void p(double ar[])
{
StringBuilder sb = new StringBuilder(22 * ar.length);
for (double a : ar){sb.append(a);sb.append(' ');}
out.println(sb);
}
void p(char ar[])
{
StringBuilder sb = new StringBuilder(2 * ar.length);
for (char aa : ar){sb.append(aa);sb.append(' ');}
out.println(sb);
}
void p(String ar[])
{
int c = 0;
for (String s : ar) c += s.length() + 1;
StringBuilder sb = new StringBuilder(c);
for (String a : ar){sb.append(a);sb.append(' ');}
out.println(sb);
}
void p(int ar[][])
{
StringBuilder sb = new StringBuilder(11 * ar.length * ar[0].length);
for (int a[] : ar)
{
for (int aa : a){sb.append(aa);sb.append(' ');}
sb.append("\n");
}
p(sb);
}
void p(long ar[][])
{
StringBuilder sb = new StringBuilder(20 * ar.length * ar[0].length);
for (long a[] : ar)
{
for (long aa : a){sb.append(aa);sb.append(' ');}
sb.append("\n");
}
p(sb);
}
void p(double ar[][])
{
StringBuilder sb = new StringBuilder(22 * ar.length * ar[0].length);
for (double a[] : ar)
{
for (double aa : a){sb.append(aa);sb.append(' ');}
sb.append("\n");
}
p(sb);
}
void p(char ar[][])
{
StringBuilder sb = new StringBuilder(2 * ar.length * ar[0].length);
for (char a[] : ar)
{
for (char aa : a){sb.append(aa);sb.append(' ');}
sb.append("\n");
}
p(sb);
}
void pl(Object... ar) {for (Object e : ar) p(e + " ");pl();}
}
|
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
|
68ec6f55b81e8d2b6322b1f1ece79cb5
|
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.Random;
import java.util.StringTokenizer;
/*
*/
public class C {
public static void main(String[] args) {
FastScanner fs=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int T=fs.nextInt();
outer: for (int tt=0; tt<T; tt++) {
int n=fs.nextInt();
ArrayList<Edge>[] nodes=new ArrayList[n];
for (int i=0; i<n; i++) nodes[i]=new ArrayList<>();
Edge[] edges=new Edge[n-1];
for (int i=1; i<n; i++) {
edges[i-1]=new Edge(fs.nextInt()-1, fs.nextInt()-1);
nodes[edges[i-1].from].add(edges[i-1]);
nodes[edges[i-1].to].add(edges[i-1]);
}
//check if impossible
for (int i=0; i<n; i++) {
if (nodes[i].size()>2) {
out.println(-1);
continue outer;
}
}
int endpoint=0;
for (int i=1; i<n; i++) if (nodes[i].size()==1) endpoint=i;
Edge from=null;
ArrayList<Edge> edgesSorted=new ArrayList<>();
while (true) {
// System.out.println("At "+endpoint+" "+from);
if (nodes[endpoint].get(0)==from) {
if (nodes[endpoint].size()==1) break;
from=nodes[endpoint].get(1);
}
else
from=nodes[endpoint].get(0);
endpoint^=from.from^from.to;
edgesSorted.add(from);
}
for (int i=0; i<edgesSorted.size(); i++) edgesSorted.get(i).color=2+i%2;
for (int i=0; i<n-1; i++) {
out.print(edges[i].color+" ");
}
out.println();
}
out.close();
}
static class Edge {
int from, to;
int color;
public Edge(int from, int to) {
this.from=from;
this.to=to;
}
public String toString() {
return from+" "+to;
}
}
static final Random random=new Random();
static final int mod=1_000_000_007;
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
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 long add(long a, long b) {
return (a+b)%mod;
}
static long sub(long a, long b) {
return ((a-b)%mod+mod)%mod;
}
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 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
|
4ed0118f67e5dff46a9938ec36e48a6e
|
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.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Solution {
// VM options: -Xmx1024m -Xss1024m
private ArrayList<Pii>[] g;
private void solve() throws IOException {
int n = nextInt();
g = new ArrayList[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
for (int i = 1; i < n; i++) {
int t1 = nextInt() - 1;
int t2 = nextInt() - 1;
g[t1].add(new Pii(t2, i - 1));
g[t2].add(new Pii(t1, i - 1));
}
for (int i = 0; i < n; i++) {
if (g[i].size() > 2) {
out.println(-1);
return;
}
}
res = new int[n - 1];
dfs(0, -1);
for (int i : res) {
out.print((i + 1) + " ");
}
out.println();
}
private int[] res;
private void dfs(int v, int p) {
if (g[v].size() == 1) {
for (Pii nv : g[v]) {
if (res[nv.y] == 0) {
res[nv.y] = 1;
}
if (nv.x != p) {
dfs(nv.x, v);
}
}
} else {
Pii nv1 = g[v].get(0);
Pii nv2 = g[v].get(1);
if (res[nv1.y] == 0 && res[nv2.y] == 0) {
res[nv1.y] = 1;
res[nv2.y] = 2;
} else {
if (res[nv1.y] == 0) {
res[nv1.y] = 3 - res[nv2.y];
} else {
res[nv2.y] = 3 - res[nv1.y];
}
}
if (nv1.x != p) {
dfs(nv1.x, v);
}
if (nv2.x != p) {
dfs(nv2.x, v);
}
}
}
private static class Pii {
int x;
int y;
public Pii(int x, int y) {
this.x = x;
this.y = y;
}
}
private static final String inputFilename = "input.txt";
private static final String outputFilename = "output.txt";
private BufferedReader in;
private StringTokenizer line;
private PrintWriter out;
private final boolean isDebug;
private Solution(boolean isDebug) {
this.isDebug = isDebug;
}
public static void main(String[] args) throws IOException {
new Solution(Arrays.asList(args).contains("DEBUG_MODE")).run(args);
}
private void run(String[] args) throws IOException {
if (isDebug) {
in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFilename)));
// in = new BufferedReader(new InputStreamReader(System.in));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
}
out = new PrintWriter(System.out);
// out = new PrintWriter(outputFilename);
// int t = isDebug ? nextInt() : 1;
// int t = 1;
int t = nextInt();
for (int i = 0; i < t; i++) {
// out.print("Case #" + (i + 1) + ": ");
solve();
out.flush();
}
in.close();
out.flush();
out.close();
}
private void println(Object... objects) {
boolean isFirst = true;
for (Object o : objects) {
if (!isFirst) {
out.print(" ");
} else {
isFirst = false;
}
out.print(o.toString());
}
out.println();
}
private int[] nextIntArray(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
private long[] nextLongArray(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong();
}
return res;
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private String nextToken() throws IOException {
while (line == null || !line.hasMoreTokens()) {
line = new StringTokenizer(in.readLine());
}
return line.nextToken();
}
private static void assertPredicate(boolean p) {
if (!p) {
throw new RuntimeException();
}
}
private static void assertPredicate(boolean p, String message) {
if (!p) {
throw new RuntimeException(message);
}
}
private static void assertNotEqual(int unexpected, int actual) {
if (actual == unexpected) {
throw new RuntimeException("assertNotEqual: " + unexpected + " == " + actual);
}
}
private static void assertEqual(int expected, int actual) {
if (expected != actual) {
throw new RuntimeException("assertEqual: " + expected + " != " + actual);
}
}
}
|
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
|
662b49ff8908eb5988fb723e50977c42
|
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.*;
/**
__ __
( _) ( _)
/ / \\ / /\_\_
/ / \\ / / | \ \
/ / \\ / / |\ \ \
/ / , \ , / / /| \ \
/ / |\_ /| / / / \ \_\
/ / |\/ _ '_| \ / / / \ \\
| / |/ 0 \0\ / | | \ \\
| |\| \_\_ / / | \ \\
| | |/ \.\ o\o) / \ | \\
\ | /\\`v-v / | | \\
| \/ /_| \\_| / | | \ \\
| | /__/_ `-` / _____ | | \ \\
\| [__] \_/ |_________ \ | \ ()
/ [___] ( \ \ |\ | | //
| [___] |\| \| / |/
/| [____] \ |/\ / / ||
( \ [____ / ) _\ \ \ \| | ||
\ \ [_____| / / __/ \ / / //
| \ [_____/ / / \ | \/ //
| / '----| /=\____ _/ | / //
__ / / | / ___/ _/\ \ | ||
(/-(/-\) / \ (/\/\)/ | / | /
(/\/\) / / //
_________/ / /
\____________/ (
*/
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
ArrayDeque<Edge>[] edges=new ArrayDeque[n];
for(int i=0;i<n;i++) {
edges[i]=new ArrayDeque<Edge>();
}
for(int i=1;i<n;i++) {
int u=sc.nextInt()-1;
int v=sc.nextInt()-1;
edges[u].add(new Edge(v,i-1));
edges[v].add(new Edge(u,i-1));
}
int head=0;
boolean ok=true;
for(int i=0;i<n;i++) {
if(edges[i].size()>2) {
ok=false;
break;
}
if(edges[i].size()==1) {
head=i;
}
}
if(!ok) {
System.out.println(-1);
}
else {
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;
}
for(Edge e:edges[curr]) {
if(e.u!=prev) {
prev=curr;
curr=e.u;
res[e.v]=weight;
break;
}
}
weight ^=1;
}
for(int i=0;i<n-1;i++) {
System.out.print(res[i]+" ");
}
System.out.println();
}
}
}
public static class Edge{
int u;
int v;
Edge(int u,int v){
this.u=u;
this.v=v;
}
}
}
|
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 11
|
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
|
3fe673333224790fbfdacf784ca37a47
|
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 C766_Not_assigning_27_01_2022{
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 int n;
static ArrayList<Integer>[] adj;
static HashMap<String, Integer> map;
static boolean[] visited;
public static void DFS(int u, int val){
visited [u] = true;
for(int v: adj[u]){
if(visited[v])continue;
map.put(u+":"+v,val);
map.put(v+":"+u,val);
DFS(v,val==2? 5:2);
}
}
public static void main(String[] args){
FastReader in = new FastReader();
int t = in.nextInt();
while(t-->0){
n = in.nextInt();
List<int[]> edges = new ArrayList<>();
for(int i=0;i<n-1;i++){
int a = in.nextInt();
int b = in.nextInt();
edges.add(new int[]{a,b});
}
Not_Assigning(edges);
}
}
public static void Not_Assigning(List<int[]> edges){
if(n==2){
System.out.println(2);
return;
}
if(n==3){
System.out.println(2+" "+5);
return;
}
adj = new ArrayList[n+1];
map = new HashMap<>();
visited = new boolean[n+1];
Arrays.setAll(adj,idx -> new ArrayList<Integer>());
for(int[] edge: edges){
int u = edge[0];
int v = edge[1];
adj[u].add(v);
adj[v].add(u);
}
ArrayList<Integer> start = new ArrayList<>();
for(int i=1;i<=n;i++){
int size = adj[i].size();
if(size==1) start.add(i);
else if(size>2){
System.out.println(-1);
return;
}
}
for(int s:start){
if(visited[s])continue;
DFS(s,2);
}
for(int[] edge: edges){
System.out.print(map.get(edge[0]+":"+edge[1])+" ");
}
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 11
|
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
|
5b34fb2f4c270d92a69c6539fc2b7b3b
|
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 static java.lang.Math.sqrt;
import static java.lang.System.out;
import static java.lang.System.err;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static FastReader sc;
// static FastWriter out;
public static void main(String hi[]){
initializeIO();
sc=new FastReader();
// FastWriter out=new FastWriter();
int t=sc.nextInt();
boolean[] seave=sieveOfEratosthenes((int)(1e6));
// int t=1;
while(t--!=0){
int n=sc.nextInt();
int[] ind=new int[n+1];
int[][] intervals=readIntIntervals(n-1,2);
List<List<Integer>> li=readUndirectedGraph(intervals,n);
debug("got");
for(int i=0;i<n-1;i++){
int x=intervals[i][0];
int y=intervals[i][1];
ind[x]++;
ind[y]++;
}
int max=0;
int one=0;
// debug(ind);
for(int i=0;i<=n;i++){
if(ind[i]==1)one=i;
max=max(max,ind[i]);
}
// debug("max in "+max);
if(max>=3)out.println(-1);
else{
Map<String,Integer> map=new HashMap<>();
boolean[] vis=new boolean[n];
Queue<int[]> qu=new LinkedList<>();
qu.add(new int[]{one,2});
// map.put(0,2);
// debug(one);
while (!qu.isEmpty()) {
int[] arr=qu.poll();
// debug(" line "+arr[0]);
int cur=arr[1];
for(int v:li.get(arr[0])){
if(!map.containsKey("("+arr[0]+","+v+")")&&!map.containsKey("("+v+","+arr[0]+")")){
map.put("("+arr[0]+","+v+")",(cur==3)?2:3);
map.put("("+v+","+arr[0]+")",(cur==3)?2:3);
qu.add(new int[]{v,(cur==3)?2:3});
}
}
}
for(int i=0;i<n-1;i++){
if(map.containsKey("("+intervals[i][0]+","+intervals[i][1]+")")){
out.print(map.get("("+intervals[i][0]+","+intervals[i][1]+")")+" ");
}
}
out.println();
}
}
// print(solve(nums,n,m,it,jt));
// System.out.println(String.format("%.10f", max));
}
private static int solve(String[] nums,int n,int m,int it,int jt){
return 0;
}
/*
************************************see constraints carefully***************************
----------------------------------------------------------------------------------------------------------------------------------------------------------
//pallindrome
1:- agar palllindrome related hai to dkho equal character k pair koonse konse hain kyunki bo humeasaa laag jaynge
2:- phir usme ek char add kardo agar kaar sakte ho too
*****if lost****
try to think of prefix and postfix array
//cloring
1->devide on no of colors
2->bipartrate graph
------------------------------------------------------------------------------------------------------------------------------------------------
//bit manupulation
1-> agar do no ka xor min karna hai to dusra bo no ho jiski last bit set ho
for example{
3 ka xor esse no se karao jiski last bit (11)3 set ho jo 2^k
^
| last bit
hogi
}
2-> A || b >max(a,b)
-------------------------------------------------------------------------------------------------------------------------------------------------
//game theory
1;- jo pahle game start karega uske paas advantage hoga
jo ki hai ki agar sath mai finish kiya too jisne pahle start kiya thaa bo jittega kyunki usne start pahle kiya thaa thsts it
//MEX concept
Mex of array is smallest +ve integer not present in array
orr
ek chiz orr
0 2 1 1 0
| |
mex1
| ^=<mex2|
*visited array ka consept use karna hai lowest no find karne k liye*
----------------------------------------------------------------------------------------------------------------------------------------------------
// lexograpgical greater
array x is lexographicallly greater then y first position where element differ there xi>yi
or
sizeof(x)>size(y) and y is prefix of x
--------------------------------------------------------------------------------------------------------
//prime number tricks
3 pime no add karoge to prime nahi rahenge
orr kuch number hain 2 k kombination wale no bo bhi sirf 2 ko add kar k prime baana lenge
*/
private static void print(String s){
out.println(s);
}
private static void debug(String s){
err.println(s);
}
private static int charToInt(char c){
return ((((int)(c-'0'))%48));
}
private static void print(double s){
out.println(s);
}
private static void print(float s){
out.println(s);
}
private static void print(long s){
out.println(s);
}
private static void print(int s){
out.println(s);
}
private static void debug(double s){
err.println(s);
}
private static void debug(float s){
err.println(s);
}
private static void debug(long s){
err.println(s);
}
private static void debug(int s){
err.println(s);
}
private static boolean isPrime(int n){
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
//read graph
private static List<List<Integer>> readUndirectedGraph(int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<n;i++){
int x=sc.nextInt();
int y=sc.nextInt();
graph.get(x).add(y);
graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readUndirectedGraph(int[][] intervals,int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<intervals.length;i++){
int x=intervals[i][0];
int y=intervals[i][1];
graph.get(x).add(y);
graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readDirectedGraph(int[][] intervals,int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<intervals.length;i++){
int x=intervals[i][0];
int y=intervals[i][1];
graph.get(x).add(y);
// graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readDirectedGraph(int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<n;i++){
int x=sc.nextInt();
int y=sc.nextInt();
graph.get(x).add(y);
// graph.get(y).add(x);
}
return graph;
}
static String[] readStringArray(int n){
String[] arr=new String[n];
for(int i=0;i<n;i++){
arr[i]=sc.next();
}
return arr;
}
private static Map<Character,Integer> freq(String s){
Map<Character,Integer> map=new HashMap<>();
for(char c:s.toCharArray()){
map.put(c,map.getOrDefault(c,0)+1);
}
return map;
}
static boolean[] sieveOfEratosthenes(long n){
boolean prime[] = new boolean[(int)n + 1];
for (int i = 2; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true){
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
public static long maxProfit(List<Long> prices) {
long sofar=0;
long max_v=0;
for(int i=0;i<prices.size();i++){
sofar+=prices.get(i);
if (sofar<0) {
sofar=0;
}
max_v=Math.max(max_v,sofar);
}
return max_v;
}
static boolean isMemberAC(int a, int d, int x){
// If difference is 0, then x must
// be same as a.
if (d == 0)
return (x == a);
// Else difference between x and a
// must be divisible by d.
return ((x - a) % d == 0 && (x - a) / d >= 0);
}
private static void sort(int[] arr){
int n=arr.length;
List<Integer> li=new ArrayList<>();
for(int x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sort(long[] arr){
int n=arr.length;
List<Long> li=new ArrayList<>();
for(long x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static long sum(int[] arr){
long sum=0;
for(int x:arr){
sum+=x;
}
return sum;
}
private static long evenSumFibo(long n){
long l1=0,l2=2;
long sum=0;
while (l2<n) {
long l3=(4*l2)+l1;
sum+=l2;
if(l3>n)break;
l1=l2;
l2=l3;
}
return sum;
}
private static void initializeIO(){
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
System.setErr(new PrintStream(new FileOutputStream("error.txt")));
} catch (Exception e) {
// System.err.println(e.getMessage());
}
}
private static int maxOfArray(int[] arr){
int max=Integer.MIN_VALUE;
for(int x:arr){
max=Math.max(max,x);
}
return max;
}
private static long maxOfArray(long[] arr){
long max=Long.MIN_VALUE;
for(long x:arr){
max=Math.max(max,x);
}
return max;
}
private static int[][] readIntIntervals(int n,int m){
int[][] arr=new int[n][m];
for(int j=0;j<n;j++){
for(int i=0;i<m;i++){
arr[j][i]=sc.nextInt();
}
}
return arr;
}
private static long gcd(long a,long b){
if(b==0)return a;
return gcd(b,a%b);
}
private static int gcd(int a,int b){
if(b==0)return a;
return gcd(b,a%b);
}
private static int[] readIntArray(int n){
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
return arr;
}
private static double[] readDoubleArray(int n){
double[] arr=new double[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextDouble();
}
return arr;
}
private static long[] readLongArray(int n){
long[] arr=new long[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextLong();
}
return arr;
}
private static void print(int[] arr){
out.println(Arrays.toString(arr));
}
private static void print(long[] arr){
out.println(Arrays.toString(arr));
}
private static void print(String[] arr){
out.println(Arrays.toString(arr));
}
private static void print(double[] arr){
out.println(Arrays.toString(arr));
}
private static void debug(String[] arr){
err.println(Arrays.toString(arr));
}
private static void debug(int[] arr){
err.println(Arrays.toString(arr));
}
private static void debug(long[] arr){
err.println(Arrays.toString(arr));
}
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
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().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
static class Dsu {
int[] parent, size;
Dsu(int n) {
parent = new int[n + 1];
size = new int[n + 1];
for (int i = 0; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
}
private int findParent(int u) {
if (parent[u] == u) return u;
return parent[u] = findParent(parent[u]);
}
private boolean union(int u, int v) {
// System.out.println("uf "+u+" "+v);
int pu = findParent(u);
// System.out.println("uf2 "+pu+" "+v);
int pv = findParent(v);
// System.out.println("uf3 " + u + " " + pv);
if (pu == pv) return false;
if (size[pu] <= size[pv]) {
parent[pu] = pv;
size[pv] += size[pu];
} else {
parent[pv] = pu;
size[pu] += size[pv];
}
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 11
|
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
|
2795a20289615c6c95862ed8fdd36e40
|
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 static java.lang.Math.sqrt;
import static java.lang.System.out;
import static java.lang.System.err;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static FastReader sc;
// static FastWriter out;
public static void main(String hi[]){
initializeIO();
sc=new FastReader();
// FastWriter out=new FastWriter();
int t=sc.nextInt();
boolean[] seave=sieveOfEratosthenes((int)(1e6));
// int t=1;
while(t--!=0){
List<List<int[]>> li=new ArrayList<>();
int n=sc.nextInt();
for(int i=0;i<=n;i++){
li.add(new ArrayList<>());
}
int[] ind=new int[n+1];
int[][] intervals=new int[n-1][2];
for(int i=0;i<n-1;i++){
intervals[i][0]=sc.nextInt();
intervals[i][1]=sc.nextInt();
// debug(intervals[i]);
}
for(int i=0;i<n-1;i++){
int x=intervals[i][0];
int y=intervals[i][1];
ind[x]++;
ind[y]++;
li.get(x).add(new int[]{y,i});
li.get(y).add(new int[]{x,i});
}
int max=0;
int one=0;
// debug(ind);
for(int i=0;i<=n;i++){
if(ind[i]==1)one=i;
max=max(max,ind[i]);
}
// debug("max in "+max);
if(max>=3)out.println(-1);
else{
Map<String,Integer> map=new HashMap<>();
boolean[] vis=new boolean[n];
Queue<int[]> qu=new LinkedList<>();
qu.add(new int[]{one,2});
// map.put(0,2);
// debug(one);
while (!qu.isEmpty()) {
int[] arr=qu.poll();
// debug(" line "+arr[0]);
int cur=arr[1];
for(int[] v:li.get(arr[0])){
if(!map.containsKey("("+arr[0]+","+v[0]+")")&&!map.containsKey("("+v[0]+","+arr[0]+")")){
map.put("("+arr[0]+","+v[0]+")",(cur==3)?2:3);
map.put("("+v[0]+","+arr[0]+")",(cur==3)?2:3);
qu.add(new int[]{v[0],(cur==3)?2:3});
// cur=(cur==3)?2:3;
}
}
}
// for(Map.Entry<String,Integer> e:map.entrySet()){
// debug(e.getKey()+" "+e.getValue());
// }
for(int i=0;i<n-1;i++){
if(map.containsKey("("+intervals[i][0]+","+intervals[i][1]+")")){
out.print(map.get("("+intervals[i][0]+","+intervals[i][1]+")")+" ");
}
}
out.println();
}
}
// print(solve(nums,n,m,it,jt));
// System.out.println(String.format("%.10f", max));
}
private static int solve(String[] nums,int n,int m,int it,int jt){
boolean see=false;
debug(n+" "+m+" "+it+" "+jt);
int max=4;
for(int i=0;i<n;i++){
char[] arr=nums[i].toCharArray();
// debug(nums[i]+" "+i);
for(int j=0;j<m;j++){
if(arr[j]=='B'){
// debug(i+" "+j);
see=true;
if((i==it&&j==jt))max=0;
if((i==it||j==jt))max=min(max,1);
}
}
}
if(max<4)return max;
if(see)return 2;
return -1;
}
/*
************************************see constraints carefully***************************
//pallindrome
1:- agar palllindrome related hai to dkho equal character k pair koonse konse hain kyunki bo humeasaa laag jaynge
2:- phir usme ek char add kardo agar kaar sakte ho too
*****if lost****
try to think of prefix and postfix array
//cloring
1->devide on no of colors
2->bipartrate graph
//bit manupulation
1-> agar do no ka xor min karna hai to dusra bo no ho jiski last bit set ho
for example{
3 ka xor esse no se karao jiski last bit (11)3 set ho jo 2^k
^
| last bit
hogi
}
2-> A || b >max(a,b)
//game theory
1;- jo pahle game start karega uske paas advantage hoga
jo ki hai ki agar sath mai finish kiya too jisne pahle start kiya thaa bo jittega kyunki usne start pahle kiya thaa thsts it
//MEX concept
Mex of array is smallest +ve integer not present in array
orr
ek chiz orr
0 2 1 1 0
| |
mex1
| ^=<mex2|
*visited array ka consept use karna hai lowest no find karne k liye*
// lexograpgical greater
array x is lexographicallly greater then y first position where element differ there xi>yi
or
sizeof(x)>size(y) and y is prefix of x
*/
private static void print(String s){
out.println(s);
}
private static void debug(String s){
err.println(s);
}
private static int charToInt(char c){
return ((((int)(c-'0'))%48));
}
private static void print(double s){
out.println(s);
}
private static void print(float s){
out.println(s);
}
private static void print(long s){
out.println(s);
}
private static void print(int s){
out.println(s);
}
private static void debug(double s){
err.println(s);
}
private static void debug(float s){
err.println(s);
}
private static void debug(long s){
err.println(s);
}
private static void debug(int s){
err.println(s);
}
private static boolean isPrime(int n){
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
static String[] readStringArray(int n){
String[] arr=new String[n];
for(int i=0;i<n;i++){
arr[i]=sc.next();
}
return arr;
}
private static Map<Character,Integer> freq(String s){
Map<Character,Integer> map=new HashMap<>();
for(char c:s.toCharArray()){
map.put(c,map.getOrDefault(c,0)+1);
}
return map;
}
static boolean[] sieveOfEratosthenes(long n){
boolean prime[] = new boolean[(int)n + 1];
for (int i = 2; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true){
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
public static long maxProfit(List<Long> prices) {
long sofar=0;
long max_v=0;
for(int i=0;i<prices.size();i++){
sofar+=prices.get(i);
if (sofar<0) {
sofar=0;
}
max_v=Math.max(max_v,sofar);
}
return max_v;
}
static boolean isMemberAC(int a, int d, int x){
// If difference is 0, then x must
// be same as a.
if (d == 0)
return (x == a);
// Else difference between x and a
// must be divisible by d.
return ((x - a) % d == 0 && (x - a) / d >= 0);
}
private static void sort(int[] arr){
int n=arr.length;
List<Integer> li=new ArrayList<>();
for(int x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sort(long[] arr){
int n=arr.length;
List<Long> li=new ArrayList<>();
for(long x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static long sum(int[] arr){
long sum=0;
for(int x:arr){
sum+=x;
}
return sum;
}
private static long[] readLongArray(int n){
long[] arr=new long[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextLong();
}
return arr;
}
private static long evenSumFibo(long n){
long l1=0,l2=2;
long sum=0;
while (l2<n) {
long l3=(4*l2)+l1;
sum+=l2;
if(l3>n)break;
l1=l2;
l2=l3;
}
return sum;
}
private static void initializeIO(){
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
System.setErr(new PrintStream(new FileOutputStream("error.txt")));
} catch (Exception e) {
// System.err.println(e.getMessage());
}
}
private static int maxOfArray(int[] arr){
int max=Integer.MIN_VALUE;
for(int x:arr){
max=Math.max(max,x);
}
return max;
}
private static long maxOfArray(long[] arr){
long max=Long.MIN_VALUE;
for(long x:arr){
max=Math.max(max,x);
}
return max;
}
private static int[][] getIntervals(int n,int m){
int[][] arr=new int[n][m];
for(int j=0;j<n;j++){
for(int i=0;i<m;i++){
arr[j][m]=sc.nextInt();
}
}
return arr;
}
private static long gcd(long a,long b){
if(b==0)return a;
return gcd(b,a%b);
}
private static int[] rintArray(int n){
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
return arr;
}
private static double[] readDoubleArray(int n){
double[] arr=new double[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextDouble();
}
return arr;
}
private static long[] rlongArray(int n){
long[] arr=new long[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextLong();
}
return arr;
}
private static String[] rstringArray(int n){
String[] arr=new String[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextLine();
}
return arr;
}
private static void print(int[] arr){
out.println(Arrays.toString(arr));
}
private static void print(long[] arr){
out.println(Arrays.toString(arr));
}
private static void print(String[] arr){
out.println(Arrays.toString(arr));
}
private static void print(double[] arr){
out.println(Arrays.toString(arr));
}
private static void debug(String[] arr){
err.println(Arrays.toString(arr));
}
private static void debug(int[] arr){
err.println(Arrays.toString(arr));
}
private static void debug(long[] arr){
err.println(Arrays.toString(arr));
}
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
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().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
static class Dsu {
int[] parent, size;
Dsu(int n) {
parent = new int[n + 1];
size = new int[n + 1];
for (int i = 0; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
}
private int findParent(int u) {
if (parent[u] == u) return u;
return parent[u] = findParent(parent[u]);
}
private boolean union(int u, int v) {
// System.out.println("uf "+u+" "+v);
int pu = findParent(u);
// System.out.println("uf2 "+pu+" "+v);
int pv = findParent(v);
// System.out.println("uf3 " + u + " " + pv);
if (pu == pv) return false;
if (size[pu] <= size[pv]) {
parent[pu] = pv;
size[pv] += size[pu];
} else {
parent[pv] = pu;
size[pu] += size[pv];
}
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 11
|
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
|
69a4834ee17375eed4c82b003c56c450
|
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 static java.lang.Math.sqrt;
import static java.lang.System.out;
import static java.lang.System.err;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static FastReader sc;
// static FastWriter out;
public static void main(String hi[]){
initializeIO();
sc=new FastReader();
// FastWriter out=new FastWriter();
int t=sc.nextInt();
boolean[] seave=sieveOfEratosthenes((int)(1e6));
// int t=1;
while(t--!=0){
List<List<int[]>> li=new ArrayList<>();
int n=sc.nextInt();
for(int i=0;i<=n;i++){
li.add(new ArrayList<>());
}
int[] ind=new int[n+1];
int[][] intervals=new int[n-1][2];
for(int i=0;i<n-1;i++){
intervals[i][0]=sc.nextInt();
intervals[i][1]=sc.nextInt();
// debug(intervals[i]);
}
for(int i=0;i<n-1;i++){
int x=intervals[i][0];
int y=intervals[i][1];
ind[x]++;
ind[y]++;
li.get(x).add(new int[]{y,i});
li.get(y).add(new int[]{x,i});
}
if(n==2){
print(2);
}else if(n==3){
print(2+" "+11);
}else{
int max=0;
int one=0;
// debug(ind);
for(int i=0;i<=n;i++){
if(ind[i]==1)one=i;
max=max(max,ind[i]);
}
// debug("max in "+max);
if(max>=3)out.println(-1);
else{
Map<String,Integer> map=new HashMap<>();
boolean[] vis=new boolean[n];
Queue<int[]> qu=new LinkedList<>();
qu.add(new int[]{one,2});
// map.put(0,2);
// debug(one);
while (!qu.isEmpty()) {
int[] arr=qu.poll();
// debug(" line "+arr[0]);
int cur=arr[1];
for(int[] v:li.get(arr[0])){
if(!map.containsKey("("+arr[0]+","+v[0]+")")&&!map.containsKey("("+v[0]+","+arr[0]+")")){
map.put("("+arr[0]+","+v[0]+")",(cur==3)?2:3);
map.put("("+v[0]+","+arr[0]+")",(cur==3)?2:3);
qu.add(new int[]{v[0],(cur==3)?2:3});
// cur=(cur==3)?2:3;
}
}
}
// for(Map.Entry<String,Integer> e:map.entrySet()){
// debug(e.getKey()+" "+e.getValue());
// }
for(int i=0;i<n-1;i++){
if(map.containsKey("("+intervals[i][0]+","+intervals[i][1]+")")){
out.print(map.get("("+intervals[i][0]+","+intervals[i][1]+")")+" ");
}
}
out.println();
}
}
}
// print(solve(nums,n,m,it,jt));
// System.out.println(String.format("%.10f", max));
}
private static int solve(String[] nums,int n,int m,int it,int jt){
boolean see=false;
debug(n+" "+m+" "+it+" "+jt);
int max=4;
for(int i=0;i<n;i++){
char[] arr=nums[i].toCharArray();
// debug(nums[i]+" "+i);
for(int j=0;j<m;j++){
if(arr[j]=='B'){
// debug(i+" "+j);
see=true;
if((i==it&&j==jt))max=0;
if((i==it||j==jt))max=min(max,1);
}
}
}
if(max<4)return max;
if(see)return 2;
return -1;
}
/*
************************************see constraints carefully***************************
//pallindrome
1:- agar palllindrome related hai to dkho equal character k pair koonse konse hain kyunki bo humeasaa laag jaynge
2:- phir usme ek char add kardo agar kaar sakte ho too
*****if lost****
try to think of prefix and postfix array
//cloring
1->devide on no of colors
2->bipartrate graph
//bit manupulation
1-> agar do no ka xor min karna hai to dusra bo no ho jiski last bit set ho
for example{
3 ka xor esse no se karao jiski last bit (11)3 set ho jo 2^k
^
| last bit
hogi
}
2-> A || b >max(a,b)
//game theory
1;- jo pahle game start karega uske paas advantage hoga
jo ki hai ki agar sath mai finish kiya too jisne pahle start kiya thaa bo jittega kyunki usne start pahle kiya thaa thsts it
//MEX concept
Mex of array is smallest +ve integer not present in array
orr
ek chiz orr
0 2 1 1 0
| |
mex1
| ^=<mex2|
*visited array ka consept use karna hai lowest no find karne k liye*
// lexograpgical greater
array x is lexographicallly greater then y first position where element differ there xi>yi
or
sizeof(x)>size(y) and y is prefix of x
*/
private static void print(String s){
out.println(s);
}
private static void debug(String s){
err.println(s);
}
private static int charToInt(char c){
return ((((int)(c-'0'))%48));
}
private static void print(double s){
out.println(s);
}
private static void print(float s){
out.println(s);
}
private static void print(long s){
out.println(s);
}
private static void print(int s){
out.println(s);
}
private static void debug(double s){
err.println(s);
}
private static void debug(float s){
err.println(s);
}
private static void debug(long s){
err.println(s);
}
private static void debug(int s){
err.println(s);
}
private static boolean isPrime(int n){
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
static String[] readStringArray(int n){
String[] arr=new String[n];
for(int i=0;i<n;i++){
arr[i]=sc.next();
}
return arr;
}
private static Map<Character,Integer> freq(String s){
Map<Character,Integer> map=new HashMap<>();
for(char c:s.toCharArray()){
map.put(c,map.getOrDefault(c,0)+1);
}
return map;
}
static boolean[] sieveOfEratosthenes(long n){
boolean prime[] = new boolean[(int)n + 1];
for (int i = 2; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true){
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
public static long maxProfit(List<Long> prices) {
long sofar=0;
long max_v=0;
for(int i=0;i<prices.size();i++){
sofar+=prices.get(i);
if (sofar<0) {
sofar=0;
}
max_v=Math.max(max_v,sofar);
}
return max_v;
}
static boolean isMemberAC(int a, int d, int x){
// If difference is 0, then x must
// be same as a.
if (d == 0)
return (x == a);
// Else difference between x and a
// must be divisible by d.
return ((x - a) % d == 0 && (x - a) / d >= 0);
}
private static void sort(int[] arr){
int n=arr.length;
List<Integer> li=new ArrayList<>();
for(int x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sort(long[] arr){
int n=arr.length;
List<Long> li=new ArrayList<>();
for(long x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static long sum(int[] arr){
long sum=0;
for(int x:arr){
sum+=x;
}
return sum;
}
private static long[] readLongArray(int n){
long[] arr=new long[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextLong();
}
return arr;
}
private static long evenSumFibo(long n){
long l1=0,l2=2;
long sum=0;
while (l2<n) {
long l3=(4*l2)+l1;
sum+=l2;
if(l3>n)break;
l1=l2;
l2=l3;
}
return sum;
}
private static void initializeIO(){
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
System.setErr(new PrintStream(new FileOutputStream("error.txt")));
} catch (Exception e) {
// System.err.println(e.getMessage());
}
}
private static int maxOfArray(int[] arr){
int max=Integer.MIN_VALUE;
for(int x:arr){
max=Math.max(max,x);
}
return max;
}
private static long maxOfArray(long[] arr){
long max=Long.MIN_VALUE;
for(long x:arr){
max=Math.max(max,x);
}
return max;
}
private static int[][] getIntervals(int n,int m){
int[][] arr=new int[n][m];
for(int j=0;j<n;j++){
for(int i=0;i<m;i++){
arr[j][m]=sc.nextInt();
}
}
return arr;
}
private static long gcd(long a,long b){
if(b==0)return a;
return gcd(b,a%b);
}
private static int[] rintArray(int n){
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
return arr;
}
private static double[] readDoubleArray(int n){
double[] arr=new double[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextDouble();
}
return arr;
}
private static long[] rlongArray(int n){
long[] arr=new long[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextLong();
}
return arr;
}
private static String[] rstringArray(int n){
String[] arr=new String[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextLine();
}
return arr;
}
private static void print(int[] arr){
out.println(Arrays.toString(arr));
}
private static void print(long[] arr){
out.println(Arrays.toString(arr));
}
private static void print(String[] arr){
out.println(Arrays.toString(arr));
}
private static void print(double[] arr){
out.println(Arrays.toString(arr));
}
private static void debug(String[] arr){
err.println(Arrays.toString(arr));
}
private static void debug(int[] arr){
err.println(Arrays.toString(arr));
}
private static void debug(long[] arr){
err.println(Arrays.toString(arr));
}
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
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().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
static class Dsu {
int[] parent, size;
Dsu(int n) {
parent = new int[n + 1];
size = new int[n + 1];
for (int i = 0; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
}
private int findParent(int u) {
if (parent[u] == u) return u;
return parent[u] = findParent(parent[u]);
}
private boolean union(int u, int v) {
// System.out.println("uf "+u+" "+v);
int pu = findParent(u);
// System.out.println("uf2 "+pu+" "+v);
int pv = findParent(v);
// System.out.println("uf3 " + u + " " + pv);
if (pu == pv) return false;
if (size[pu] <= size[pv]) {
parent[pu] = pv;
size[pv] += size[pu];
} else {
parent[pv] = pu;
size[pu] += size[pv];
}
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 11
|
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
|
a8ae759342ca4b8bab66579ef3f1be17
|
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.List;
import java.util.Map;
import java.util.Scanner;
import java.util.HashMap;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int T = in.nextInt();
while (T-- > 0) {
solveOne(in, out);
}
}
private void solveOne(Scanner in, PrintWriter out) {
int N = in.nextInt();
List<int[]> edges = new ArrayList<>();
Map<Integer, ArrayList<int[]>> T = new HashMap<>();
int start = -1;
boolean isOK = true;
for (int i = 0; i < N - 1; i++) {
int x = in.nextInt();
int y = in.nextInt();
edges.add(new int[]{x, y});
add(x, y, T);
add(y, x, T);
start = x;
if ((T.get(x).size() >= 3) || T.get(y).size() >= 3) isOK = false;
}
if (!isOK) {
out.println(-1);
return;
}
dfs(start, 2, T);
StringBuilder sb = new StringBuilder();
for (int[] edge : edges) {
for (int i = 0; i < T.get(edge[0]).size(); i++) {
int[] e = T.get(edge[0]).get(i);
if (e[0] == edge[1]) sb.append(e[1]).append(" ");
}
}
out.println(sb.toString().trim());
}
private void dfs(int current, int color, Map<Integer, ArrayList<int[]>> T) {
if (!T.containsKey(current)) return;
ArrayList<int[]> l = T.get(current);
for (int j = 0; j < l.size(); j++) {
int[] edge = l.get(j);
if (edge[1] == -1) {
edge[1] = color;
for (int i = 0; i < T.get(edge[0]).size(); i++) {
int[] e = T.get(edge[0]).get(i);
if (e[0] == current) e[1] = color;
}
dfs(edge[0], inverse(color), T);
color = inverse(color);
}
}
}
private void add(int x, int y, Map<Integer, ArrayList<int[]>> T) {
if (!T.containsKey(x)) T.put(x, new ArrayList<>());
ArrayList<int[]> l = T.get(x);
l.add(new int[]{y, -1});
T.put(x, l);
}
private int inverse(int num) {
return (num == 2) ? 3 : 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 11
|
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
|
45d5f69326d28bdb462c752468961919
|
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.List;
import java.util.Map;
import java.util.Scanner;
import java.util.HashMap;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int T = in.nextInt();
while (T-- > 0) {
solveOne(in, out);
}
}
private void solveOne(Scanner in, PrintWriter out) {
int N = in.nextInt();
List<int[]> edges = new ArrayList<>();
Map<Integer, ArrayList<int[]>> T = new HashMap<>();
int start = -1;
for (int i = 0; i < N - 1; i++) {
int x = in.nextInt();
int y = in.nextInt();
edges.add(new int[]{x, y});
add(x, y, T);
add(y, x, T);
start = x;
}
for (int i : T.keySet()) {
if (T.get(i) != null && T.get(i).size() >= 3) {
out.println(-1);
return;
}
}
dfs(start, 2, T);
StringBuilder sb = new StringBuilder();
for (int[] edge : edges) {
for (int i = 0; i < T.get(edge[0]).size(); i++) {
int[] e = T.get(edge[0]).get(i);
if (e[0] == edge[1]) sb.append(e[1]).append(" ");
}
}
out.println(sb.toString().trim());
}
private void dfs(int current, int color, Map<Integer, ArrayList<int[]>> T) {
if (!T.containsKey(current)) return;
ArrayList<int[]> l = T.get(current);
for (int j = 0; j < l.size(); j++) {
int[] edge = l.get(j);
if (edge[1] == -1) {
edge[1] = color;
for (int i = 0; i < T.get(edge[0]).size(); i++) {
int[] e = T.get(edge[0]).get(i);
if (e[0] == current) e[1] = color;
}
dfs(edge[0], inverse(color), T);
color = inverse(color);
}
}
}
private void add(int x, int y, Map<Integer, ArrayList<int[]>> T) {
if (!T.containsKey(x)) T.put(x, new ArrayList<>());
ArrayList<int[]> l = T.get(x);
l.add(new int[]{y, -1});
T.put(x, l);
}
private int inverse(int num) {
return (num == 2) ? 3 : 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 11
|
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
|
2b989f8f78d6ef45de8d78659056f16f
|
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.List;
import java.util.Map;
import java.util.Scanner;
import java.util.HashMap;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int T = in.nextInt();
while (T-- > 0) {
solveOne(in, out);
}
}
private void solveOne(Scanner in, PrintWriter out) {
int N = in.nextInt();
List<int[]> edges = new ArrayList<>();
Map<Integer, ArrayList<int[]>> T = new HashMap<>();
for (int i = 0; i < N - 1; i++) {
int x = in.nextInt();
int y = in.nextInt();
edges.add(new int[]{x, y});
add(x, y, T);
add(y, x, T);
}
int start = -1;
for (int i : T.keySet()) {
if (T.get(i) != null && T.get(i).size() >= 3) {
out.println(-1);
return;
} else if (T.get(i) != null && T.get(i).size() == 1) {
start = i;
}
}
if (start == -1) {
out.println(-1);
return;
}
dfs(start, 2, T);
StringBuilder sb = new StringBuilder();
for (int[] edge : edges) {
for (int i = 0; i < T.get(edge[0]).size(); i++) {
int[] e = T.get(edge[0]).get(i);
if (e[0] == edge[1]) sb.append(e[1]).append(" ");
}
}
out.println(sb.toString().trim());
}
private void dfs(int current, int color, Map<Integer, ArrayList<int[]>> T) {
if (!T.containsKey(current)) return;
ArrayList<int[]> l = T.get(current);
for (int j = 0; j < l.size(); j++) {
int[] edge = l.get(j);
if (edge[1] == -1) {
edge[1] = color;
for (int i = 0; i < T.get(edge[0]).size(); i++) {
int[] e = T.get(edge[0]).get(i);
if (e[0] == current) e[1] = color;
}
dfs(edge[0], inverse(color), T);
color = inverse(color);
}
}
}
private void add(int x, int y, Map<Integer, ArrayList<int[]>> T) {
if (!T.containsKey(x)) T.put(x, new ArrayList<>());
ArrayList<int[]> l = T.get(x);
l.add(new int[]{y, -1});
T.put(x, l);
}
private int inverse(int num) {
return (num == 2) ? 3 : 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 11
|
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
|
26efd0231dc5dcaf4011f8a797a5c0d3
|
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.List;
import java.util.Map;
import java.util.Scanner;
import java.util.HashMap;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int T = in.nextInt();
while (T-- > 0) {
solveOne(in, out);
}
}
private void solveOne(Scanner in, PrintWriter out) {
int N = in.nextInt();
List<int[]> edges = new ArrayList<>();
Map<Integer, ArrayList<int[]>> T = new HashMap<>();
for (int i = 0; i < N - 1; i++) {
int x = in.nextInt();
int y = in.nextInt();
edges.add(new int[]{x, y});
add(x, y, T);
add(y, x, T);
}
int start = -1;
for (int i : T.keySet()) {
if (T.get(i) != null && T.get(i).size() >= 3) {
out.println(-1);
return;
} else if (T.get(i) != null && T.get(i).size() == 1) {
start = i;
}
}
if (start == -1) {
out.println(-1);
return;
}
dfs(start, 2, T);
StringBuilder sb = new StringBuilder();
for (int[] edge : edges) {
for (int i = 0; i < T.get(edge[0]).size(); i++) {
int[] e = T.get(edge[0]).get(i);
if (e[0] == edge[1]) sb.append(e[1]).append(" ");
}
}
out.println(sb.toString().trim());
}
private void dfs(int current, int color, Map<Integer, ArrayList<int[]>> T) {
if (!T.containsKey(current)) return;
int[] edge = T.get(current).get(0);
boolean visited = false;
if (edge[1] == -1) {
visited = true;
edge[1] = color;
for (int i = 0; i < T.get(edge[0]).size(); i++) {
int[] e = T.get(edge[0]).get(i);
if (e[0] == current) e[1] = color;
}
dfs(edge[0], inverse(color), T);
}
if (visited) color = inverse(color);
if (T.get(current).size() == 2) {
edge = T.get(current).get(1);
if (edge[1] == -1) {
edge[1] = color;
for (int i = 0; i < T.get(edge[0]).size(); i++) {
int[] e = T.get(edge[0]).get(i);
if (e[0] == current) e[1] = color;
}
dfs(edge[0], inverse(color), T);
}
}
}
private void add(int x, int y, Map<Integer, ArrayList<int[]>> T) {
if (!T.containsKey(x)) T.put(x, new ArrayList<>());
ArrayList<int[]> l = T.get(x);
l.add(new int[]{y, -1});
T.put(x, l);
}
private int inverse(int num) {
return (num == 2) ? 3 : 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 11
|
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
|
2646c670037305ad384a1f10d39f7972
|
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.io.*;
import java.util.*;
public class Main{
static boolean[] primecheck = new boolean[1000002];
static ArrayList<Integer>[] adj;
static int[] vis;
static long mod = (long)1e9 + 7;
static int w = 2;
static Map<Pair, Integer> hm;
static int[] ans, val, f;
public static void main(String[] args) {
OutputStream outputStream = System.out;
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(outputStream);
PROBLEM solver = new PROBLEM();
int t = 1;
t = in.nextInt();
for (int i = 0; i < t; i++) {
solver.solve(in, out);
}
out.close();
}
static class PROBLEM {
public void solve(FastReader in, PrintWriter out){
int n = in.nextInt();
hm = new HashMap<>();
f = new int[n+1];
ans = new int[n+1];
val = new int[n+1];
vis = new int[n+1];
adj = new ArrayList[n+1];
int st = -1, flag = 0;
for (int i = 0; i < n+1; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < n-1; i++) {
int u = in.nextInt(), v = in.nextInt();
Pair p = new Pair(u, v);
hm.put(p, i+1);
f[u]++;
f[v]++;
if(f[u] > 2 || f[v] > 2){
flag = -1;
}
adj[u].add(v);
adj[v].add(u);
}
if(flag == -1) out.println(-1);
else {
dfs(1, 1);
for (int i = 1; i < n; i++) {
out.print(ans[i] + " ");
}
out.println();
}
}
}
static void dfs(int i, int type){
vis[i] = 1;
for(int j: adj[i]){
if(vis[j] == 0) {
Pair p = new Pair(i, j);
int id = -1;
if(hm.containsKey(p)){
id = hm.get(p);
}
else {
p = new Pair(j, i);
if (hm.containsKey(p)) id = hm.get(p);
}
ans[id] = (type == 0) ? 2 : 5;
type^=1;
dfs(j, type);
}
}
}
static long sigmaK(long k){
return (k*(k+1))/2;
}
static void swap(int[] a, int l, int r) {
int temp = a[l];
a[l] = a[r];
a[r] = temp;
}
static HashMap<Integer, Integer> initializeMap(int n){
HashMap<Integer,Integer> hm = new HashMap<>();
for (int i = 0; i <= n; i++) {
hm.put(i, 0);
}
return hm;
}
static boolean isRegular(char[] c){
Stack<Character> s = new Stack<>();
for (char value : c) {
if (s.isEmpty() && value == ')') return false;
if (value == '(') s.push(value);
else s.pop();
}
return s.isEmpty();
}
static ArrayList<ArrayList<Integer>> createAdj(int n, int e){
FastReader in = new FastReader();
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n + 1; i++) {
adj.add(new ArrayList<>());
}
for (int i = 0; i < e; i++) {
int a = in.nextInt(), b = in.nextInt();
System.out.println(a);
adj.get(a).add(b);
adj.get(b).add(a);
}
return adj;
}
static int binarySearch(int[] a, int l, int r, int x){
if(r>=l){
int mid = l + (r-l)/2;
if(a[mid] == x) return mid;
if(a[mid] > x) return binarySearch(a, l, mid-1, x);
else return binarySearch(a,mid+1, r, x);
}
return -1;
}
static boolean isPalindromeI(int n){
int d = 0;
int y = n;
while(y>0){
d++;
y/=10;
}
int[] a = new int[d];
for (int i = 0; i < d; i++) {
a[i] = n%10;
n/=10;
}
for (int i = 0; i < d / 2; i++) {
if(a[i] != a[d-i-1]) return false;
}
return true;
}
static long gcd(long a, long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
static long lcm(long a, long b)
{
return (a / gcd(a, b)) * b;
}
static boolean isSquare(double a) {
boolean isSq = false;
double b = Math.sqrt(a);
double c = Math.sqrt(a) - Math.floor(b);
if (c == 0) isSq = true;
return isSq;
}
static long fast_pow(long a, long b) { //Jeel bhai OP
if(b == 0)
return 1L;
long val = fast_pow(a, b / 2);
if(b % 2 == 0)
return val * val % mod;
else
return val * val % mod * a % mod;
}
static int exponentMod(int A, int B, int C) {
// Base cases
if (A == 0)
return 0;
if (B == 0)
return 1;
// If B is even
long y;
if (B % 2 == 0) {
y = exponentMod(A, B / 2, C);
y = (y * y) % C;
}
// If B is odd
else {
y = A % C;
y = (y * exponentMod(A, B - 1, C) % C) % C;
}
return (int) ((y + C) % C);
}
// 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){
//
// int ans = Integer.compare(x, o.x);
// if(o.x == x) ans = Integer.compare(y, o.y);
//
// return ans;
//
//// int ans = Integer.compare(y, o.y);
//// if(o.y == y) ans = Integer.compare(x, o.x);
////
//// return ans;
// }
// }
static class Tuple implements Comparable<Tuple>{
int x, y, id;
Tuple(int x, int y, int id){
this.x = x;
this.y = y;
this.id = id;
}
public int compareTo(Tuple o){
int ans = Integer.compare(x, o.x);
if(o.x == x) ans = Integer.compare(y, o.y);
return ans;
}
}
public static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
public U x;
public V y;
public Pair(U x, V y) {
this.x = x;
this.y = y;
}
public int hashCode() {
return (x == null ? 0 : x.hashCode() * 31) + (y == null ? 0 : y.hashCode());
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair<U, V> p = (Pair<U, V>) o;
return (x == null ? p.x == null : x.equals(p.x)) && (y == null ? p.y == null : y.equals(p.y));
}
public int compareTo(Pair<U, V> b) {
int cmpU = x.compareTo(b.x);
return cmpU != 0 ? cmpU : y.compareTo(b.y);
}
public int compareToY(Pair<U, V> b) {
int cmpU = y.compareTo(b.y);
return cmpU != 0 ? cmpU : x.compareTo(b.x);
}
public String toString() {
return String.format("(%s, %s)", x.toString(), y.toString());
}
}
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());
}
char nextChar() {
return next().charAt(0);
}
boolean nextBoolean() {
return !(nextInt() == 0);
}
// boolean nextBoolean(){return Boolean.parseBoolean(next());}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int[] readArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) array[i] = nextInt();
return array;
}
}
private static int[] mergeSort(int[] array) {
//array.length replaced with ctr
int ctr = array.length;
if (ctr <= 1) {
return array;
}
int midpoint = ctr / 2;
int[] left = new int[midpoint];
int[] right;
if (ctr % 2 == 0) {
right = new int[midpoint];
} else {
right = new int[midpoint + 1];
}
for (int i = 0; i < left.length; i++) {
left[i] = array[i];
}
for (int i = 0; i < right.length; i++) {
right[i] = array[i + midpoint];
}
left = mergeSort(left);
right = mergeSort(right);
int[] result = merge(left, right);
return result;
}
private static int[] merge(int[] left, int[] right) {
int[] result = new int[left.length + right.length];
int leftPointer = 0, rightPointer = 0, resultPointer = 0;
while (leftPointer < left.length || rightPointer < right.length) {
if (leftPointer < left.length && rightPointer < right.length) {
if (left[leftPointer] < right[rightPointer]) {
result[resultPointer++] = left[leftPointer++];
} else {
result[resultPointer++] = right[rightPointer++];
}
} else if (leftPointer < left.length) {
result[resultPointer++] = left[leftPointer++];
} else {
result[resultPointer++] = right[rightPointer++];
}
}
return result;
}
public static void Sieve(int n) {
Arrays.fill(primecheck, true);
primecheck[0] = false;
primecheck[1] = false;
for (int i = 2; i * i < n + 1; i++) {
if (primecheck[i]) {
for (int j = i * 2; j < n + 1; j += i) {
primecheck[j] = false;
}
}
}
}
}
|
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 11
|
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
|
3b8a5e3a4cac91483a5264eff4ea8c91
|
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.io.*;
import java.util.*;
public class Main{
static boolean[] primecheck = new boolean[1000002];
static ArrayList<Integer>[] adj;
static int[] vis;
static long mod = (long)1e9 + 7;
static int w = 2;
static Map<Pair, Integer> hm;
static int[] ans, val, f;
public static void main(String[] args) {
OutputStream outputStream = System.out;
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(outputStream);
PROBLEM solver = new PROBLEM();
int t = 1;
t = in.nextInt();
for (int i = 0; i < t; i++) {
solver.solve(in, out);
}
out.close();
}
static class PROBLEM {
public void solve(FastReader in, PrintWriter out){
int n = in.nextInt();
hm = new HashMap<>();
f = new int[n+1];
ans = new int[n+1];
val = new int[n+1];
vis = new int[n+1];
adj = new ArrayList[n+1];
int st = -1, flag = 0;
for (int i = 0; i < n+1; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < n-1; i++) {
int u = in.nextInt(), v = in.nextInt();
Pair p = new Pair(u, v);
hm.put(p, i+1);
f[u]++;
f[v]++;
if(f[u] > 2 || f[v] > 2){
flag = -1;
}
adj[u].add(v);
adj[v].add(u);
}
for (int i = 0; i < f.length; i++) {
if(f[i] == 1){
st = i;
break;
}
}
if(flag == -1) out.println(-1);
else {
dfs(st, hm);
for (int i = 1; i < n; i++) {
out.print(ans[i] + " ");
}
out.println();
}
// int n = in.nextInt(), m = in.nextInt();
// int cur = n - n/2 + m - m/2;
//
// if((n&1) == 1) cur--;
// if((m&1) == 1) cur--;
//
//
// int ctr = 0;
// if((n&1) == 1 && (m&1) == 1) ctr = 1;
// else if((n&1) == 0 && (m&1) == 0) ctr = 4;
// else ctr = 2;
//
// int y = ctr;
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// if(y == 0){
// ctr+=4;
// y = ctr;
// cur++;
// }
// out.print(cur + " ");
// y--;
// }
// }
// out.println();
}
}
static void dfs(int i, Map<Pair, Integer> hm){
vis[i] = 1;
for(int j: adj[i]){
if(vis[j] == 0) {
int w = 2;
if(val[i] == 2 || val[j] == 2) w = 5;
int id = 0;
Pair p = new Pair(i, j);
if(hm.containsKey(p)){
id = hm.get(p);
}
else {
p = new Pair(j, i);
if (hm.containsKey(p)) id = hm.get(p);
}
ans[id] = w;
val[i] = w;
val[j] = w;
dfs(j, hm);
}
}
}
static long sigmaK(long k){
return (k*(k+1))/2;
}
static void swap(int[] a, int l, int r) {
int temp = a[l];
a[l] = a[r];
a[r] = temp;
}
static HashMap<Integer, Integer> initializeMap(int n){
HashMap<Integer,Integer> hm = new HashMap<>();
for (int i = 0; i <= n; i++) {
hm.put(i, 0);
}
return hm;
}
static boolean isRegular(char[] c){
Stack<Character> s = new Stack<>();
for (char value : c) {
if (s.isEmpty() && value == ')') return false;
if (value == '(') s.push(value);
else s.pop();
}
return s.isEmpty();
}
static ArrayList<ArrayList<Integer>> createAdj(int n, int e){
FastReader in = new FastReader();
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n + 1; i++) {
adj.add(new ArrayList<>());
}
for (int i = 0; i < e; i++) {
int a = in.nextInt(), b = in.nextInt();
System.out.println(a);
adj.get(a).add(b);
adj.get(b).add(a);
}
return adj;
}
static int binarySearch(int[] a, int l, int r, int x){
if(r>=l){
int mid = l + (r-l)/2;
if(a[mid] == x) return mid;
if(a[mid] > x) return binarySearch(a, l, mid-1, x);
else return binarySearch(a,mid+1, r, x);
}
return -1;
}
static boolean isPalindromeI(int n){
int d = 0;
int y = n;
while(y>0){
d++;
y/=10;
}
int[] a = new int[d];
for (int i = 0; i < d; i++) {
a[i] = n%10;
n/=10;
}
for (int i = 0; i < d / 2; i++) {
if(a[i] != a[d-i-1]) return false;
}
return true;
}
static long gcd(long a, long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
static long lcm(long a, long b)
{
return (a / gcd(a, b)) * b;
}
static boolean isSquare(double a) {
boolean isSq = false;
double b = Math.sqrt(a);
double c = Math.sqrt(a) - Math.floor(b);
if (c == 0) isSq = true;
return isSq;
}
static long fast_pow(long a, long b) { //Jeel bhai OP
if(b == 0)
return 1L;
long val = fast_pow(a, b / 2);
if(b % 2 == 0)
return val * val % mod;
else
return val * val % mod * a % mod;
}
static int exponentMod(int A, int B, int C) {
// Base cases
if (A == 0)
return 0;
if (B == 0)
return 1;
// If B is even
long y;
if (B % 2 == 0) {
y = exponentMod(A, B / 2, C);
y = (y * y) % C;
}
// If B is odd
else {
y = A % C;
y = (y * exponentMod(A, B - 1, C) % C) % C;
}
return (int) ((y + C) % C);
}
// 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){
//
// int ans = Integer.compare(x, o.x);
// if(o.x == x) ans = Integer.compare(y, o.y);
//
// return ans;
//
//// int ans = Integer.compare(y, o.y);
//// if(o.y == y) ans = Integer.compare(x, o.x);
////
//// return ans;
// }
// }
static class Tuple implements Comparable<Tuple>{
int x, y, id;
Tuple(int x, int y, int id){
this.x = x;
this.y = y;
this.id = id;
}
public int compareTo(Tuple o){
int ans = Integer.compare(x, o.x);
if(o.x == x) ans = Integer.compare(y, o.y);
return ans;
}
}
public static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
public U x;
public V y;
public Pair(U x, V y) {
this.x = x;
this.y = y;
}
public int hashCode() {
return (x == null ? 0 : x.hashCode() * 31) + (y == null ? 0 : y.hashCode());
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair<U, V> p = (Pair<U, V>) o;
return (x == null ? p.x == null : x.equals(p.x)) && (y == null ? p.y == null : y.equals(p.y));
}
public int compareTo(Pair<U, V> b) {
int cmpU = x.compareTo(b.x);
return cmpU != 0 ? cmpU : y.compareTo(b.y);
}
public int compareToY(Pair<U, V> b) {
int cmpU = y.compareTo(b.y);
return cmpU != 0 ? cmpU : x.compareTo(b.x);
}
public String toString() {
return String.format("(%s, %s)", x.toString(), y.toString());
}
}
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());
}
char nextChar() {
return next().charAt(0);
}
boolean nextBoolean() {
return !(nextInt() == 0);
}
// boolean nextBoolean(){return Boolean.parseBoolean(next());}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int[] readArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) array[i] = nextInt();
return array;
}
}
private static int[] mergeSort(int[] array) {
//array.length replaced with ctr
int ctr = array.length;
if (ctr <= 1) {
return array;
}
int midpoint = ctr / 2;
int[] left = new int[midpoint];
int[] right;
if (ctr % 2 == 0) {
right = new int[midpoint];
} else {
right = new int[midpoint + 1];
}
for (int i = 0; i < left.length; i++) {
left[i] = array[i];
}
for (int i = 0; i < right.length; i++) {
right[i] = array[i + midpoint];
}
left = mergeSort(left);
right = mergeSort(right);
int[] result = merge(left, right);
return result;
}
private static int[] merge(int[] left, int[] right) {
int[] result = new int[left.length + right.length];
int leftPointer = 0, rightPointer = 0, resultPointer = 0;
while (leftPointer < left.length || rightPointer < right.length) {
if (leftPointer < left.length && rightPointer < right.length) {
if (left[leftPointer] < right[rightPointer]) {
result[resultPointer++] = left[leftPointer++];
} else {
result[resultPointer++] = right[rightPointer++];
}
} else if (leftPointer < left.length) {
result[resultPointer++] = left[leftPointer++];
} else {
result[resultPointer++] = right[rightPointer++];
}
}
return result;
}
public static void Sieve(int n) {
Arrays.fill(primecheck, true);
primecheck[0] = false;
primecheck[1] = false;
for (int i = 2; i * i < n + 1; i++) {
if (primecheck[i]) {
for (int j = i * 2; j < n + 1; j += i) {
primecheck[j] = false;
}
}
}
}
}
|
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 11
|
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
|
9bf9d3b54081cf4129e90fb59ee1bdb1
|
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.*;
//C. Minimize Distance
public class B {
static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
static int gcd(int n, int m) {
if (m == 0)
return n;
return gcd(m, n % m);
}
static boolean ispalin(int[] s, int p) {
int n = s.length;
int i = 0;
int j = n - 1;
while (i < j) {
if (s[i] == p) {
i++;
continue;
}
if (s[j] == p) {
j--;
continue;
}
if (s[i] != s[j])
return false;
i++;
j--;
}
return true;
}
static void dfs(Vector<Vector<Pair>> adj, int[] dis, int v, int prev, int par) {
for (Pair i : adj.get(v)) {
if (i.x == par)
continue;
if (prev == 2)
dis[i.y] = 3;
else
dis[i.y] = 2;
if (adj.get(i.x).size() == 1)
prev = 3;
else
prev = dis[i.y];
dfs(adj, dis, i.x, prev, v);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder str = new StringBuilder();
int t = sc.nextInt();
for (int xx = 0; xx < t; xx++) {
int n = sc.nextInt();
Vector<Vector<Pair>> adj = new Vector<>();
for (int i = 0; i < n; i++)
adj.add(new Vector<>());
int v = 0;
int cnt[] = new int[n];
for (int i = 0; i < n - 1; i++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
adj.get(a).add(new Pair(b, i));
adj.get(b).add(new Pair(a, i));
cnt[a]++;
cnt[b]++;
}
boolean ok = true;
for (int i = 0; i < n; i++) {
if (cnt[i] >= 3)
ok = false;
if (cnt[i] == 2)
v = i;
}
if (!ok) {
str.append(-1 + "\n");
continue;
}
int[] dis = new int[n];
dfs(adj, dis, v, 2, -1);
for (int i = 0; i < n - 1; i++)
str.append(dis[i] + " ");
str.append("\n");
}
System.out.println(str);
sc.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 11
|
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
|
8a9e986dd2f57a256d905b0ef47c3b0a
|
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.util.Map.Entry;
import java.math.*;
import java.sql.Array;
public class Simple{
public static class Pair implements Comparable<Pair>{
int x;
int y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
public int compareTo(Pair other){
return (int) (this.y - other.y);
}
public boolean equals(Pair other){
if(this.x == other.x && this.y == other.y)return true;
return false;
}
public int hashCode(){
return 31*x + y;
}
// @Override
// public int compareTo(Simple.Pair o) {
// // TODO Auto-generated method stub
// return 0;
// }
}
static int power(int x, int y, int p)
{
// Initialize result
int res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static int modInverse(int n, int p)
{
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static int nCrModPFermat(int n, int r,
int p)
{
if (n<r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
int[] fac = new int[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}
static int nCrModp(int n, int r, int p)
{
if (r > n - r)
r = n - r;
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
int C[] = new int[r + 1];
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
public static class Node{
int root;
ArrayList<Node> al;
Node par;
public Node(int root,ArrayList<Node> al,Node par){
this.root = root;
this.al = al;
this.par = par;
}
}
// public static int helper(int arr[],int n ,int i,int j,int dp[][]){
// if(i==0 || j==0)return 0;
// if(dp[i][j]!=-1){
// return dp[i][j];
// }
// if(helper(arr, n, i-1, j-1, dp)>=0){
// return dp[i][j]=Math.max(helper(arr, n, i-1, j-1,dp)+arr[i-1], helper(arr, n, i-1, j,dp));
// }
// return dp[i][j] = helper(arr, n, i-1, j,dp);
// }
// public static void dfs(ArrayList<ArrayList<Integer>> al,int levelcount[],int node,int count){
// levelcount[count]++;
// for(Integer x : al.get(node)){
// dfs(al, levelcount, x, count+1);
// }
// }
public static long __gcd(long a, long b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
public static long helper(int arr1[][],int m){
Arrays.sort(arr1, (int a[],int b[])-> a[0]-b[0]);
long ans =0;
for(int i=1;i<m;i++){
long count =0;
for(int j=0;j<i;j++){
if(arr1[i][1] > arr1[j][1])count++;
}
ans+=count;
}
return ans;
}
public static class DSU{
int n;
int par[];
int rank[];
public DSU(int n){
this.n = n;
par = new int[n+1];
rank = new int[n+1];
for(int i=1;i<=n;i++){
par[i] = i ;
rank[i] = 0;
}
}
public int findPar(int node){
if(node==par[node]){
return node;
}
return par[node] = findPar(par[node]);//path compression
}
public void union(int u,int v){
u = findPar(u);
v = findPar(v);
if(rank[u]<rank[v]){
par[u] = v;
}
else if(rank[u]>rank[v]){
par[v] = u;
}
else{
par[v] = u;
rank[u]++;
}
}
}
public static void dfs(ArrayList<ArrayList<Integer>> adj,ArrayList<ArrayList<Integer>> edges,int node,boolean[] vis,ArrayList<Integer> al){
vis[node] = true;
if(!vis[adj.get(node).get(0)]){
al.add(edges.get(node).get(0));
dfs(adj, edges, adj.get(node).get(0), vis, al);
}
else if(adj.get(node).size()==2&&!vis[adj.get(node).get(1)]){
al.add(edges.get(node).get(1));
dfs(adj, edges, adj.get(node).get(1), vis, al);
}
}
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int t =s.nextInt();
for(int t1 = 1;t1<=t;t1++){
int n = s.nextInt();
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
ArrayList<ArrayList<Integer>> edges = new ArrayList<>();
for(int i=0;i<=n;i++){
adj.add(new ArrayList<>());
edges.add(new ArrayList<>());
}
int indegree[] = new int[n+1];
boolean bool= true;
for(int i=1;i<n;i++){
int u = s.nextInt();
int v = s.nextInt();
indegree[u]++;
indegree[v]++;
if(indegree[u] > 2 || indegree[v]>2){
bool = false;
}
adj.get(u).add(v);
adj.get(v).add(u);
edges.get(u).add(i);
edges.get(v).add(i);
}
if(!bool){
System.out.println(-1);
continue;
}
ArrayList<Integer> al = new ArrayList<>();
boolean[] vis = new boolean[n+1];
int node = 0;
for(int i=1;i<=n;i++){
if(indegree[i]==1){
node = i;
break;
}
}
if(node==0){
System.out.println(-1);
continue;
}
dfs(adj,edges,node,vis,al);
int ans[] = new int[n];
for(int i=1;i<n;i++){
if(i%2==0){
ans[al.get(i-1)] = 2;
}
else{
ans[al.get(i-1)]= 3;
}
}
for(int i =1;i<n;i++){
System.out.print(ans[i]+" ");
}
System.out.println();
}
}
}
/*
4 2 2 7
0 2 5
-2 3
5
0*x1 + 1*x2 + 2*x3 + 3*x4
*/
|
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 11
|
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
|
1824412395a7be9ccae80b6ddadc6967
|
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.eeshaan;
import java.util.*;
public class cf1 {
public static boolean isPrime(int n){
for (int i = 2; i <= Math.sqrt(n) ; i++) {
if(n%i == 0)
return false;
}
return true;
}
public static long even_sum(int n){
return n*n+n;
}
public static long odd_sum(int n){
return n*n;
}
public static int dfs(List<List<Integer>> ls){
int ans =0,cur,n = ls.size();
boolean[] vis = new boolean[n];
int[] seen = new int[n];
Arrays.fill(vis,false);
Arrays.fill(seen,0);
Stack<Integer> st = new Stack<>();
for (int k = 0; k <n ; k++) {
// System.out.println(k+" ans:"+ans);
if(!vis[k]) {
st.add(k);
vis[k] = true;
seen[k] = 1;
while (!st.isEmpty()){
cur = st.pop();
vis[cur] = true;
int cur_color = seen[cur];
for (int i = 0; i <ls.get(cur).size() ; i++) {
if(seen[ls.get(cur).get(i)] == 0 )
seen[ls.get(cur).get(i)] = -1*cur_color;
else if (seen[ls.get(cur).get(i)] == cur_color)
ans += 1;
if (!vis[ls.get(cur).get(i)]) {
st.add(ls.get(cur).get(i));
vis[ls.get(cur).get(i)] = true;
}
}
}
}
}
return ans/2;
}
public static boolean stable(int d, int[] arr , int c){
int cnt = 1, prev = arr[0];
// System.out.println(Arrays.toString(arr));
for (int i = 1; i <arr.length ; i++) {
if(arr[i]-prev >= d){
cnt+=1;
prev = arr[i];
}
}
// System.out.println("in check - "+d+" "+cnt);
return cnt>=c;
}
public static void main(String[] das) {
// System.out.println((int)'z'+"/"+(int)'a');
Scanner sc = new Scanner(System.in);
int t, n, m, r,c, ans = 0;
// int r1,r2,c1,c2,d1,d2;
t = sc.nextInt();
// k = sc.nextLong();
// int[] arr = new int[n];
// int[] left = new int[n];
// int[] right = new int[n];
// char id = sc.next().charAt(0);
// sc.nextLine();
// String a ;
// a = sc.nextLine();
// b = sc.nextLine();
// System.out.println( Integer.MAX_VALUE);
// System.out.println(-3/2 +""+-7/2);
for (int i = 0; i < t; i++) {
n = sc.nextInt();
ans = 0;
List<List<Integer>> graph = new ArrayList<>();
int[][] info = new int[n - 1][3];
int[][] arr = new int[n][4];
for (int j = 0; j < n; j++) {
Arrays.fill(arr[j], -1);
graph.add(new ArrayList<>());
}
for (int j = 0; j < n - 1; j++) {
r = sc.nextInt();
c = sc.nextInt();
graph.get(r - 1).add(c - 1);
graph.get(c - 1).add(r - 1);
info[j][0] = r - 1;
info[j][1] = c - 1;
if (arr[r - 1][0] == -1)
arr[r - 1][0] = c - 1;
else
arr[r - 1][2] = c - 1;
if (arr[c - 1][0] == -1)
arr[c - 1][0] = r - 1;
else
arr[c - 1][2] = r - 1;
}
for (int j = 0; j < n; j++) {
if (graph.get(j).size() > 2) {
ans = -1;
break;
}
}
if (ans == -1)
System.out.println(ans);
else {
Stack<Integer> st = new Stack<>();
for (int j = 0; j < n; j++) {
if (arr[j][2] == -1) {
st.add(j);
break;
}
}
boolean[] vis = new boolean[n];
Arrays.fill(vis,false);
vis[st.peek()] = true;
int cur,col = 2;
while (!st.isEmpty()){
cur = st.pop();
for (int j = 0; j <graph.get(cur).size() ; j++) {
if(!vis[graph.get(cur).get(j)]){
st.add(graph.get(cur).get(j));
vis[graph.get(cur).get(j)] = true;
if(arr[cur][0]==graph.get(cur).get(j))
arr[cur][1] = col;
else
arr[cur][3] = col;
if(arr[graph.get(cur).get(j)][0]==cur)
arr[graph.get(cur).get(j)][1]=col;
else
arr[graph.get(cur).get(j)][3]=col;
if(col==2)
col = 5;
else
col = 2;
}
}
}
for (int j = 0; j < info.length; j++) {
r = info[j][0];
c = info[j][1];
if (arr[r][0] == c)
System.out.print(arr[r][1] + " ");
else
System.out.print(arr[r][3] + " ");
}
System.out.println();
}
}
}
}
/*
52 53 54 51
100 = 152
52cr 13 - 5 5 3, 4 5 4 ,4 4 5
*/
|
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 11
|
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
|
5749be76785527abd4a5b077f207e274
|
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 notassigning;
import java.util.*;
import java.io.*;
public class notassigning {
public static void main(String[] args) throws IOException {
BufferedReader fin = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(fin.readLine());
StringBuilder fout = new StringBuilder();
while(t-- > 0) {
int n = Integer.parseInt(fin.readLine());
boolean isValid = true;
int start = -1;
ArrayList<ArrayList<Integer>> c = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i < n; i++) {
c.add(new ArrayList<Integer>());
}
HashMap<ArrayList<Integer>, Integer> order = new HashMap<ArrayList<Integer>, Integer>();
for(int i = 0; i < n - 1; i++) {
StringTokenizer st = new StringTokenizer(fin.readLine());
int a = Integer.parseInt(st.nextToken()) - 1;
int b = Integer.parseInt(st.nextToken()) - 1;
order.put(new ArrayList<Integer>(Arrays.asList(a, b)), i);
c.get(a).add(b);
c.get(b).add(a);
if((c.get(a).size() == 3 || c.get(b).size() == 3) && isValid) {
isValid = false;
}
}
if(!isValid) {
fout.append("-1\n");
continue;
}
//locate the start of the chain
for(int i = 0; i < n; i++) {
if(c.get(i).size() == 1) {
start = i;
break;
}
}
int[] ans = new int[n - 1];
int cur = start;
int next = c.get(start).get(0);
int prime = 2;
while(true) {
int index = 0;
if(order.containsKey(new ArrayList<Integer>(Arrays.asList(cur, next)))) {
index = order.get(new ArrayList<Integer>(Arrays.asList(cur, next)));
}
else {
index = order.get(new ArrayList<Integer>(Arrays.asList(next, cur)));
}
ans[index] = prime;
if(c.get(next).size() == 1) {
break;
}
prime = prime == 3? 2 : 3;
int prev = cur;
cur = next;
next = c.get(cur).get(0) == prev? c.get(cur).get(1) : c.get(cur).get(0);
}
for(int i : ans) {
fout.append(i).append(" ");
}
fout.append("\n");
}
System.out.print(fout);
}
}
|
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 11
|
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
|
bd4e9ab7c856d6aab78305a53c078606
|
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 Srhossain{
static int[] visited;
static int[][] vec;
static int[] res;
static int[] partner;
static void dfs(int u){
visited[u] = 1;
for(int i=0; i<2; i++){
int x = vec[u][i];
if(x!=0 && visited[x] == 0){
dfs(x);
partner[u]=x;
if(res[x]==5)res[u]=2;
else res[u]=5;
// System.out.println(x+" "+u);
}
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int tc=1; tc<=t; tc++){
int n = sc.nextInt();
visited = new int[n+1];
vec = new int[n+1][2];
int[] u = new int[n+1];
int[] v = new int[n+1];
int[] cntt = new int[n+1];
res = new int[n+1];
partner = new int[n+1];
int[] w = new int[n+1];
int cnt = 1;
for(int i=1; i<n; i++){
u[i] = sc.nextInt();
v[i] = sc.nextInt();
if(vec[u[i]][0] == 0)vec[u[i]][0] = v[i];
else if(vec[u[i]][1] == 0)vec[u[i]][1] = v[i];
else cnt = -1;
if(vec[v[i]][0] == 0)vec[v[i]][0] = u[i];
else if(vec[v[i]][1] == 0)vec[v[i]][1] = u[i];
else cnt = -1;
cntt[u[i]]++;
cntt[v[i]]++;
if(cntt[u[i]]>2)cnt = -1;
if(cntt[v[i]]>2)cnt = -1;
}
if(cnt == -1){System.out.print("-1\n");continue;}
res[1] = 2;
w[u[1]] = w[v[1]] = 2;
for(int i=1; i<=n; i++){
if(cntt[i]==1){
dfs(i);
break;
}
}
for(int i=1; i<n; i++){
// System.out.print("("+u[i]+" "+v[i]+")");
if(u[i] == partner[v[i]])System.out.print(res[v[i]]+" ");
if(v[i] == partner[u[i]])System.out.print(res[u[i]]+" ");
}
// for(int i=1; i<n; i++)System.out.print(res[i]+" ");
System.out.print("\n");
}
sc.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 11
|
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
|
fe617e52e0f98d356374cd41aceb9616
|
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.*;
import java.util.*;
public class Main {
static final int INF = 0x3f3f3f3f;
static final long LNF = 0x3f3f3f3f3f3f3f3fL;
static int n;static Edge[]edge;
static int[]head;static int idx;
static boolean[]vis=new boolean[200010];
static int[]map;static int[]idi;
public static void main(String[] args) throws IOException {
initReader();
int t=nextInt();
while (t--!=0){
n=nextInt();
int[]arr=new int[n+1];
init(n);
int[][]h=new int[n+1][3];
for(int i=1;i<=n-1;i++){
int a=nextInt();
int b=nextInt();
arr[a]++;arr[b]++;
add(new Edge(a,b),i);
add(new Edge(b,a),i);
h[i][1]=a;h[i][2]=b;
}
boolean g=true;
int id=0;
for(int i=1;i<=n;i++){
if(arr[i]>=3){
g=false;
break;
}
if(arr[i]==1)id=i;
}
if(!g)pw.print("-1");
else {
bul(id,2);
for(int i=1;i<=n-1;i++){
pw.print(map[i]+" ");
}
}
pw.println();
}
pw.close();
}
static class Edge{
int from;int to;int next;
public Edge(int from,int to){
this.from=from;
this.to=to;
}
}
static void add(Edge e,int c){
idi[idx]=c;
edge[idx]=e;
e.next=head[e.from];
head[e.from]=idx++;
}
static void init(int n){
edge=new Edge[2*n+10];
head=new int[2*n+10];
Arrays.fill(head,-1);
idx=0;
Arrays.fill(vis,false);
map=new int[2*n+10];
idi=new int[2*n+10];
}
static void bul(int id,int w){
vis[id]=true;
for (int i = head[id]; i !=-1; i=edge[i].next) {
int t=edge[i].to;
if(!vis[t]) {
map[idi[i]]=w;
bul(t, 5 - w);
}
}
}
/***************************************************************************************/
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter pw;
public static void initReader() throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer("");
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
// 从文件读写
// reader = new BufferedReader(new FileReader("test.in"));
// tokenizer = new StringTokenizer("");
// pw = new PrintWriter(new BufferedWriter(new FileWriter("test1.out")));
}
public static boolean hasNext() {
try {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
return false;
}
return true;
}
public static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
return null;
}
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static char nextChar() throws IOException {
return next().charAt(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 11
|
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
|
68ebf93cfb3622d30b0064937ac47c06
|
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.fill;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
*/
public class TemplateFast {
private void solveOne() {
int n = nextInt();
int[] from = new int[n];
int[] to = new int[n];
Graph_ graph_ = new Graph_();
for (int i = 0; i < n - 1; i++) {
from[i] = nextInt() - 1;
to[i] = nextInt() - 1;
graph_.addEdgeUndirected(from[i], to[i]);
}
int start = -1;
for(int vert : graph_.keySet()) {
if(graph_.get(vert).size() >= 3) {
System.out.println("-1");
return;
}
if(graph_.get(vert).size() == 1) {
start = vert;
}
}
Map<String, Integer> pairIdToAssignment = new HashMap<>();
dfs(start, -1, graph_, pairIdToAssignment, 0);
for (int i = 0; i < n - 1; i++) {
System.out.print(pairIdToAssignment.get(pairId(from[i], to[i])));
System.out.print(' ');
}
System.out.println();
}
private void dfs(int start, int parent, Graph_ graph_, Map<String, Integer> pairIdToAssignment, int deep) {
for(int to : graph_.get(start)) {
if (to != parent) {
int localAssignment = deep % 2 == 0 ? 2 : 3;
pairIdToAssignment.put(pairId(start, to), localAssignment);
pairIdToAssignment.put(pairId(to, start), localAssignment);
dfs(to, start, graph_, pairIdToAssignment, deep + 1);
}
}
}
String pairId(int from, int to) {
return from + "<>" + to;
}
private void solve() {
// calculatePrimes();
// System.out.println("Primes amount: " + primeSet.size());
// System.out.println("Primes: " + primeSet.toString());
int t = nextInt();
for (int tt = 0; tt < t; tt++) {
solveOne();
}
}
static class Graph_ extends HashMap<Integer, Set<Integer>> {
public void addEdgeUndirected(int from, int to) {
addEdgeDirected(from, to);
addEdgeDirected(to, from);
}
public void addEdgeDirected(int from, int to) {
putIfAbsent(from, new TreeSet<>());
get(from).add(to);
}
@Override
public Set<Integer> get(Object key) {
return super.getOrDefault(key, new HashSet<>());
}
}
class AssertionRuntimeException extends RuntimeException {
AssertionRuntimeException(Object expected,
Object actual, Object... input) {
super("expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
}
}
private int nextInt() {
return System.in.readInt();
}
private long nextLong() {
return System.in.readLong();
}
private String nextString() {
return System.in.readString();
}
private int[] nextIntArr(int n) {
return System.in.readIntArray(n);
}
private long[] nextLongArr(int n) {
return System.in.readLongArray(n);
}
public static void main(String[] args) {
new TemplateFast().run();
}
static class System {
private static FastInputStream in;
private static FastPrintStream out;
}
private void run() {
final boolean ONLINE_JUDGE = java.lang.System.getProperty("ONLINE_JUDGE") != null;
final boolean USE_IO = ONLINE_JUDGE;
if (USE_IO) {
System.in = new FastInputStream(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
} else {
final String nameIn = "input.txt";
final String nameOut = "output.txt";
try {
System.in = new FastInputStream(new FileInputStream(nameIn));
System.out = new FastPrintStream(new PrintStream(nameOut));
solve();
System.out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
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 FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(int[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(int[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(long[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(long[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
public FastPrintStream printf(String format, Object... args) {
return print(String.format(format, args));
}
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");
}
}
}
private static class FastInputStream {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastInputStream(InputStream stream) {
this.stream = stream;
}
public double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = readDouble();
}
return array;
}
public String[] readStringArray(int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++) {
array[i] = readString();
}
return array;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public char[][] readTable(int rowCount, int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readCharArray(columnCount);
}
return table;
}
public int[][] readIntTable(int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readIntArray(columnCount);
}
return table;
}
public double[][] readDoubleTable(int rowCount, int columnCount) {
double[][] table = new double[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readDoubleArray(columnCount);
}
return table;
}
public long[][] readLongTable(int rowCount, int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readLongArray(columnCount);
}
return table;
}
public String[][] readStringTable(int rowCount, int columnCount) {
String[][] table = new String[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readStringArray(columnCount);
}
return table;
}
public String readText() {
StringBuilder result = new StringBuilder();
while (true) {
int character = read();
if (character == '\r') {
continue;
}
if (character == -1) {
break;
}
result.append((char) character);
}
return result.toString();
}
public void readStringArrays(String[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readString();
}
}
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int peekNonWhitespace() {
while (isWhitespace(peek())) {
read();
}
return peek();
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
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 11
|
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
|
c4d74182fd0a2174cf9fac07e004ad9e
|
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.*;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
*/
public class TemplateExperimental {
private void solveOne() {
int n = nextInt();
int[] from = new int[n];
int[] to = new int[n];
Graph_ graph_ = new Graph_();
for (int i = 0; i < n - 1; i++) {
from[i] = nextInt() - 1;
to[i] = nextInt() - 1;
graph_.addEdgeUndirected(from[i], to[i]);
}
int start = -1;
for (int vert : graph_.keySet()) {
if (graph_.get(vert).size() >= 3) {
System.out.println("-1");
return;
}
if (graph_.get(vert).size() == 1) {
start = vert;
}
}
Map<String, Integer> pairIdToAssignment = new HashMap<>();
dfs(start, -1, graph_, pairIdToAssignment, 0);
for (int i = 0; i < n - 1; i++) {
System.out.print(pairIdToAssignment.get(pairId(from[i], to[i])));
System.out.print(' ');
}
System.out.println();
}
private void dfs(int start, int parent, Graph_ graph_, Map<String, Integer> pairIdToAssignment, int deep) {
for (int to : graph_.get(start)) {
if (to != parent) {
int localAssignment = deep % 2 == 0 ? 2 : 3;
pairIdToAssignment.put(pairId(start, to), localAssignment);
pairIdToAssignment.put(pairId(to, start), localAssignment);
dfs(to, start, graph_, pairIdToAssignment, deep + 1);
}
}
}
String pairId(int from, int to) {
return from + "<>" + to;
}
private void solve() {
// calculatePrimes();
// System.out.println("Primes amount: " + primeSet.size());
// System.out.println("Primes: " + primeSet.toString());
int t = nextInt();
for (int tt = 0; tt < t; tt++) {
solveOne();
}
}
static class Graph_ extends HashMap<Integer, Set<Integer>> {
public void addEdgeUndirected(int from, int to) {
addEdgeDirected(from, to);
addEdgeDirected(to, from);
}
public void addEdgeDirected(int from, int to) {
putIfAbsent(from, new TreeSet<>());
get(from).add(to);
}
@Override
public Set<Integer> get(Object key) {
return super.getOrDefault(key, new HashSet<>());
}
}
class AssertionRuntimeException extends RuntimeException {
AssertionRuntimeException(Object expected,
Object actual, Object... input) {
super("expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
}
}
private int nextInt() {
return System.in.ints();
}
private long nextLong() {
return System.in.longs();
}
// private String nextString() {
// return System.in.readString();
// }
//
// private int[] nextIntArr(int n) {
// return System.in.readIntArray(n);
// }
//
// private long[] nextLongArr(int n) {
// return System.in.readLongArray(n);
// }
public static void main(String[] args) {
new TemplateExperimental().run();
}
static class LightScanner {
private static final int BUF_SIZE = 16 * 1024;
private final InputStream stream;
private final byte[] buf = new byte[BUF_SIZE];
private int ptr;
private int len;
public LightScanner(InputStream stream) {
this.stream = stream;
}
private void reload() {
try {
ptr = 0;
len = stream.read(buf);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
private void load(int n) {
if (ptr + n <= len) return;
java.lang.System.arraycopy(buf, ptr, buf, 0, len - ptr);
len -= ptr;
ptr = 0;
try {
int r = stream.read(buf, len, BUF_SIZE - len);
if (r == -1) return;
len += r;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
private void skip() {
while (0 <= len) {
while (ptr < len && isTokenSeparator(buf[ptr])) ptr++;
if (ptr < len) return;
reload();
}
throw new NoSuchElementException("EOF");
}
public int ints() {
skip();
load(12);
int b = buf[ptr++];
boolean negate;
if (b == '-') {
negate = true;
b = buf[ptr++];
} else negate = false;
int x = 0;
for (; !isTokenSeparator(b); b = buf[ptr++]) {
if ('0' <= b && b <= '9') x = x * 10 + b - '0';
else throw new NumberFormatException("Unexpected character '" + b + "'");
}
return negate ? -x : x;
}
public long longs() {
skip();
load(20);
// int b = buf[ptr++];
// boolean negate;
// if (b == '-') {
// negate = true;
// b = buf[ptr++];
// } else negate = false;
long x = 0;
for (int b = buf[ptr++]; !isTokenSeparator(b); b = buf[ptr++]) {
x = x * 10 + b - '0';
}
// return negate ? -x : x;
return x;
}
public void close() {
try {
stream.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static boolean isTokenSeparator(int b) {
return b < 33 || 126 < b;
}
}
static class System {
private static LightScanner in;
private static FastPrintStream out;
}
private void run() {
final boolean ONLINE_JUDGE = java.lang.System.getProperty("ONLINE_JUDGE") != null;
final boolean USE_IO = ONLINE_JUDGE;
if (USE_IO) {
System.in = new LightScanner(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
} else {
final String nameIn = "input.txt";
final String nameOut = "output.txt";
try {
System.in = new LightScanner(new FileInputStream(nameIn));
System.out = new FastPrintStream(new PrintStream(nameOut));
solve();
System.out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
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 FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(int[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(int[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(long[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(long[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
public FastPrintStream printf(String format, Object... args) {
return print(String.format(format, args));
}
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");
}
}
}
}
|
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 11
|
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
|
e936bd058bc9c17a7827290f12b0c2db
|
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.fill;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
*/
public class Main {
int ASSIGNMENT_LIMIT = 100_000;
int PRIME_LIMIT = ASSIGNMENT_LIMIT * 2;
boolean[] prime = new boolean[PRIME_LIMIT + 1];
Set<Integer> primeSet = new TreeSet<>();
Graph_ graph_ = new Graph_();
void calculatePrimes() {
fill(prime, true);
prime[1] = prime[0] = false;
for (int i = 2; i <= PRIME_LIMIT; i++)
if (prime[i])
if (i * 1L * i <= PRIME_LIMIT)
for (int j = i * i; j <= PRIME_LIMIT; j += i)
prime[j] = false;
for (int i = 0; i <= PRIME_LIMIT; i++) {
if (prime[i] && i <= ASSIGNMENT_LIMIT)
primeSet.add(i);
}
for (int from : primeSet) {
for (int to : primeSet) {
if (prime[from + to]) {
graph_.addEdgeUndirected(from, to);
}
}
}
int max = 0;
int fromMax = -1;
Set<Integer> set = null;
Set<Integer> differentGroups = new TreeSet<>();
for (int neigh : graph_.keySet()) {
int group = graph_.get(neigh).size();// + 1;
System.out.println("From = " + neigh + " group = " + graph_.get(neigh));
differentGroups.add(group);
if(max < group) {
max = group;
set = graph_.get(neigh);
fromMax = neigh;
}
}
System.out.println("-------------------");
System.out.println("From = " + fromMax + " Max group = " + max);
System.out.println("Set = " + set.toString());
System.out.println(differentGroups.toString());
}
private void solveOne() {
int n = nextInt();
int[] from = new int[n];
int[] to = new int[n];
Graph_ graph_ = new Graph_();
for (int i = 0; i < n - 1; i++) {
from[i] = nextInt() - 1;
to[i] = nextInt() - 1;
graph_.addEdgeUndirected(from[i], to[i]);
}
int start = -1;
for(int vert : graph_.keySet()) {
if(graph_.get(vert).size() >= 3) {
System.out.println("-1");
return;
}
if(graph_.get(vert).size() == 1) {
start = vert;
}
}
Map<String, Integer> pairIdToAssignment = new HashMap<>();
dfs(start, -1, graph_, pairIdToAssignment, 0);
for (int i = 0; i < n - 1; i++) {
System.out.print(pairIdToAssignment.get(pairId(from[i], to[i])));
System.out.print(' ');
}
System.out.println();
}
private void dfs(int start, int parent, Graph_ graph_, Map<String, Integer> pairIdToAssignment, int deep) {
for(int to : graph_.get(start)) {
if (to != parent) {
int localAssignment = deep % 2 == 0 ? 2 : 3;
pairIdToAssignment.put(pairId(start, to), localAssignment);
pairIdToAssignment.put(pairId(to, start), localAssignment);
dfs(to, start, graph_, pairIdToAssignment, deep + 1);
}
}
}
String pairId(int from, int to) {
return from + "<>" + to;
}
private void solve() {
// calculatePrimes();
// System.out.println("Primes amount: " + primeSet.size());
// System.out.println("Primes: " + primeSet.toString());
int t = nextInt();
for (int tt = 0; tt < t; tt++) {
solveOne();
}
}
static class Graph_ extends HashMap<Integer, Set<Integer>> {
public void addEdgeUndirected(int from, int to) {
addEdgeDirected(from, to);
addEdgeDirected(to, from);
}
public void addEdgeDirected(int from, int to) {
putIfAbsent(from, new TreeSet<>());
get(from).add(to);
}
@Override
public Set<Integer> get(Object key) {
return super.getOrDefault(key, new HashSet<>());
}
}
private int nextInt() {
return System.in.ints();
}
private long nextLong() {
return System.in.longs();
}
// private String nextString() {
// return System.in.readString();
// }
//
// private int[] nextIntArr(int n) {
// return System.in.readIntArray(n);
// }
//
// private long[] nextLongArr(int n) {
// return System.in.readLongArray(n);
// }
public static void main(String[] args) {
new Main().run();
}
// static abstract class LightScannerAdapter implements AutoCloseable {
// public abstract void close();
//
// }
static class LightScanner2 {
private static final int BUF_SIZE = 16 * 1024;
private final InputStream stream;
private final byte[] buf = new byte[BUF_SIZE];
private int ptr;
private int len;
public LightScanner2(InputStream stream) {
this.stream = stream;
}
private void reload() {
try {
ptr = 0;
len = stream.read(buf);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
private void load(int n) {
if (ptr + n <= len) return;
java.lang.System.arraycopy(buf, ptr, buf, 0, len - ptr);
len -= ptr;
ptr = 0;
try {
int r = stream.read(buf, len, BUF_SIZE - len);
if (r == -1) return;
len += r;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
private void skip() {
while (0 <= len) {
while (ptr < len && isTokenSeparator(buf[ptr])) ptr++;
if (ptr < len) return;
reload();
}
throw new NoSuchElementException("EOF");
}
public int ints() {
skip();
load(12);
int b = buf[ptr++];
boolean negate;
if (b == '-') {
negate = true;
b = buf[ptr++];
} else negate = false;
int x = 0;
for (; !isTokenSeparator(b); b = buf[ptr++]) {
if ('0' <= b && b <= '9') x = x * 10 + b - '0';
else throw new NumberFormatException("Unexpected character '" + b + "'");
}
return negate ? -x : x;
}
public long longs() {
skip();
load(20);
int b = buf[ptr++];
boolean negate;
if (b == '-') {
negate = true;
b = buf[ptr++];
} else negate = false;
long x = 0;
for (; !isTokenSeparator(b); b = buf[ptr++]) {
if ('0' <= b && b <= '9') x = x * 10 + b - '0';
else throw new NumberFormatException("Unexpected character '" + b + "'");
}
return negate ? -x : x;
}
public void close() {
try {
stream.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static boolean isTokenSeparator(int b) {
return b < 33 || 126 < b;
}
}
static class System {
// private static FastInputStream in;
private static LightScanner2 in;// = new LightScanner2(inputStream);
private static FastPrintStream out;
}
private void run() {
// System.in = new FastInputStream(java.lang.System.in);
System.in = new LightScanner2(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
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 FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(int[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(int[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(long[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(long[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
public FastPrintStream printf(String format, Object... args) {
return print(String.format(format, args));
}
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");
}
}
}
}
|
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 11
|
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
|
3f1ba67c41c2ac8a142daa6acfb5c42a
|
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.fill;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
*/
//https://codeforces.com/problemset/problem/1627/C
public class MS_4_J {
int ASSIGNMENT_LIMIT = 100_000;
int PRIME_LIMIT = ASSIGNMENT_LIMIT * 2;
boolean[] prime = new boolean[PRIME_LIMIT + 1];
Set<Integer> primeSet = new TreeSet<>();
Graph_ graph_ = new Graph_();
void calculatePrimes() {
fill(prime, true);
prime[1] = prime[0] = false;
for (int i = 2; i <= PRIME_LIMIT; i++)
if (prime[i])
if (i * 1L * i <= PRIME_LIMIT)
for (int j = i * i; j <= PRIME_LIMIT; j += i)
prime[j] = false;
for (int i = 0; i <= PRIME_LIMIT; i++) {
if (prime[i] && i <= ASSIGNMENT_LIMIT)
primeSet.add(i);
}
for (int from : primeSet) {
for (int to : primeSet) {
if (prime[from + to]) {
graph_.addEdgeUndirected(from, to);
}
}
}
int max = 0;
int fromMax = -1;
Set<Integer> set = null;
Set<Integer> differentGroups = new TreeSet<>();
for (int neigh : graph_.keySet()) {
int group = graph_.get(neigh).size();// + 1;
System.out.println("From = " + neigh + " group = " + graph_.get(neigh));
differentGroups.add(group);
if(max < group) {
max = group;
set = graph_.get(neigh);
fromMax = neigh;
}
}
System.out.println("-------------------");
System.out.println("From = " + fromMax + " Max group = " + max);
System.out.println("Set = " + set.toString());
System.out.println(differentGroups.toString());
}
private void solveOne() {
int n = nextInt();
int[] from = new int[n];
int[] to = new int[n];
Graph_ graph_ = new Graph_();
for (int i = 0; i < n - 1; i++) {
from[i] = nextInt() - 1;
to[i] = nextInt() - 1;
graph_.addEdgeUndirected(from[i], to[i]);
}
int start = -1;
for(int vert : graph_.keySet()) {
if(graph_.get(vert).size() >= 3) {
System.out.println("-1");
return;
}
if(graph_.get(vert).size() == 1) {
start = vert;
}
}
Map<String, Integer> pairIdToAssignment = new HashMap<>();
dfs(start, -1, graph_, pairIdToAssignment, 0);
for (int i = 0; i < n - 1; i++) {
System.out.print(pairIdToAssignment.get(pairId(from[i], to[i])));
System.out.print(' ');
}
System.out.println();
}
private void dfs(int start, int parent, Graph_ graph_, Map<String, Integer> pairIdToAssignment, int deep) {
for(int to : graph_.get(start)) {
if (to != parent) {
int localAssignment = deep % 2 == 0 ? 2 : 3;
pairIdToAssignment.put(pairId(start, to), localAssignment);
pairIdToAssignment.put(pairId(to, start), localAssignment);
dfs(to, start, graph_, pairIdToAssignment, deep + 1);
}
}
}
String pairId(int from, int to) {
return from + "<>" + to;
}
private void solve() {
// calculatePrimes();
// System.out.println("Primes amount: " + primeSet.size());
// System.out.println("Primes: " + primeSet.toString());
int t = nextInt();
for (int tt = 0; tt < t; tt++) {
solveOne();
}
}
static class Graph_ extends HashMap<Integer, Set<Integer>> {
public void addEdgeUndirected(int from, int to) {
addEdgeDirected(from, to);
addEdgeDirected(to, from);
}
public void addEdgeDirected(int from, int to) {
putIfAbsent(from, new TreeSet<>());
get(from).add(to);
}
@Override
public Set<Integer> get(Object key) {
return super.getOrDefault(key, new HashSet<>());
}
}
class AssertionRuntimeException extends RuntimeException {
AssertionRuntimeException(Object expected,
Object actual, Object... input) {
super("expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
}
}
private int nextInt() {
return System.in.readInt();
}
private long nextLong() {
return System.in.readLong();
}
private String nextString() {
return System.in.readString();
}
private int[] nextIntArr(int n) {
return System.in.readIntArray(n);
}
private long[] nextLongArr(int n) {
return System.in.readLongArray(n);
}
public static void main(String[] args) {
new MS_4_J().run();
}
static class System {
private static FastInputStream in;
private static FastPrintStream out;
}
private void run() {
System.in = new FastInputStream(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
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 FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(int[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(int[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
public FastPrintStream printf(String format, Object... args) {
return print(String.format(format, args));
}
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");
}
}
}
private static class FastInputStream {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastInputStream(InputStream stream) {
this.stream = stream;
}
public double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = readDouble();
}
return array;
}
public String[] readStringArray(int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++) {
array[i] = readString();
}
return array;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public void readIntArrays(int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readInt();
}
}
}
public void readLongArrays(long[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readLong();
}
}
}
public void readDoubleArrays(double[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readDouble();
}
}
}
public char[][] readTable(int rowCount, int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readCharArray(columnCount);
}
return table;
}
public int[][] readIntTable(int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readIntArray(columnCount);
}
return table;
}
public double[][] readDoubleTable(int rowCount, int columnCount) {
double[][] table = new double[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readDoubleArray(columnCount);
}
return table;
}
public long[][] readLongTable(int rowCount, int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readLongArray(columnCount);
}
return table;
}
public String[][] readStringTable(int rowCount, int columnCount) {
String[][] table = new String[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readStringArray(columnCount);
}
return table;
}
public String readText() {
StringBuilder result = new StringBuilder();
while (true) {
int character = read();
if (character == '\r') {
continue;
}
if (character == -1) {
break;
}
result.append((char) character);
}
return result.toString();
}
public void readStringArrays(String[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readString();
}
}
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int peekNonWhitespace() {
while (isWhitespace(peek())) {
read();
}
return peek();
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
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 11
|
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
|
91388b0f9a5d273023a58fa429b5743d
|
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 int t, n;
public static ArrayList<Edge> adj[];
public static HashSet<Integer> used[];
public static int[] edges;
public static boolean[] visited;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
t = Integer.parseInt(br.readLine());
for(int test = 0; test < t; test++) {
n = Integer.parseInt(br.readLine());
adj = new ArrayList[n];
used = new HashSet[n];
edges = new int[n - 1];
visited = new boolean[n];
for(int i = 0; i < n; i++) adj[i] = new ArrayList<Edge>();
for(int i = 0; i < n; i++) used[i] = new HashSet<Integer>();
for(int i = 0; i < n - 1; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int num1 = Integer.parseInt(st.nextToken()) - 1;
int num2 = Integer.parseInt(st.nextToken()) - 1;
adj[num1].add(new Edge(num2, i));
adj[num2].add(new Edge(num1, i));
}
boolean works = true;
Stack<Integer> s = new Stack<Integer>();
s.add(0);
while(!s.isEmpty()) {
int p = s.pop();
if(!visited[p]) {
visited[p] = true;
if(adj[p].size() > 2) {
works = false;
break;
} else {
for(Edge e: adj[p]) {
if(edges[e.i] == 0) {
if(!used[p].contains(2)) {
edges[e.i] = 2;
used[p].add(2);
used[e.c].add(2);
} else if(!used[p].contains(3)) {
edges[e.i] = 3;
used[p].add(3);
used[e.c].add(3);
}
}
if(!visited[e.c]) s.add(e.c);
}
}
}
}
if(works) {
for(int a: edges) pw.print(a + " ");
pw.println();
} else pw.println(-1);
}
pw.flush();
pw.close();
}
public static class Edge{
private int c, i;
public Edge(int c, int i) {
this.c = c;
this.i = i;
}
public String toString() {
return this.c + " " + this.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 11
|
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
|
5a8ad74d70456d8f3c0fafd946165908
|
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 int t, n;
public static ArrayList<Edge> adj[];
public static int[] edges;
public static boolean[] visited;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
t = Integer.parseInt(br.readLine());
for(int test = 0; test < t; test++) {
n = Integer.parseInt(br.readLine());
adj = new ArrayList[n];
edges = new int[n - 1];
visited = new boolean[n];
for(int i = 0; i < n; i++) adj[i] = new ArrayList<Edge>();
for(int i = 0; i < n - 1; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int num1 = Integer.parseInt(st.nextToken()) - 1;
int num2 = Integer.parseInt(st.nextToken()) - 1;
adj[num1].add(new Edge(num2, i));
adj[num2].add(new Edge(num1, i));
}
int start = 0;
for(int i = 0; i < n; i++) {
if(adj[i].size() == 1) {
start = i;
break;
}
}
Stack<Integer> s = new Stack<Integer>();
boolean works = true;
boolean num = true;
s.add(start);
while(!s.isEmpty()) {
if(!works) break;
int p = s.pop();
if(!visited[p]) {
visited[p] = true;
if(adj[p].size() > 2) works = false;
else {
for(Edge e: adj[p]) {
if(!visited[e.c]) {
if(num) edges[e.i] = 2;
else edges[e.i] = 3;
num = !num;
s.add(e.c);
}
}
}
}
}
if(works) {
for(int a: edges) pw.print(a + " ");
pw.println();
} else pw.println(-1);
}
pw.flush();
pw.close();
}
public static class Edge{
private int c, i;
public Edge(int c, int i) {
this.c = c;
this.i = i;
}
public String toString() {
return this.c + " " + this.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 11
|
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
|
601cd692a402cd2b4853e59ed3c367b7
|
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 11
|
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
|
8c771d902b821348f4582d436f8f04e0
|
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 notAssigningCF {
public static void main (String[]args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer (f.readLine());
int testCases = Integer.parseInt(st.nextToken());
for (int i = 0; i < testCases; i++) {
st = new StringTokenizer (f.readLine());
int nodeNumber = Integer.parseInt(st.nextToken());
Hashtable <Integer, ArrayList<Integer>> graph = new Hashtable <Integer, ArrayList<Integer>>();
for (int j = 1; j <= nodeNumber; j++) {
graph.put(j, new ArrayList<Integer>());
}
int tempI = nodeNumber - 1;
int [] firstNodes = new int [tempI];
int [] secondNodes = new int [tempI];
for (int j = 0; j < tempI; j++) {
st = new StringTokenizer (f.readLine());
int firstNode = Integer.parseInt(st.nextToken());
int secondNode = Integer.parseInt(st.nextToken());
firstNodes[j] = firstNode;
secondNodes[j] = secondNode;
ArrayList<Integer> temp = graph.get(firstNode);
temp.add(secondNode);
graph.put(firstNode, temp);
ArrayList<Integer> tempTwo = graph.get(secondNode);
tempTwo.add(firstNode);
graph.put(secondNode, tempTwo);
}
boolean works = true;
int startingNode = -1;
for (int j = 1; j <= nodeNumber; j++) {
if (graph.get(j).size() >= 3) {
works = false;
}
if (graph.get(j).size() == 1) {
startingNode = j;
}
}
if (!works) {
System.out.println(-1);
continue;
}
int currentNode = startingNode;
boolean even = false;
Hashtable <Integer, Boolean> nodeSeen = new Hashtable <Integer, Boolean>();
Hashtable <Integer, Hashtable<Integer, Boolean>> edgesBank = new Hashtable <Integer, Hashtable<Integer, Boolean>>();
for (int j = 1; j <= nodeNumber; j++) {
edgesBank.put(j, new Hashtable <Integer, Boolean>());
}
while (true) {
int childNode = -1;
if (graph.get(currentNode).size() == 1) {
childNode = graph.get(currentNode).get(0);
}
else {
if (nodeSeen.containsKey(graph.get(currentNode).get(0))) {
childNode = graph.get(currentNode).get(1);
}
else {
childNode = graph.get(currentNode).get(0);
}
}
if (even) {
Hashtable <Integer, Boolean> temp = edgesBank.get(currentNode);
temp.put(childNode, false);
edgesBank.put(currentNode, temp);
even = false;
}
else {
Hashtable <Integer, Boolean> temp = edgesBank.get(currentNode);
temp.put(childNode, true);
edgesBank.put(currentNode, temp);
even = true;
}
nodeSeen.put(currentNode, true);
if (nodeSeen.size() == nodeNumber - 1) {
break;
}
currentNode = childNode;
}
for (int j = 0; j < tempI; j++) {
if (edgesBank.get(firstNodes[j]).get(secondNodes[j]) == null) {
if (edgesBank.get(secondNodes[j]).get(firstNodes[j]) == true) {
System.out.print("2 ");
}
else {
System.out.print("3 ");
}
}
else {
if (edgesBank.get(firstNodes[j]).get(secondNodes[j]) == true) {
System.out.print("2 ");
}
else {
System.out.print("3 ");
}
}
}
System.out.println("");
}
f.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 11
|
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
|
e2071774659d845cfa8874a9d9a1d8e0
|
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.Arrays;
import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int lines = s.nextInt();
s.nextLine();
for (int i = 0; i < lines; i += 1) {
solve(s.nextInt(), s);
}
}
public static void solve(int n, Scanner s) {
int[][] node = new int[n][4];
int[][] edge = new int[n - 1][2];
int a, b;
boolean skip = false;
for (int i = 0; i < n - 1; i++) {
a = s.nextInt() - 1;
b = s.nextInt() - 1;
if (node[a][2] == 2 || node[b][2] == 2) {
skip = true;
}
if (!skip) {
node[a][node[a][2]++] = i;
node[b][node[b][2]++] = i;
edge[i] = new int[]{a, b};
}
}
if (skip) {
System.out.println(-1);
return;
}
int ind = -1;
for (int i = 0; i < n; i++) {
if (node[i][2] == 1) ind = i;
}
int[] val = new int[n - 1];
int nE;
int nInd;
for (int i = 0; i < n - 1; i++) {
nE = Math.max(node[ind][0], node[ind][1]);
val[nE] = i % 2 == 0 ? 2 : 3;
nInd = edge[nE][0] != ind ? edge[nE][0] : edge[nE][1];
if (node[nInd][0] == nE) node[nInd][0] = 0;
if (node[nInd][1] == nE) node[nInd][1] = 0;
ind = nInd;
}
System.out.println(Arrays.toString(val).replace("[", "").replace("]", "").replace(",", ""));
}
}
|
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 11
|
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
|
5cd2261376e272b98b7980fcc45b07fe
|
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: cypher70
*** Date: 04.03.22
*/
import java.io.*;
import java.util.*;
public class 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;
}
int[] readArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
}
static String reverse(String s) {
StringBuilder rev = new StringBuilder();
for (int i = s.length()-1; i >= 0; i--) {
rev.append(s.charAt(i));
}
return rev.toString();
}
static void debug(int[] arr) {
for (int e: arr) {
System.out.print(e + " ");
}
System.out.println();
}
/*
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< HELPER FUNCTIONS ABOVE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
static class pair {
int a, b;
public pair(int a, int b) {
this.a = a;
this.b = b;
}
}
static boolean dfs(int node, ArrayList<ArrayList<pair>> adj, boolean[] visited, int[] ans, int pw) {
visited[node] = true;
if (adj.get(node).size() > 2) return false;
for (pair e: adj.get(node)) {
if (visited[e.a]) continue;
ans[e.b] = pw == 5 ? 2 : 5;
if (!dfs(e.a, adj, visited, ans, ans[e.b])) return false;
}
return true;
}
public static void main(String[] args) {
FastReader f = new FastReader();
int t = f.nextInt();
while (t --> 0) {
int n = f.nextInt();
ArrayList<ArrayList<pair>> adj = new ArrayList<>(n+1);
for (int i = 0; i <= n; i++) {
adj.add(i, new ArrayList<>());
}
for (int i = 0; i < n-1; i++) {
int u = f.nextInt();
int v = f.nextInt();
adj.get(u).add(new pair(v, i));
adj.get(v).add(new pair(u, i));
}
int[] ans = new int[n-1];
boolean[] visited = new boolean[n+1];
boolean ok = adj.get(1).size() > 2 ? false : true;
visited[1] = true;
ans[adj.get(1).get(0).b] = 2;
ok &= dfs(adj.get(1).get(0).a, adj, visited, ans, 2);
if (adj.get(1).size() > 1) {
ans[adj.get(1).get(1).b] = 5;
ok &= dfs(adj.get(1).get(1).a, adj, visited, ans, 5);
}
if (!ok) {
System.out.println(-1);
continue;
}
for (int e: ans) {
System.out.print(e + " ");
}
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 11
|
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
|
cc8efac1b2145626a11efe505f9f6e50
|
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
|
//jai Shree Krishna
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Collections;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.List;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A{
// author: Tarun Verma
static FastScanner sc = new FastScanner();
static int inf = Integer.MAX_VALUE;
static long mod = 1000000007;
static BufferedWriter output = new BufferedWriter(
new OutputStreamWriter(System.out));
static PrintWriter out=new PrintWriter(System.out);
/* Common Mistakes By Me
* make sure to read the bottom part of question
* special cases (n=1?)
* in BIT MASKING try don't forget a^b=c == a^c=b
* READ READ AND READ THE Test Cases VERY PROPERLY AND NEVER BE OVERCONFIDENT
* Always Reset vis,adj array upto n+1 otherwise can cause TLE
* Try to see array from back in increase and decrease questions
*/
static List<pair> adj [] ;
static boolean dfsBipartite(int node, int vis[], int n, int ans[]) {
if(vis[node] == -1) {
vis[node] = 1;
}
for(pair i: adj[node]) {
if(vis[i.fr] == -1) {
vis[i.fr] = 1 ^ vis[node];
ans[i.sc] = vis[i.fr];
if(!dfsBipartite(i.fr,vis, n, ans)) return false;
} else {
if(vis[i.fr] == vis[node]) return false;
}
}
return true;
}
public static void solve() {
int n = sc.nextInt();
adj = new List[n];
for(int i =0;i<n;i++) {
adj[i] = new ArrayList<>();
}
ArrayList<pair> a = new ArrayList<pair>();
for(int i =0;i<n-1;i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
a.add(new pair(u, v));
adj[u].add(new pair(v, i));
adj[v].add(new pair(u, i));
}
for(int i =0;i<n;i++) {
if(adj[i].size() > 2) {
System.out.println(-1);
return;
}
}
int node = -1;
for(int i=0;i<n;i++) {
if(adj[i].size() == 1) {
node = i;
break;
}
}
int vis[] = new int[n];
Arrays.fill(vis, -1);
int ans [] = new int[n-1];
dfsBipartite(node, vis, n, ans);
for(int i: ans) {
if(i == 0) {
System.out.print(2 + " ");
} else {
System.out.print(3 + " ");
}
}
System.out.println();
}
public static void main(String[] args) {
int t = 1;
t = sc.nextInt();
outer: for (int tt = 0; tt < t; tt++) {
solve();
}
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////DO NOT BELOW THIS LINE //////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
static Comparator<pair> comp = new Comparator<pair>() {
@Override
public int compare(pair o1, pair o2) {
if(o1.fr == o2.fr) {
return o1.sc - o2.sc;
}
return o1.fr - o2.fr;
}
};
static int max(int a, int b) { return Math.max(a, b);}
static int min(int a, int b) {return Math.min(a, b);}
static long max(long a, long b){return Math.max(a, b);}
static long min(long a, long b) {return Math.min(a, b);}
static void sort(int arr[]) {
ArrayList<Integer> a = new ArrayList<Integer>();
for(int i: arr) a.add(i);
Collections.sort(a);
for(int i=0;i<arr.length;i++) arr[i] = a.get(i);
}
static void sort(long arr[]) {
ArrayList<Long> a = new ArrayList<Long>();
for(long i: arr) a.add(i);
Collections.sort(a);
for(int i=0;i<arr.length;i++) arr[i] = a.get(i);
}
static int abs(int a) {return Math.abs(a);}
static long abs(long a) {return Math.abs(a);}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static class 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[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] read2dArray(int n, int m) {
int arr[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = nextInt();
}
}
return arr;
}
ArrayList<Integer> readArrayList(int n) {
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
int a = nextInt();
arr.add(a);
}
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
}
static class pair {
int fr, sc;
pair(int fr, int sc) {
this.fr = fr;
this.sc = sc;
}
}
////////////////////////////////////////////////////////////////////////////////////
}
|
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 11
|
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
|
6f948eb5905ead41a1b0b5c58f0b71d7
|
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 NotAssign {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
private static LinkedList<Pair> adj[];
private static boolean vis[];
private static int val[];
private static int ans[];
public static void dfs(int v) {
if (vis[v])
return;
vis[v] = true;
Iterator<Pair> iterator = adj[v].listIterator();
while (iterator.hasNext()) {
Pair pair = iterator.next();
int idx = pair.index;
int child = pair.node;
if (!vis[child]) {
if (v == 1) {
if (val[v] == 0) {
val[v] = 1;
ans[idx] = 2;
val[child] = 2;
} else {
ans[idx] = 5;
val[child] = 5;
}
} else {
if (val[v] == 2) {
ans[idx] = 5;
val[child] = 5;
} else {
ans[idx] = 2;
val[child] = 2;
}
}
dfs(child);
}
}
}
public static void main(String[] args) throws IOException {
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
int n = Integer.parseInt(br.readLine());
adj = new LinkedList[n + 1];
val = new int[n + 1];
ans = new int[n];
vis = new boolean[n + 1];
for (int i = 1; i <= n; i++) {
adj[i] = new LinkedList<>();
}
for (int i = 0; i < n - 1; i++) {
String uv[] = br.readLine().split(" ");
int u = Integer.parseInt(uv[0]);
int v = Integer.parseInt(uv[1]);
adj[u].add(new Pair(i, v));
adj[v].add(new Pair(i, u));
}
boolean can = true;
for (int i = 1; i <= n; i++) {
int l = adj[i].size();
if (l > 2) {
can = false;
break;
}
}
if (can == false) {
bw.write("-1\n");
continue;
}
dfs(1);
for (int i = 0; i < n-1; i++) {
bw.write(ans[i] + " ");
}
bw.newLine();
}
bw.flush();
}
}
class Pair {
int index, node;
Pair(int index, int node) {
this.index = index;
this.node = node;
}
}
|
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 11
|
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
|
aad05477de0a0a943c10573c006805ce
|
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.*;
/* Name of the class has to be "Main" only if the class is public. */
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 class Pair{
int val,wt;
Pair(int x, int y) {
val=x;
wt=y;
}
}
public static void main (String[] args) throws java.lang.Exception
{
FastReader scn = new FastReader();
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int t = scn.nextInt();
while (t>0) {
int n = scn.nextInt();
HashMap<Integer,HashSet<Pair>> m1 =new HashMap<>();
int[][] a = new int[n-1][3];
int ans = 0;
for(int i=0;i<n-1;i++){
int u = scn.nextInt();
int v = scn.nextInt();
if(!m1.containsKey(u)){
m1.put(u,new HashSet<>());
}
if(!m1.containsKey(v)){
m1.put(v,new HashSet<>());
}
m1.get(u).add(new Pair(v,i));
m1.get(v).add(new Pair(u,i));
if(m1.get(v).size()>=3 || m1.get(u).size()>=3){
ans = -1;
}
a[i][0]= Math.min(u,v);
a[i][1]= Math.max(u,v);
a[i][2] = i;
}
if(ans==-1){
System.out.println(ans);
}else{
int[] b = new int[n-1];
int c1 = m1.get(1).size();
boolean[] d= new boolean[n+1];
Queue<Pair> q1= new LinkedList<>();
q1.add(new Pair(1,-1));
while(!q1.isEmpty()){
Pair p = q1.remove();
d[p.val]= true;
for(Pair next: m1.get(p.val)){
if(d[next.val]){
continue;
}
int tar = next.wt;
if(tar!=-1){
if(p.wt==2){
b[tar]=3;
}else if(p.wt==3){
b[tar] = 2;
}else if(p.wt ==-1){
b[tar]= 2;
p.wt = 2;
}
q1.add(new Pair(next.val,b[tar]));
}
}
}
for(int i=0;i<n-1;i++){
System.out.print(b[i]+" ");
}
System.out.println();
}
t--;
}
}
}
|
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 11
|
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
|
74a8376a6cecba569d0f846030eecf49
|
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.text.*;
import java.io.*;
public class Main {
static long sum = 0;
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter writer = new PrintWriter(System.out);
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
int max = Integer.MIN_VALUE;
int arr[][] = new int[n-1][2];
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i = 0; i <= n; i++)adj.add(new ArrayList<>());
for(int i = 0; i < n-1; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
adj.get(a).add(b);
adj.get(b).add(a);
if(a<b) {
arr[i][0] = a;
arr[i][1] = b;
}else {
arr[i][0] = b;
arr[i][1] = a;
}
}
int oneIndex = 1;
for(int i = 1; i <= n; i++) {
ArrayList<Integer> list = adj.get(i);
max = Math.max(max, list.size());
if(list.size()==1)oneIndex=i;
}
boolean visited[] = new boolean[n+1];
HashMap<Pair, Integer> map = new HashMap<>();
if(max >= 3)writer.println(-1);
else {
dfs(adj,map,oneIndex, visited,2);
for(int oo[] : arr) {
Pair pp = new Pair(oo[0], oo[1]);
writer.print(map.get(pp)+" ");
}
writer.println();
}
}
writer.flush();
writer.close();
}
private static void dfs(ArrayList<ArrayList<Integer>> adj, HashMap<Pair, Integer> map , int index, boolean[] visited, int val) {
visited[index] = true;
for(int j : adj.get(index)) {
if(!visited[j]) {
Pair pp = new Pair(index,j);
if(index > j) {
pp.a = j;
pp.b = index;
}
map.put(pp, val);
if(val==2)val=3;
else val=2;
dfs(adj,map,j,visited, val);
}
}
}
private static long power (long a, long n, long p) {
long res = 1;
while(n!=0) {
if(n%2==1) {
res=(res*a)%p;
n--;
}else {
a= (a*a)%p;
n/=2;
}
}
return res;
}
private static boolean isPrime(int c) {
for (int i = 2; i*i <= c; i++) {
if(c%i==0)return false;
}
return true;
}
private static int find(int a , int arr[]) {
if(arr[a] != a) return arr[(int)a] = find(arr[(int)a], arr);
return arr[(int)a];
}
private static void union(int a, int b, int arr[]) {
int aa = find(a,arr);
int bb = find(b, arr);
arr[aa] = bb;
}
private static int gcd(int a, int b) {
if(a==0)return b;
return gcd(b%a, a);
}
public static int[] readIntArray(int size, FastReader s) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = s.nextInt();
}
return array;
}
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;
}
}
}
class SegmentTree{
int size;
long arr[];
SegmentTree(int n){
size = 1;
while(size<n)size*=2;
arr = new long[size*2];
}
public void build(int input[]) {
build(input, 0,0, size);
}
public void set(int i, int v) {
set(i,v,0,0,size);
}
// sum from l + r-1
public long sum(int l, int r) {
return sum(l,r,0,0,size);
}
private void build(int input[], int x, int lx, int rx) {
if(rx-lx==1) {
if(lx < input.length )
arr[x] = 1;
return;
}
int mid = (lx+rx)/2;
build(input, 2*x+1, lx, mid);
build(input,2*x+2,mid,rx);
arr[x] = arr[2*x+1] + arr[2*x+2];
}
private void set(int i, int v, int x, int lx, int rx) {
if(rx-lx==1) {
arr[x]++;
return;
}
int mid = (lx+rx)/2;
if(i < mid) set(i, v, 2*x+1, lx, mid);
else set(i,v,2*x+2,mid,rx);
arr[x] = arr[2*x+1] + arr[2*x+2];
}
private long sum(int l, int r, int x, int lx, int rx) {
if(lx>=r || rx <= l)return 0;
if(lx>=l && rx <= r)return arr[x];
int mid = (lx+rx)/2;
long s1 = sum(l,r,2*x+1,lx,mid);
long s2 = sum(l,r,2*x+2,mid,rx);
return s2+s1;
}
// int first_above(int v, int l, int x, int lx, int rx) {
// if(arr[x].a<v)return -1;
// if(rx<=l)return -1;
// if(rx-lx==1)return lx;
// int m = (lx+rx)/2;
// int res = first_above(v,l,2*x+1,lx,m);
// if(res==-1)res = first_above(v,l,2*x+2,m,rx);
// return res;
//
// }
}
class Pair implements Comparable<Pair>{
long a;
long b;
long c;
Pair(long a, long b, long c){
this.a = a;
this.b = b;
this.c = c;
}
Pair(long a, long b){
this.a = a;
this.b = b;
this.c = 0;
}
@Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null || obj.getClass()!= this.getClass()) return false;
Pair pair = (Pair) obj;
return (pair.a == this.a && pair.b == this.b && pair.c == this.c);
}
@Override
public int hashCode()
{
// return Objects.hash(a,b);
return new Long(a).hashCode() * 31 + new Long(b).hashCode();
}
@Override
public int compareTo(Pair o) {
if(o.a != this.a) return Long.compare(this.a, o.a);
else
return Long.compare(this.b, o.b);
}
@Override
public String toString() {
return this.a + " " + this.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 11
|
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
|
e46ab47425517c3eb5d98af22da4ea4b
|
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.*;
// Ctrl + Alt + F for formatting code
public class setup {
int[][] four_dir = new int[][] {{1, 0}, { -1, 0}, {0, -1}, {0, 1}};
static int mod = (int)1e9 + 7;
static long gcd(long a, long b, long n) {
if (a == b) {
return (power(a, n, mod) + power(b, n, mod)) % mod;
}
long num = a - b, max = 1;
for (int i = 1; i * i <= num; i++) {
if (num % i == 0) {
if ((power(a, n, i) + power(b, n, i)) % i == 0) {
max = Math.max(max, i);
}
if ((power(a, n, num / i) + power(b, n, num / i)) % (num / i) == 0) {
max = Math.max(max, num / i);
break;
}
}
}
return (max % mod);
}
static long power(long a, long n, long d) {
a = a % d;
long res = 1;
while (n > 0) {
if (n % 2 == 1) {
res = ((res % d) * (a % d)) % d;
} else {
a = ((a % d) * (a % d)) % d;
n /= 2;
}
}
return res % d;
}
public static int findParent(int u, int[] parent) {
if (u == parent[u])return u;
int x = findParent(parent[u], parent);
parent[u] = x;
return x;
}
public static boolean equi(String s1, String s2) {
int[] freq = new int[26];
for (int i = 0; i < s1.length(); i++) {
freq[s1.charAt(i) - 'a']++;
}
for (int i = 0; i < s2.length(); i++) {
freq[s2.charAt(i) - 'a']++;
if (freq[s2.charAt(i) - 'a'] >= 2)return true;
}
return false;
}
static class pair {
long count;
int p;
pair(int count, int p) {
this.count = count;
this.p = p;
}
}
public static long kdanes(List<Integer> nums) {
long gm = 0, currMax = 0;
for (int i = 0; i < nums.size(); i++) {
currMax = Math.max(nums.get(i), currMax + nums.get(i));
gm = Math.max(gm, currMax);
}
return gm;
}
// public static boolean[] visited;
public static List<List<Integer>> graph;
public static int[] color;
public static int cnt = 0;
public static long[] c;
// public static int[] ans;
static class Edge {
int v;
int index;
Edge(int v, int index) {
this.v = v;
this.index = index;
}
}
static int[] primes = new int[] {5, 2};
// static Long[][] dp=new Long[30001][30001];
// static int[] nums=new int[30001];
public static boolean[] visited = new boolean[2 * (int)1e5 + 1];
public static void main(String[] args) throws IOException {
try {
System.setIn(new FileInputStream("input1.txt"));
System.setOut(new PrintStream(new FileOutputStream("output1.txt")));
} catch (Exception e) {
System.err.println(e);
}
FastScanner fs = new FastScanner();
PrintWriter output = new PrintWriter(System.out);
int t = fs.nextInt();
while (t-- > 0) {
int n = fs.nextInt();
List<List<Edge>> graph = new ArrayList<>();
for (int i = 0; i < n + 1; i++)graph.add(new ArrayList<>());
int[] ans = new int[n - 1];
int[] indegree = new int[n + 1];
boolean flag = false;
for (int i = 0; i < n - 1; i++) {
int[] uv = fs.intArray();
int u=uv[0];
int v=uv[1];
graph.get(u).add(new Edge(v, i));
graph.get(v).add(new Edge(u, i));
indegree[u]++;
indegree[v]++;
if (indegree[u] >= 3 || indegree[v] >= 3) {
flag = true;
}
}
if (flag) {
output.println(-1);
continue;
}
dfs(ans, graph, -1, 1, 0);
for (int ele : ans) {
output.print(ele + " ");
}
output.println();
}
output.flush();
}
public static void dfs(int[] ans, List<List<Edge>> graph, int parent, int src, int index) {
for (Edge e : graph.get(src)) {
if (e.v != parent) {
ans[e.index] = primes[index];
dfs(ans, graph, src, e.v, index == 0 ? 1 : 0);
index++;
}
}
}
// public static boolean[] kosaraju(int v, ArrayList<ArrayList<Integer>> adj)
// {
// Stack<Integer> st=topoSort(adj,v);
// List<List<Integer>> tGraph=transpose(adj,v);
// boolean[] visited=new boolean[v];
// int cnt=0;
// boolean[] ans=new boolean[v];
// Arrays.fill(ans,true);
// while(st.size()!=0){
// int c=st.pop();
// if(!visited[c]){
// int cc=dfs(tGraph,visited,c)+1;
// if(cc==1){
// ans[c]=false;
// }
// }
// }
// return ans;
// }
// public static void topo(Stack<Integer> st,ArrayList<ArrayList<Integer>> adj,boolean[] visited,int n,int src){
// visited[src]=true;
// for(int child:adj.get(src)){
// if(!visited[child])
// topo(st,adj,visited,n,child);
// }
// st.add(src);
// }
// public static Stack<Integer> topoSort(ArrayList<ArrayList<Integer>> adj,int n){
// Stack<Integer> st=new Stack<>();
// boolean[] visited=new boolean[n];
// for(int i=1;i<n;i++){
// if(!visited[i])
// topo(st,adj,visited,n,i);
// }
// return st;
// }
// public static List<List<Integer>> transpose(ArrayList<ArrayList<Integer>> adj,int n){
// List<List<Integer>> graph=new ArrayList<>();
// for(int i=0;i<n;i++){
// graph.add(new ArrayList<>());
// }
// for(int i=0;i<adj.size();i++){
// ArrayList<Integer> childs=adj.get(i);
// for(int j=0;j<childs.size();j++){
// graph.get(childs.get(j)).add(i);
// }
// }
// return graph;
// }
// public static int dfs(List<List<Integer>> graph,boolean[] visited,int src){
// visited[src]=true;
// int count=0;
// for(int child:graph.get(src)){
// if(!visited[child]){
// count+=dfs(graph,visited,child)+1;
// }
// }
// return count;
// }
// public static String findOrder(String [] dict, int n, int k)
// {
// // Write your code here
// List<List<Integer>> graph=new ArrayList<>();
// for(int i=0;i<k;i++)graph.add(new ArrayList<>());
// int[] indegree=new int[k];
// for(int i=0;i<n-1;i++){
// String first=dict[i];
// String next=dict[i+1];
// for(int j=0;j<Math.min(first.length(),next.length());j++){
// if(first.charAt(j)!=next.charAt(j)){
// graph.get(first.charAt(j)-'a').add(next.charAt(j)-'a');
// indegree[next.charAt(j)-'a']++;
// break;
// }
// }
// }
// LinkedList<Integer> que=new LinkedList<>();
// String ans="";
// for(int i=0;i<k;i++){
// if(indegree[i]==0){
// ans+=(char)(i+'a');
// que.add(i);
// }
// }
// while(que.size()!=0){
// int node=que.removeFirst();
// for(int child:graph.get(node)){
// indegree[child]--;
// if(indegree[child]==0){
// que.add(child);
// ans+=(char)(child+'a');
// }
// }
// }
// return ans;
// }
// static boolean biPartite( int src, int cc, int n) {
// color[src] = cc;
// if (src <= n) {
// c[cc]++;
// }
// visited[src] = true;
// for (int child : graph.get(src)) {
// if (!visited[child]) {
// if (!biPartite(child, cc == 1 ? 0 : 1, n))return false;
// } else {
// if (color[child] == color[src])return false;
// }
// }
// return true;
// }
// public static void dfs(List<List<Integer>> graph, int src, int par, int[] color, int pc) {
// if (color[src - 1] != pc) {
// pc = color[src - 1];
// cnt++;
// }
// for (int child : graph.get(src)) {
// if (child != par) {
// dfs(graph, child, src, color, pc);
// }
// }
// }
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
boolean hasNext() {
return st.hasMoreTokens();
}
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {}
return st.nextToken();
}
String[] nextArray() throws IOException {
return br.readLine().split(" ");
}
int[] intArray() throws IOException {
return Arrays.stream(br.readLine().split("\\s")).mapToInt(Integer::parseInt).toArray();
}
long[] longArray() throws IOException {
return Arrays.stream(br.readLine().split("\\s")).mapToLong(Long::parseLong).toArray();
}
int nextInt() {
return Integer.parseInt(next());
}
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 11
|
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
|
d4f09833de33187d86d4550f41014aad
|
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.MessageFormat;
import java.util.*;
public class C {
class TreeEdge {
int from;
int to;
int weight;
public TreeEdge(int from, int to, int w) {
this.from = from;
this.to = to;
this.weight = w;
}
}
class Tree {
Map<Integer, List<TreeEdge>> adj;
List<TreeEdge> orderedEdges;
public Tree() {
orderedEdges = new ArrayList<>();
adj = new HashMap<>();
}
public int getMaxDegree() {
int maxD = -1;
for(Integer v: adj.keySet()) {
maxD = Integer.max(maxD, adj.get(v).size());
}
return maxD;
}
public void traverseSpecial(int srcNodeID) {
// System.out.println(srcNodeID);
Queue<Integer> bfsOrder = new ArrayDeque<>();
Set<Integer> visited = new HashSet<>();
bfsOrder.add(srcNodeID);
visited.add(srcNodeID);
int PRIME_2 = 2;
int PRIME_3 = 3;
boolean use2 = true;
while(!bfsOrder.isEmpty()) {
int curNode = bfsOrder.poll();
if(adj.get(curNode).size() > 2) {
throw new RuntimeException("found degree more than 2!");
}
// System.out.print(curNode + ": ");
for(TreeEdge edge: adj.get(curNode)) {
int to = (edge.to == curNode)?edge.from:edge.to;
if(!visited.contains(to)) {
bfsOrder.add(to);
visited.add(to);
}
else {
continue;
}
// System.out.print(to + " ");
if(use2) {
edge.weight = PRIME_2;
use2 = false;
}
else {
edge.weight = PRIME_3;
use2 = true;
}
}
// System.out.println();
}
}
public void addEdge(int from, int to) {
TreeEdge e = new TreeEdge(from,to,0);
orderedEdges.add(e);
if(!adj.containsKey(from)) {
adj.put(from, new ArrayList<>());
}
adj.get(from).add(e);
if(!adj.containsKey(to)) {
adj.put(to, new ArrayList<>());
}
adj.get(to).add(e);
}
public int getAnyLeaf() {
for(Integer v: adj.keySet()) {
if(adj.get(v).size() == 1) {
return v;
}
}
return -1;
}
}
private SimpleInputReader in;
private SimpleOutputWriter out;
public C(Reader r, Writer w) {
in = new SimpleInputReader(r);
out = new SimpleOutputWriter(w);
}
public void closeIO() throws Exception {
in.close();
out.close();
}
private boolean hasMaxDeg2(Tree tree) {
return tree.getMaxDegree() <= 2;
}
public void solve() throws Exception {
int te = in.nextInt();
for(int i = 0; i < te; i++) {
int v = in.nextInt();
Tree tree = new Tree();
for(int j = 0; j < v-1; j++) {
int f = in.nextInt();
int t = in.nextInt();
tree.addEdge(f,t);
}
if(!hasMaxDeg2(tree)) {
out.writeLine(-1);
continue;
}
int leafNode = tree.getAnyLeaf();
tree.traverseSpecial(leafNode);
for(TreeEdge e: tree.orderedEdges) {
out.writeTokens(e.weight, " ");
}
out.newLine();
}
}
public static void main(String[] args) throws Exception {
Reader r = new InputStreamReader(System.in);
Writer w = new PrintWriter(System.out);
C sol = new C(r, w);
sol.solve();
sol.closeIO();
}
public static class SimpleInputReader implements AutoCloseable{
private BufferedReader reader;
private StringTokenizer tokenizer;
public SimpleInputReader(Reader reader) {
this.reader = new BufferedReader(reader);
}
public String readLine() throws IOException {
return reader.readLine();
}
public String nextString() throws IOException {
while(tokenizer == null || !tokenizer.hasMoreTokens()) {
String nextLine = readLine();
if(nextLine == null) {
throw new IOException("no more lines left!");
}
tokenizer = new StringTokenizer(nextLine);
}
return tokenizer.nextToken();
}
public Integer nextInt() throws IOException {
return Integer.parseInt(nextString());
}
public Long nextLong() throws IOException {
return Long.parseLong(nextString());
}
public float nextFloat() throws IOException {
return Float.parseFloat(nextString());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextString());
}
@Override
public void close() throws Exception {
reader.close();
}
}
public static class SimpleOutputWriter implements AutoCloseable{
private final BufferedWriter bufferedWriter;
public SimpleOutputWriter(Writer writer) {
bufferedWriter = new BufferedWriter(writer);
}
public void writeLine(Object s, Object... extras) throws IOException {
writeTokens(s, (Object[]) extras);
bufferedWriter.newLine();
}
public void flush() throws IOException {
bufferedWriter.flush();
}
public void writeTokens(Object o, Object... extras) throws IOException {
bufferedWriter.write(o.toString());
for (Object extra : extras) {
bufferedWriter.write(extra.toString());
}
}
@Override
public void close() throws Exception {
bufferedWriter.close();
}
public void newLine() throws IOException {
bufferedWriter.newLine();
}
}
}
|
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 11
|
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
|
4c6df395e22827ac8be2e663ac543ad8
|
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 scan = new Scanner(System.in);
int t = scan.nextInt();
for (int i = 0; i < t; i++) {
int n = scan.nextInt();
ArrayList<ArrayList<Pair>> graph = new ArrayList<>();
for (int j = 0; j < n; j++) {
graph.add(new ArrayList<>());
}
for (int j = 0; j < n - 1; j++) {
int u;
int v;
u = scan.nextInt();
v = scan.nextInt();
u--;
v--;
graph.get(u).add(new Pair(v, j));
graph.get(v).add(new Pair(u, j));
}
boolean soluble = true;
int curV = 0;
int prevV = -1;
int[] ans = new int[n];
int prime = 2;
for (int j = 0; j < n; j++) {
ArrayList<Pair> list = graph.get(j);
if (list.size() > 2) {
soluble = false;
} else if (list.size() == 1) {
curV = j;
}
}
if (soluble) {
for (int j = 0; j < n - 1; j++) {
ArrayList<Pair> list = graph.get(curV);
for (int z = 0; z < list.size(); z++) {
if (list.get(z).vertex != prevV) {
ans[list.get(z).numberOfEdge] = prime;
prime = changePrime(prime);
prevV = curV;
curV = list.get(z).vertex;
break;
}
}
}
for (int j = 0; j < n - 1; j++) {
System.out.print(ans[j] + " ");
}
System.out.println();
} else {
System.out.println(-1);
}
}
}
public static int changePrime(int prime) {
if (prime == 2) {
prime = 3;
} else {
prime = 2;
}
return prime;
}
}
class Pair {
int vertex;
int numberOfEdge;
public Pair(int vertex, int numberOfEdge) {
this.vertex = vertex;
this.numberOfEdge = numberOfEdge;
}
}
|
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 11
|
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
|
ede45500ea5af386acfa056d317eae8e
|
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
|
/*
3
2
1 2
4
1 3
4 3
2 1
7
1 2
1 3
3 4
3 5
6 2
7 2
Label every other vertex with either three or two
*/
import java.util.*;
import java.io.*;
public class Main{
public static int n;
public static int[] color;
public static Node[] nodes;
public static boolean poss;
public static HashSet<Edge> edges = new HashSet<Edge>();
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//color edges not nodes
int nc = Integer.parseInt(br.readLine());
for(int cc = 0; cc < nc; cc++){
n = Integer.parseInt(br.readLine());
color = new int[n - 1];
nodes = new Node[n];
poss = true; //-1 if false
for(int a = 0; a < n; a++) nodes[a] = new Node(a);
for(int a = 0; a < n - 1; a++){
StringTokenizer node = new StringTokenizer(br.readLine());
int first = Integer.parseInt(node.nextToken()) - 1;
int second = Integer.parseInt(node.nextToken()) - 1;
nodes[first].addEdge(new Edge(first, second, a));
nodes[second].addEdge(new Edge(first, second, a));
}
find();
if(poss){
StringBuilder sb = new StringBuilder();
for(int c : color) sb.append(c + " ");
System.out.println(sb);
}
else System.out.println(-1);
}
br.close();
}
public static int[] eVals = {2, 3};
public static void find(){
Queue<State> q = new LinkedList<State>();
q.add(new State(-1, 0, -1));
boolean[] seen = new boolean[n];
Arrays.fill(color, -1);
while(!q.isEmpty()){
State cur = q.poll();
//System.out.println("cur is " + cur);
if(!seen[cur.pos]){
seen[cur.pos] = true;
boolean[] taken = new boolean[4];
if(cur.prevColor != -1) taken[cur.prevColor] = true;
for(Edge e : nodes[cur.pos].edges){
if(e.id == cur.prev) continue;
//edges need to be different colors from each other and previous edge leading to this node, odd + odd = even so can only support up to two edges per node
for(int a = 0; a < 2; a++){
if(!taken[eVals[a]] && ((color[e.id] == -1) || (color[e.id] == eVals[a]))){
color[e.id] = eVals[a];
taken[eVals[a]] = true;
}
}
if(color[e.id] == -1){
poss = false;
break;
}
q.add(new State(color[e.id], e.connection(cur.pos), e.id));
}
}
}
}
}
class State{
int prevColor;
int pos;
int prev;
public State(int pC, int p, int pp){
prevColor = pC;
pos = p;
prev = pp;
}
public String toString(){
return prevColor + " previous color, current position is " + pos;
}
}
class Edge{
int a;
int b;
int id;
public Edge(int ac, int bc, int i){
a = ac;
b = bc;
id = i;
}
public String toString(){
return a + " " + b;
}
@Override
public int hashCode(){
return Objects.hash(a, b);
}
@Override
public boolean equals(Object o){
if(o == this) return true;
if(!(o instanceof Edge)) return false;
Edge o2 = (Edge) o;
if(o2.a == a && o2.b == b) return true;
return false;
}
public int connection(int other){
if(other == a) return b;
return a;
}
}
class Node{
int id;
ArrayList<Edge> edges = new ArrayList<Edge>();
public Node(int i){
id = i;
}
public void addEdge(Edge e){
edges.add(e);
}
public String toString(){
return id + " " + edges;
}
}
|
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 11
|
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
|
087914106d92b4d1e915d6cd9078ccb0
|
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.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String... args) throws IOException {
int t = readInt();
for (int i = 0; i < t; i++) {
int n = readInt();
Map<Integer, Node> graph = new HashMap<>();
boolean failed = false;
for (int j = 0; j < n - 1; j++) {
int i1 = readInt();
int i2 = readInt();
Node u = graph.get(i1);
if (u == null) {
u = new Node();
graph.put(i1, u);
}
Node v = graph.get(i2);
if (v == null) {
v = new Node();
graph.put(i2, v);
}
if (u.n1 == -1) {
u.n1 = i2;
u.i1 = j;
} else if (u.n2 == -1) {
u.n2 = i2;
u.i2 = j;
} else {
failed = true;
}
if (v.n1 == -1) {
v.n1 = i1;
v.i1 = j;
} else if (v.n2 == -1) {
v.n2 = i1;
v.i2 = j;
} else {
failed = true;
}
}
if (failed) {
System.out.println("-1");
continue;
}
int[] weights = new int[n - 1];
int prev = -1;
int b = 0;
for (Map.Entry<Integer, Node> entry : graph.entrySet()) {
if (entry.getValue().n2 == -1) {
b = entry.getKey();
break;
}
}
boolean next2 = true;
while (true) {
Node v = graph.get(b);
int next = v.n1;
int edge = v.i1;
if (next == prev) {
next = v.n2;
edge = v.i2;
}
if (next == -1) {
break;
}
prev = b;
b = next;
if (next2) {
weights[edge] = 2;
next2 = false;
} else {
weights[edge] = 3;
next2 = true;
}
}
for (int j = 0; j < n - 2; j++) {
System.out.print(weights[j]);
System.out.print(' ');
}
System.out.println(weights[n - 2]);
}
}
static class Node {
int n1 = -1, i1 = -1, n2 = -1, i2 = -1;
}
static int readInt() throws IOException {
int i = System.in.read();
while (i == ' ' || i == '\n' || i == '\r') {
i = System.in.read();
}
boolean negative = false;
if (i == '-') {
negative = true;
i = System.in.read();
}
int result = 0;
while (i != ' ' && i != '\n' && i != '\r' && i != -1) {
result *= 10;
result += i - '0';
i = System.in.read();
}
return negative ? -result : result;
}
}
|
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 11
|
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
|
7bb85392062170cbae0e3f45a3018f1f
|
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.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) {
// write your code here
boolean readFromLocal = true;
//readFromLocal = false;
String filepath = "src/input.txt";
//FileInputStrviseam fileInputStream = new FileInputStream(filepath);
InputReader inputReader = new InputReader(System.in);
Solve s = new Solve();
s.solve(inputReader);
}
}
class Solve {
public void solve(InputReader inputReader) {
int t,n;
t = inputReader.nextInt();
while (t>0) {
t--;
n = inputReader.nextInt();
Graph g = new Graph(n);
g.res = new int[n-1];
for(int i=1;i<n;i++){
g.addEdge(inputReader.nextInt(), inputReader.nextInt(),i-1,true);
}
if (g.hasDegreeMoreThanTwo()){
System.out.println(-1);
}else {
int minDegree = 2,node = 1;
for(int i=1;i<=n;i++){
if (g.adj[i].size()<minDegree){
node = i;
minDegree = g.adj[i].size();
}
}
g.dfs(node,-1,2);
for(int i=0;i<n-1;i++){
System.out.print(g.res[i] + " ");
}
System.out.println();
}
}
}
}
class PairComp implements Comparator<Pair> {
@Override
public int compare(Pair o1, Pair o2) {
return (int) (o1.first - o2.first);
}
}
class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int[] nextSortedIntArray(int n) {
int[] array = nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n) {
int[] array = new int[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) array[i] = nextLong();
return array;
}
public long[] nextSumLongArray(int n) {
long[] array = new long[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextSortedLongArray(int n) {
long[] array = nextLongArray(n);
Arrays.sort(array);
return array;
}
}
class Pair implements Comparable<Pair> {
long first, second;
public Pair(long first, long second) {
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return (int) (this.second - o.second);
}
}
class Utils {
static void swap(int[] res, int i, int j) {
int temp = res[i];
res[i] = res[j];
res[j] = temp;
}
static long pow(long num, int n, long mod) {
long res = num % mod;
while (n > 0) {
if ((n & 1) != 0) {
res = (res * num) % mod;
}
num = (num * num) % mod;
n >>= 1;
}
return res;
}
}
class Graph {
public ArrayList<int[]>[] adj;
int size;
boolean[] vis;
public int [] res;
Graph(int n){
this.size = n;
this.adj = new ArrayList[n+1];
this.vis = new boolean[n+1];
for (int i = 0; i <=n; i++) {
adj[i] = new ArrayList<>();
}
}
public void addEdge(int a, int b, int edge,boolean biDirectional){
adj[a].add(new int[]{b, edge});
if (biDirectional) {
adj[b].add(new int[]{a, edge});
}
}
public void dfs(int node,int parent,int prime){
for (int[] nodePair: adj[node]) {
if (nodePair[0]!=parent){
res[nodePair[1]] = prime;
dfs(nodePair[0],node,prime^1);
}
}
}
boolean hasDegreeMoreThanTwo() {
for (int i = 0; i <= size; i++) {
if (adj[i].size()>2){
return true;
}
}
return false;
}
}
|
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 11
|
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
|
8eb9123dd32c94b33fcbe63e13ad6374
|
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.*;
public class cp23 {
static BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
static int mod = 1000000007;
static String toReturn = "";
static int steps = Integer.MAX_VALUE;
static int maxlen = 1000005;
/*MATHEMATICS FUNCTIONS START HERE
MATHS
MATHS
MATHS
MATHS*/
static long gcd(long a, long b) {
if(b == 0) return a;
else return gcd(b, a % b);
}
static long powerMod(long x, long y, int mod) {
if(y == 0) return 1;
long temp = powerMod(x, y / 2, mod);
temp = ((temp % mod) * (temp % mod)) % mod;
if(y % 2 == 0) return temp;
else return ((x % mod) * (temp % mod)) % mod;
}
static long modInverse(long n, int p) {
return powerMod(n, p - 2, p);
}
static long nCr(int n, int r, int mod, long [] fact, long [] ifact) {
return ((fact[n] % mod) * ((ifact[r] * ifact[n - r]) % mod)) % mod;
}
/*
* static long [] seive(long n) {
*
* }
*/
/*MATHS
MATHS
MATHS
MATHS
MATHEMATICS FUNCTIONS END HERE */
/*SWAP FUNCTION START HERE
SWAP
SWAP
SWAP
SWAP
*/
static void swap(int i, int j, int [] arr) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/*SWAP
SWAP
SWAP
SWAP
SWAP FUNCTION END HERE*/
/*BINARY SEARCH METHODS START HERE
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
*/
static boolean BinaryCheck(long test, long [] arr, long health) {
for(int i = 0; i <= arr.length - 1; i++) {
if(i == arr.length - 1) health -= test;
else if(arr[i + 1] - arr[i] > test) {
health = health - test;
}else {
health = health - (arr[i + 1] - arr[i]);
}
if(health <= 0) return true;
}
return false;
}
static long binarySearchModified(long n, long [] arr) {
long start = 0, end = n, ans = n;
while(start < end) {
long mid = (start + end) / 2;
if(BinaryCheck(mid, arr, n)) {
ans = Math.min(ans, mid);
end = mid;
}else {
start = mid + 1;
}
}
return ans;
}
/*BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
BINARY SEARCH METHODS END HERE*/
/*RECURSIVE FUNCTION START HERE
* RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
*/
static int recurse(int x, int y, int n, int steps1, Integer [][] dp) {
if(x > n || y > n) return 0;
if(dp[x][y] != null) {
return dp[x][y];
}
else if(x == n || y == n) {
return steps1;
}
return dp[x][y] = Math.max(recurse(x + y, y, n, steps1 + 1, dp), recurse(x, x + y, n, steps1 + 1, dp));
}
/*RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
RECURSIVE FUNCTION END HERE*/
/*GRAPH FUNCTIONS START HERE
* GRAPH
* GRAPH
* GRAPH
* GRAPH
* */
static class edge{
int from, to, weight;
public edge(int x, int y, int z) {
this.from = x;
this.to = y;
this.weight = z;
}
}
static void addEdge(ArrayList<ArrayList<edge>> graph, int from, int to, int weight) {
edge temp = new edge(from, to, weight);
edge temp1 = new edge(to, from, weight);
graph.get(from).add(temp);
graph.get(to).add(temp1);
}
static int ans = 0;
static void dfs(ArrayList<ArrayList<edge>> graph, int vertex, boolean [] visited, int [] toReturn, int weight) {
//System.out.println(graph.get(vertex).size());
if(visited[vertex]) return;
visited[vertex] = true;
if(graph.get(vertex).size() > 2) return;
for(int i = 0; i < graph.get(vertex).size(); i++) {
edge temp = graph.get(vertex).get(i);
if(!visited[temp.to]) {
//System.out.println(temp.to);
toReturn[temp.weight] = weight;
dfs(graph, temp.to, visited, toReturn, 5 - weight);
weight = 5 - weight;
}
}
}
static void bfs(ArrayList<ArrayList<edge>> graph, int vertex, boolean [] visited, int [] toReturn, Queue<Integer> q, int weight) {
if(visited[vertex]) return;
visited[vertex] = true;
if(graph.get(vertex).size() > 2) return;
int first = weight;
for(int i = 0; i < graph.get(vertex).size(); i++) {
edge temp = graph.get(vertex).get(i);
if(!visited[temp.to]) {
q.add(temp.to);
toReturn[temp.weight] = weight;
weight = 5 - weight;
}
}
if(!q.isEmpty())bfs(graph, q.poll(), visited, toReturn, q, 5 - first);
}
static void topoSort(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, ArrayList<Integer> toReturn) {
if(visited[vertex]) return;
visited[vertex] = true;
for(int i = 0; i < graph.get(vertex).size(); i++) {
if(!visited[graph.get(vertex).get(i)]) topoSort(graph, graph.get(vertex).get(i), visited, toReturn);
}
toReturn.add(vertex);
}
static boolean isCyclicDirected(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, boolean [] reStack) {
if(reStack[vertex]) return true;
if(visited[vertex]) return false;
reStack[vertex] = true;
visited[vertex] = true;
for(int i = 0; i < graph.get(vertex).size(); i++) {
if(isCyclicDirected(graph, graph.get(vertex).get(i), visited, reStack)) return true;
}
reStack[vertex] = false;
return false;
}
/*GRAPH FUNCTIONS END HERE
* GRAPH
* GRAPH
* GRAPH
* GRAPH
*/
/*disjoint Set START HERE
* disjoint Set
* disjoint Set
* disjoint Set
* disjoint Set
*/
static int [] rank;
static int [] parent;
static int parent(int [] parent, int x) {
if(parent[x] == x) return x;
else return parent[x] = parent(parent, parent[x]);
}
static void union(int x, int y, int [] rank, int [] parent) {
if(parent(parent, x) == parent(parent, y)) {
return;
}
if(rank[x] > rank[y]) {
swap(x, y, rank);
}
rank[x] += rank[y];
parent[x] = y;
}
/*disjoint Set END HERE
* disjoint Set
* disjoint Set
* disjoint Set
* disjoint Set
*/
/*INPUT START HERE
* INPUT
* INPUT
* INPUT
* INPUT
* INPUT
*/
static int nexInt() throws NumberFormatException, IOException {
return Integer.parseInt(sc.readLine());
}
static long nexLong() throws NumberFormatException, IOException {
return Long.parseLong(sc.readLine());
}
static long [] inputLongArr() throws NumberFormatException, IOException{
String [] s = sc.readLine().split(" ");
long [] toReturn = new long[s.length];
for(int i = 0; i < s.length; i++) {
toReturn[i] = Long.parseLong(s[i]);
}
return toReturn;
}
static int [] inputIntArr() throws NumberFormatException, IOException{
String [] s = sc.readLine().split(" ");
int [] toReturn = new int[s.length];
for(int i = 0; i < s.length; i++) {
toReturn[i] = Integer.parseInt(s[i]);
}
return toReturn;
}
/*INPUT
* INPUT
* INPUT
* INPUT
* INPUT
* INPUT END HERE
*/
static void solve() throws IOException {
int n = nexInt();
ArrayList<ArrayList<edge>> tree = new ArrayList<>();
for(int i = 0; i < n; i++) tree.add(new ArrayList<edge>());
for(int i = 0; i < n - 1; i++) {
int [] s1 = inputIntArr();
addEdge(tree, s1[0] - 1, s1[1] - 1, i);
}
int vertex = 0;
for(int i = 0; i < tree.size(); i++) {
if(tree.get(i).size() > 2) {
System.out.println(-1);
return;
}else if(tree.size() == 1) {
vertex = i;
}
}
int [] toReturn = new int[n - 1];
//toReturn.add(2);
dfs(tree, vertex, new boolean[n], toReturn, 2);
//System.out.println(toReturn.size());
for(int i = 0; i < toReturn.length; i++)
if(toReturn[i] != 0)System.out.print(toReturn[i] + " ");
System.out.println();
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int t = Integer.parseInt(sc.readLine()); for(int i = 0; i < t; i++)
solve();
}
}
|
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 11
|
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
|
5a3e3d08ba9d8b83e04c4e2536bd3205
|
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.*;
public class Solution {
private static final FastScanner fs = new FastScanner();
static int[] ans;
static TreeMap<Integer, List<pairs>> map;
public static void main(String[] args) {
int testCase = fs.nextInt();
for (int i = 1; i <= testCase; i++) {
solve();
}
}
public static void solve() {
int n = fs.nextInt();
map = new TreeMap<>();
ans = new int[n + 1];
int[] degress = new int[n + 1];
for (int i = 0; i < n - 1; i++) {
int first = fs.nextInt();
int second = fs.nextInt();
degress[first]++;
degress[second]++;
List<pairs> firstList = map.getOrDefault(first, new ArrayList<>());
List<pairs> secondList = map.getOrDefault(second, new ArrayList<>());
firstList.add(new pairs(second, i));
secondList.add(new pairs(first, i));
map.put(first, firstList);
map.put(second, secondList);
}
long count = Arrays.stream(degress).filter(current -> current > 2).count();
if (count >= 1) {
System.out.println(-1);
return;
}
int start = 1;
for (int i = 0; i < degress.length; i++) {
if (degress[i] == 1) {
start = i;
break;
}
}
doRecursion(start, -1, 2);
StringBuilder ans2 = new StringBuilder();
for (int i = 0; i < n - 1; i++) {
ans2.append(ans[i]).append(" ");
}
System.out.println(ans2);
}
public static void doRecursion(int currentStart, int parent, int valueToAssign) {
List<pairs> currentPairs = map.get(currentStart);
for (pairs currentPair : currentPairs) {
if (currentPair.a != parent) {
ans[currentPair.b] = valueToAssign;
doRecursion(currentPair.a, currentStart, 7 - valueToAssign);
break;
}
}
}
}
class pairs implements Comparable<pairs> {
public int a, b, c;
public pairs(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(pairs o) {
return a - o.a;
}
}
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());
}
}
/*
10
9 2
5 1
3 5
10 2
3 4
6 4
8 7
8 1
6 9
*/
|
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 11
|
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
|
e05ed03e04f2355b82f0e58f877f4e34
|
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.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
public class CF1627C {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8));
int t = Integer.parseInt(reader.readLine());
for (int i = 0; i < t; i++) {
int n = Integer.parseInt(reader.readLine());
int[][] nums = new int[n - 1][2];
for (int j = 0; j < n - 1; j++) {
String[] lines = reader.readLine().split(" ");
nums[j][0] = Integer.parseInt(lines[0]);
nums[j][1] = Integer.parseInt(lines[1]);
}
writer.write(solution(n, nums).concat(System.lineSeparator()));
}
writer.close();
reader.close();
}
private static String solution(int n, int[][] nums) {
// 无向图
Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();
for (int[] num : nums) {
int u = num[0];
int v = num[1];
Map<Integer, Integer> uMap = graph.getOrDefault(u, new HashMap<>());
uMap.put(v, -1);
graph.put(u, uMap);
Map<Integer, Integer> vMap = graph.getOrDefault(v, new HashMap<>());
vMap.put(u, -1);
graph.put(v, vMap);
}
// 不存在三个质数,任意两个之和也是质数
for (int i = 1; i <= n; i++) {
if (graph.getOrDefault(i, new HashMap<>()).size() > 2) {
return "-1";
}
}
Queue<Integer> queue = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
// 设 (u,v) 权重为 2
int u0 = nums[0][0];
int v0 = nums[0][1];
graph.get(u0).put(v0, 2);
graph.get(v0).put(u0, 2);
queue.add(u0);
queue.add(v0);
visited.add(u0);
visited.add(v0);
boolean is2 = true;
while (!queue.isEmpty()) {
is2 = !is2;
int size = queue.size();
for (int i = 0; i < size; i++) {
int cur = queue.remove();
for (int next : graph.get(cur).keySet()) {
if (!visited.contains(next)) {
visited.add(next);
graph.get(cur).put(next, is2 ? 2 : 3);
graph.get(next).put(cur, is2 ? 2 : 3);
queue.add(next);
}
}
}
}
List<Integer> resList = new ArrayList<>();
for (int[] num : nums) {
int u = num[0];
int v = num[1];
resList.add(graph.get(u).get(v));
}
// List<Integer> => String
StringBuilder stringBuilder = new StringBuilder();
for (int num : resList) {
stringBuilder.append(num).append(" ");
}
return stringBuilder.substring(0, stringBuilder.length() - 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 11
|
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
|
2e015046e625e94cffcb994db688a6c3
|
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 div_766_2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class C{
public static void main(String[] args){
FastReader sc = new FastReader();
int t=sc.nextInt();
next:while(t-->0){
int n=sc.nextInt();
pair []arr= new pair[n];
ArrayList<ArrayList<pair>> a= new ArrayList<>();
for(int i=0;i<=n;i++)a.add(new ArrayList<pair>());
for(int i=0;i<n-1;i++) {
int u=sc.nextInt();
int v=sc.nextInt();
arr[i]=new pair(u,v);
a.get(u).add(new pair(v, i));
a.get(v).add(new pair(u,i));
}
int node=1;
for(int i=1;i<=n;i++) {
if(a.get(i).size()>1) {
node=i;
}else if(a.get(i).size()>2) {
System.out.println(-1);
continue next;
}
}
int ans[]=new int [n-1];
if(a.get(node).size()==1) {
System.out.println(11);
continue next;
}
pair l=a.get(node).get(0);
pair r=a.get(node).get(1);
ans[l.y]=11;
ans[r.y]=2;
int pre=node;int temp=node;
node=l.x;boolean ch=false;
while(a.get(node).size()>=1) {
pair x=a.get(node).get(0);
// System.out.println(x.x+" "+node);
if(x.x==pre) {
if(a.get(node).size()<=1)break;
else x=a.get(node).get(1);
}
pre=node;
node=x.x;
if(!ch) ans[x.y]=2;
else ans[x.y]=11;
ch=!ch;
}
node=r.x; ch=false;pre=temp;
while(a.get(node).size()>=1) {
pair x=a.get(node).get(0);
if(x.x==pre) {
if(a.get(node).size()<=1)break;
else x=a.get(node).get(1);
}
pre=node;
node=x.x;
if(!ch) ans[x.y]=5;
else ans[x.y]=2;
ch=!ch;
}
for(int i=0;i<n-1;i++)if(ans[i]==0) {
System.out.println(-1);
continue next;
}
print(ans);
}
}
static void print(int a[]) {
for(int i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static class pair {
int x;int y;
pair(int x,int y){
this.x=x;
this.y=y;
}
}
static ArrayList<Integer> primeFac(int n){
ArrayList<Integer>ans = new ArrayList<Integer>();
int lp[]=new int [n+1];
Arrays.fill(lp, 0); //0-prime
for(int i=2;i<=n;i++) {
if(lp[i]==0) {
for(int j=i;j<=n;j+=i) {
if(lp[j]==0) lp[j]=i;
}
}
}
int fac=n;
while(fac>1) {
ans.add(lp[fac]);
fac=fac/lp[fac];
}
print(ans);
return ans;
}
static ArrayList<Long> prime_in_given_range(long l,long r){
ArrayList<Long> ans= new ArrayList<>();
int n=(int)Math.sqrt(r)+1;
int prime[]=sieve_of_Eratosthenes(n);
long res[]=new long [(int)(r-l)+1];
for(int i=0;i<=r-l;i++) {
res[i]=i+l;
}
for(int i=0;i<prime.length;i++) {
if(prime[i]==1) {
System.out.println(2);
for(int j=Math.max((int)i*i, (int)(l+i-1)/i*i);j<=r;j+=i) {
res[j-(int)l]=0;
}
}
}
for(long i:res) if(i!=0)ans.add(i);
return ans;
}
static int [] sieve_of_Eratosthenes(int n) {
int prime[]=new int [n];
Arrays.fill(prime, 1); // 1-prime | 0-not prime
prime[0]=prime[1]=0;
for(int i=2;i<n;i++) {
if(prime[i]==1) {
for(int j=i*i;j<n;j+=i) {
prime[j]=0;
}
}
}
return prime;
}
static long binpow(long a,long b) {
long res=1;
if(b==0)return a;
if(a==0)return 1;
while(b>0) {
if((b&1)==1) {
res*=a;
}
a*=a;
b>>=1;
}
return res;
}
static void print(long a[]) {
for(long i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(ArrayList<Integer> a) {
System.out.println(a.size());
for(long i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
int [] fastArray(int n) {
int a[]=new int [n];
for(int i=0;i<n;i++) {
a[i]=nextInt();
}
return a;
}
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 11
|
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
|
93572d311078a6f4161aa10407899884
|
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 {
// For fast input output
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
try {
br = new BufferedReader(
new FileReader("input.txt"));
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
} catch (Exception e) {
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 Edge
{
int node;
int index;
Edge(int node, int index)
{
this.node = node;
this.index = index;
}
}
private static void dfs(int u,List<List<Edge>> graph, int []weightIndex, int []visited, boolean flag) {
visited[u] = 1;
for( Edge x : graph.get(u)) {
if(visited[x.node] == 0 && flag == false) {
weightIndex[x.index] = 2;
dfs(x.node, graph, weightIndex, visited, true);
}
else if(visited[x.node] == 0 && flag == true) {
weightIndex[x.index] = 5;
dfs(x.node, graph, weightIndex, visited, false);
}
}
}
// end of fast i/o code
public static void main(String[] args) {
FastReader reader = new FastReader();
int t = reader.nextInt();
while(t-- > 0) {
int n = reader.nextInt();
int u, v, flag = 0;
List<List<Edge>> graph = new ArrayList<>();
for(int i=0; i<n; i++)
{
graph.add(new ArrayList<>());
}
for(int i=0; i<n-1; i++) {
u = reader.nextInt();
v = reader.nextInt();
graph.get(u-1).add(new Edge(v-1,i));
graph.get(v-1).add(new Edge(u-1,i));
if(graph.get(u-1).size() ==3 || graph.get(v-1).size() == 3) {
flag = 1;
}
}
if(flag == 1)
System.out.println(-1);
else {
int leaf = 0;
for(int i=0; i<n; i++)
{
if(graph.get(i).size() == 1)
{
leaf = i;
break;
}
}
int weightIndex[] = new int[n-1];
int visited[] = new int[n];
dfs(leaf, graph, weightIndex, visited, false);
for(int i=0; i<n-1; i++)
System.out.print(weightIndex[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 11
|
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
|
97a9a899374495880ef019b51937f290
|
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.*;
import java.util.*;
// @author : Dinosparton
public class test {
static class Pair{
long x;
long y;
Pair(long x,long y){
this.x = x;
this.y = y;
}
}
static class Duo{
int x;
String s;
Duo(int x,String s){
this.x = x;
this.s = s;
}
}
static class Sort implements Comparator<Pair>
{
@Override
public int compare(Pair a, Pair b)
{
if(a.x!=b.x)
{
return (int)(a.x - b.x);
}
else
{
return (int)(a.y-b.y);
}
}
}
static class Compare {
void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.x!=p2.x) {
return (int)(p1.x - p2.x);
}
else {
return (int)(p1.y - p2.y);
}
}
});
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].x + " " + arr[i].y + " ");
// }
// System.out.println();
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner()
{
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 dfs(ArrayList<Pair> adj[],int src,int parent ,int color[],int fill) {
for(Pair i : adj[src]) {
if((int)i.x!=parent) {
color[(int)i.y] = fill;
dfs(adj,(int)i.x,src,color,1-fill);
fill = 1 - fill;
}
}
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner();
StringBuilder res = new StringBuilder();
int tc = sc.nextInt();
while(tc-->0) {
boolean flag = true;
int n = sc.nextInt();
ArrayList<Pair> adj[] = new ArrayList[n+1];
for(int i=0;i<=n;i++) {
adj[i] = new ArrayList<>();
}
for(int i=0;i<n-1;i++) {
int src = sc.nextInt();
int dest = sc.nextInt();
adj[src].add(new Pair(dest,i));
adj[dest].add(new Pair(src,i));
}
for(int i=1;i<=n;i++) {
if(adj[i].size()>2) {
flag = false;
break;
}
}
if(!flag) {
res.append(-1+"\n");
continue;
}
int color[] = new int[n-1];
dfs(adj,1,-1,color,0);
for(int i=0;i<n-1;i++) {
if(color[i]==0) {
res.append(2+" ");
}
else {
res.append(5+" ");
}
}
res.append("\n");
}
System.out.println(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 11
|
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
|
0f85627120795aca80ccb3b16a7c861a
|
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.*;
/**
1. 如果一条点连了三条边,肯定构不成
2. 所以可能是一条链才能构成
如何判断是否是一条链?通过map
3. 如何安排
* */
public class C {
static int n;
static int idx;
static int[] e, ne, h;
static Map<Pair, Integer> dist = new HashMap<>();
static Map<Integer, Integer> map = new HashMap<>();
static List<int[]> q = new ArrayList<>();
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int T = sc.nextInt();
while (T-- > 0) {
n = sc.nextInt();
init();
boolean flag = false;
for(int i = 0; i < n - 1; i++){
int u = sc.nextInt();
int v = sc.nextInt();
q.add(new int[]{Math.min(u, v), Math.max(u, v)});
map.put(u, map.getOrDefault(u, 0) + 1);
map.put(v, map.getOrDefault(v, 0) + 1);
if(map.get(u) == 3 || map.get(v) == 3) flag = true; // 如果一个点有三条出边说明不是链
add(u, v);
add(v, u);
}
if(flag) System.out.println(-1);
else {
int i = h[1];
int j = e[i];
dist.put(new Pair(1, j), 2);
dfs(j, 2);
i = ne[i];
if (i != -1) { // 如果1还有另外一边的边
j = e[i];
dist.put(new Pair(1, j), 11);
dfs(j, 11);
}
// output result
for(int[] l: q){
int min = Math.min(l[0], l[1]);
int max = Math.max(l[0], l[1]);
System.out.print(dist.get(new Pair(min, max)) + " ");
}
System.out.println();
}
}
}
static void dfs(int u, int p){ // 上一条路径的距离
for(int i = h[u]; i != -1; i = ne[i]){
int j = e[i];
int min = Math.min(u, j);
int max = Math.max(u, j);
Pair t = new Pair(min, max);
if(dist.containsKey(t)) continue; // 说明走过了
// System.out.println(" -> " + j);
if(p == 2) dist.put(t, 11);
if(p == 11) dist.put(t, 2);
dfs(j, dist.get(t));
}
}
static void init(){
e = new int[n * 2 + 1];
ne = new int[n * 2 + 1];
h = new int[n + 1];
idx = 0;
Arrays.fill(h, -1);
map.clear();
dist.clear();
q.clear();
}
static void add(int a, int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@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);
}
}
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 11
|
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
|
ffd48d398982987309239b72dc74c6ed
|
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.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codeforces
{
static int ans[];
static void DFS(int v,ArrayList<int[]> adj[],int prime,boolean visited[],int index)
{
if(index!=-1)
ans[index]=prime;
visited[v]=true;
for(int child[]:adj[v])
{
if(visited[child[0]]==false) {
DFS(child[0], adj, 1 - prime, visited,child[1]);
prime=1-prime;
}
}
}
static void DFSUtil(int n,ArrayList<int[]> adj[])
{
boolean visited[]=new boolean[n+1];
ans=new int[n-1];
Arrays.fill(ans,-1);
DFS(1,adj,0,visited,-1);
for(int j=0;j<n-1;j++)
ans[j]+=2;
}
public static void main(String[] args) throws java.lang.Exception {
/* your code goes here */
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(buf.readLine());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < t; i++) {
String st1[]=(buf.readLine()).split(" ");
int n=Integer.parseInt(st1[0]);
ArrayList<int[]> adj[]=new ArrayList[n+1];
for(int j=1;j<=n;j++)
adj[j]=new ArrayList<>();
int edges[][]=new int[n-1][2];
for(int j=0;j<n-1;j++)
{
String st2[]=(buf.readLine()).split(" ");
int u=Integer.parseInt(st2[0]);
int v=Integer.parseInt(st2[1]);
edges[j][0]=u;
edges[j][1]=v;
adj[u].add(new int[]{v,j});
adj[v].add(new int[]{u,j});
}
int flag=0;
int ct=2;
for(int j=1;j<=n;j++)
{
if(adj[j].size()>2)
{
flag=1;
break;
}
}
if(flag==1)
sb.append(-1+"\n");
else {
DFSUtil(n,adj);
for (int j = 0; j < n - 1; j++) {
sb.append(ans[j]+" ");
}
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 11
|
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
|
45114e3dad531e5e2088f1cc1bde7579
|
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.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codeforces
{
static int ans[];
static Map<Integer,Map<Integer,Integer>> map;
static void DFS(int v,ArrayList<int[]> adj[],int prime,boolean visited[],int index)
{
if(index!=-1)
ans[index]=prime;
visited[v]=true;
for(int child[]:adj[v])
{
if(visited[child[0]]==false) {
//Map<Integer,Integer> mp1;
//mp1=map.get(v);
//mp1.put(child,prime+2);
//map.put(v,mp1);
//mp1=map.get(child);
//mp1.put(v,prime+2);
//map.put(child,mp1);
DFS(child[0], adj, 1 - prime, visited,child[1]);
prime=1-prime;
}
}
}
static void DFSUtil(int n,ArrayList<int[]> adj[])
{
boolean visited[]=new boolean[n+1];
ans=new int[n-1];
Arrays.fill(ans,-1);
DFS(1,adj,0,visited,-1);
for(int j=0;j<n-1;j++)
ans[j]+=2;
}
public static void main(String[] args) throws java.lang.Exception {
/* your code goes here */
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(buf.readLine());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < t; i++) {
String st1[]=(buf.readLine()).split(" ");
int n=Integer.parseInt(st1[0]);
ArrayList<int[]> adj[]=new ArrayList[n+1];
for(int j=1;j<=n;j++)
adj[j]=new ArrayList<>();
int edges[][]=new int[n-1][2];
for(int j=0;j<n-1;j++)
{
String st2[]=(buf.readLine()).split(" ");
int u=Integer.parseInt(st2[0]);
int v=Integer.parseInt(st2[1]);
edges[j][0]=u;
edges[j][1]=v;
adj[u].add(new int[]{v,j});
adj[v].add(new int[]{u,j});
}
map=new HashMap<>();
for(int j=1;j<=n;j++)
map.put(j,new HashMap<>());
int flag=0;
int ct=2;
for(int j=1;j<=n;j++)
{
if(adj[j].size()>2)
{
flag=1;
break;
}
}
//0-->2 1-->3
if(flag==1)
sb.append(-1+"\n");
else {
DFSUtil(n,adj);
for (int j = 0; j < n - 1; j++) {
//sb.append(map.get(edges[j][0]).get(edges[j][1])+" ");
sb.append(ans[j]+" ");
}
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 11
|
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
|
30eb70451028b957d13c874323c97acf
|
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.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codeforces
{
static int ans[];
static Map<Integer,Map<Integer,Integer>> map;
static void DFS(int v,ArrayList<Integer> adj[],int prime,boolean visited[])
{
ans[v]=prime;
visited[v]=true;
for(int child:adj[v])
{
if(visited[child]==false) {
Map<Integer,Integer> mp1;
mp1=map.get(v);
mp1.put(child,prime+2);
map.put(v,mp1);
mp1=map.get(child);
mp1.put(v,prime+2);
map.put(child,mp1);
DFS(child, adj, 1 - prime, visited);
prime=1-prime;
}
}
}
static void DFSUtil(int n,ArrayList<Integer> adj[])
{
boolean visited[]=new boolean[n+1];
ans=new int[n+1];
Arrays.fill(ans,-1);
DFS(1,adj,0,visited);
for(int j=1;j<=n;j++)
ans[j]+=2;
}
public static void main(String[] args) throws java.lang.Exception {
/* your code goes here */
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(buf.readLine());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < t; i++) {
String st1[]=(buf.readLine()).split(" ");
int n=Integer.parseInt(st1[0]);
ArrayList<Integer> adj[]=new ArrayList[n+1];
for(int j=1;j<=n;j++)
adj[j]=new ArrayList<>();
int edges[][]=new int[n-1][2];
for(int j=0;j<n-1;j++)
{
String st2[]=(buf.readLine()).split(" ");
int u=Integer.parseInt(st2[0]);
int v=Integer.parseInt(st2[1]);
edges[j][0]=u;
edges[j][1]=v;
adj[u].add(v);
adj[v].add(u);
}
map=new HashMap<>();
for(int j=1;j<=n;j++)
map.put(j,new HashMap<>());
int flag=0;
int ct=2;
for(int j=1;j<=n;j++)
{
if(adj[j].size()>2)
{
flag=1;
break;
}
}
//0-->2 1-->3
if(flag==1)
sb.append(-1+"\n");
else {
DFSUtil(n,adj);
for (int j = 0; j < n - 1; j++) {
sb.append(map.get(edges[j][0]).get(edges[j][1])+" ");
}
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 11
|
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
|
3eff61f900c2d8841e9166e9c18f291a
|
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 eround101;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.util.StringTokenizer;
public class Solution {
static HritikScanner sc = new HritikScanner();
static PrintWriter pw = new PrintWriter(System.out, true);
final static int MOD = 1000000007;
public static void main(String[] args) {
int t = ni();
while (t-- > 0) {
solve();
}
}
static void solve() {
int n = ni();
Map<Integer, HashSet<Integer>> map = new HashMap<>();
int[][] que = new int[n-1][2];
for(int i =0; i < n-1; i++)
{
int a = ni();
int b= ni();
que[i][0] = a;
que[i][1] = b;
if(!map.containsKey(a))
{
map.put(a, new HashSet<>());
}
map.get(a).add(b);
if(!map.containsKey(b))
{
map.put(b, new HashSet<>());
}
map.get(b).add(a);
}
int leaf = -1;
boolean flag = false;
for(int ele : map.keySet())
{
HashSet<Integer> adj = map.get(ele);
if(adj.size() > 2)
{
flag = true;
}
if(adj.size() == 1)
{
leaf = ele;
}
}
if(flag)
{
pl(-1);
return;
}
int[] arr = new int[n];
Queue<Integer> q = new LinkedList<>();
q.add(leaf);
HashSet<Integer> vis = new HashSet<>();
vis.add(leaf);
int k = 0;
while(!q.isEmpty())
{
int ele = q.poll();
arr[k] = ele;
k++;
for(int p : map.get(ele))
{
if(!vis.contains(p))
{
vis.add(p);
q.add(p);
}
}
}
Map<Integer, Integer> ind = new HashMap<>();
for(int i = 0; i < arr.length; i++)
{
if(!ind.containsKey(arr[i]))
{
ind.put(arr[i], i);
}
}
for(int i = 0; i < n-1; i++)
{
int index = ind.get(que[i][0]);
int nei = ind.get(que[i][1]);
if(index % 2 == 0)
{
if(nei == index + 1)
{
System.out.print(11+" ");
}
else{
System.out.print(2+" ");
}
}
else{
if(nei == index + 1)
{
System.out.print(2+" ");
}
else{
System.out.print(11+" ");
}
}
}
pl();
}
/////////////////////////////////////////////////////////////////////////////////
static class FenwickTree { // Binary Index Tree
int[] tree;
static int size;
public FenwickTree(int size) {
this.size = size;
tree = new int[size + 5];
}
public void add(int i, int val) {
while (i <= size) {
tree[i] += val;
i += i & -i; // adding the decimal value of the last set bit.
}
}
public int sum(int i) {
int res = 0;
while (i >= 1) {
res += tree[i];
i -= i & -i; // deleting the last set bit
}
return res;
}
public int sum(int l, int r) {
return sum(r) - sum(l - 1);
}
}
/////////////////////////////////////////////////////////////////////////////////
static int[] nextIntArray(int n) {
int[] arr = new int[n];
int i = 0;
while (i < n) {
arr[i++] = ni();
}
return arr;
}
static long[] nextLongArray(int n) {
long[] arr = new long[n];
int i = 0;
while (i < n) {
arr[i++] = nl();
}
return arr;
}
static int[] nextIntArray1(int n) {
int[] arr = new int[n + 1];
int i = 1;
while (i <= n) {
arr[i++] = ni();
}
return arr;
}
/////////////////////////////////////////////////////////////////////////////////
static int ni() {
return sc.nextInt();
}
static long nl() {
return sc.nextLong();
}
static double nd() {
return sc.nextDouble();
}
/////////////////////////////////////////////////////////////////////////////////
static void pl() {
pw.println();
}
static void p(Object o) {
pw.print(o + " ");
}
static void pl(Object o) {
pw.println(o);
}
/////////////////////////////////////////////////////////////////////////////////
static void print(Object s) {
System.out.println(s);
}
/////////////////////////////////////////////////////////////////////////////////
//Arrays.sort(arr(type int)) uses quick sort whose worst case time complexity is O(N^2) in case of sorted array.
// we can either use Object (Integer, Long)[Here it will use merge sort] array or suffle the array before sorting
// or we can use Collections.sort(list))
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;
}
/////////////////////////////////////////////////////////////////////////////////
//-----------HritikScanner class for faster input----------//
static class HritikScanner {
BufferedReader br;
StringTokenizer st;
public HritikScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//////////////////////////////////////////////////////////////////
public static class Pair implements Comparable<Pair> {
int num, row, col;
Pair(int num, int row, int col) {
this.num = num;
this.row = row;
this.col = col;
}
public int get1() {
return num;
}
public int get2() {
return row;
}
public int compareTo(Pair A) {
return this.num - A.num;
}
public String toString() {
return num + " " + row + " " + col;
}
}
//////////////////////////////////////////////////////////////////
// Function to return gcd of a and b time complexity O(log(a+b))
static long gcd(long a, long b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
// method to return LCM of two numbers
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
//////////////////////////////////////////////////////////////////
static boolean isPrime(long n) {
// Corner cases
if (n <= 1) {
return false;
}
if (n <= 3) {
return true;
}
// This is checked so that we can skip
// middle five numbers in below loop
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 isPowerOfTwo(long n) {
if (n == 0) {
return false;
}
return (long) (Math.ceil((Math.log(n) / Math.log(2))))
== (long) (Math.floor(((Math.log(n) / Math.log(2)))));
}
public static long getFact(int n) {
long ans = 1;
while (n > 0) {
ans *= n;
ans %= MOD;
n--;
}
return ans;
}
public static long pow(long n, int pow) {
if (pow == 0) {
return 1;
}
long temp = pow(n, pow / 2) % MOD;
temp *= temp;
temp %= MOD;
if (pow % 2 == 1) {
temp *= n;
}
temp %= MOD;
return temp;
}
public static long nCr(int n, int r) {
long ans = 1;
int temp = n - r;
while (n > temp) {
ans *= n;
ans %= MOD;
n--;
}
ans *= pow(getFact(r) % MOD, MOD - 2) % MOD;
ans %= MOD;
return ans;
}
//////////////////////////////////////////////////////////////////
// method returns Nth power of A
static double nthRoot(int A, int N) {
// intially guessing a random number between
// 0 and 9
double xPre = Math.random() % 10;
// smaller eps, denotes more accuracy
double eps = 0.001;
// initializing difference between two
// roots by INT_MAX
double delX = 2147483647;
// xK denotes current value of x
double xK = 0.0;
// loop untill we reach desired accuracy
while (delX > eps) {
// calculating current value from previous
// value by newton's method
xK = ((N - 1.0) * xPre
+ (double) A / Math.pow(xPre, N - 1)) / (double) N;
delX = Math.abs(xK - xPre);
xPre = xK;
}
return xK;
}
}
|
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 11
|
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
|
9c8172ef142901c58d009280ac42d9e1
|
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 eround101;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.util.StringTokenizer;
public class Solution {
static HritikScanner sc = new HritikScanner();
static PrintWriter pw = new PrintWriter(System.out, true);
final static int MOD = 1000000007;
public static void main(String[] args) {
int t = ni();
while (t-- > 0) {
solve();
}
}
static void solve() {
int n = ni();
Map<Integer, LinkedList<Integer>> map = new HashMap<>();
int[][] que = new int[n-1][2];
for(int i =0; i < n-1; i++)
{
int a = ni();
int b= ni();
que[i][0] = a;
que[i][1] = b;
if(!map.containsKey(a))
{
map.put(a, new LinkedList<>());
}
map.get(a).add(b);
map.get(a).add(i);
if(!map.containsKey(b))
{
map.put(b, new LinkedList<>());
}
map.get(b).add(a);
map.get(b).add(i);
}
//pl(map);
int leaf = -1;
boolean flag = true;
for(int ele : map.keySet())
{
LinkedList<Integer> adj = map.get(ele);
if(adj.size() >= 6)
{
flag = false;
}
if(adj.size() == 2)
{
leaf = ele;
}
}
if(!flag)
{
pl(-1);
return;
}
int[] arr = new int[n-1];
Queue<Integer> q = new LinkedList<>();
q.add(leaf);
HashSet<Integer> vis = new HashSet<>();
vis.add(leaf);
int k = 0;
int last = 3;
while(!q.isEmpty())
{
int ele = q.poll();
LinkedList<Integer> adj = map.get(ele);
for(int i = 0; i < adj.size(); i= i+2)
{
int att = adj.get(i);
int ind = adj.get(i+1);
if(arr[ind] == 0)
{
if(last == 3)
{
arr[ind] = 2;
last = 2;
}
else
{
arr[ind] = 3;
last = 3;
}
q.add(att);
}
}
}
for(int i = 0; i < n-1; i++)
{
System.out.print(arr[i]+" ");
}
pl();
}
/////////////////////////////////////////////////////////////////////////////////
static class FenwickTree { // Binary Index Tree
int[] tree;
static int size;
public FenwickTree(int size) {
this.size = size;
tree = new int[size + 5];
}
public void add(int i, int val) {
while (i <= size) {
tree[i] += val;
i += i & -i; // adding the decimal value of the last set bit.
}
}
public int sum(int i) {
int res = 0;
while (i >= 1) {
res += tree[i];
i -= i & -i; // deleting the last set bit
}
return res;
}
public int sum(int l, int r) {
return sum(r) - sum(l - 1);
}
}
/////////////////////////////////////////////////////////////////////////////////
static int[] nextIntArray(int n) {
int[] arr = new int[n];
int i = 0;
while (i < n) {
arr[i++] = ni();
}
return arr;
}
static long[] nextLongArray(int n) {
long[] arr = new long[n];
int i = 0;
while (i < n) {
arr[i++] = nl();
}
return arr;
}
static int[] nextIntArray1(int n) {
int[] arr = new int[n + 1];
int i = 1;
while (i <= n) {
arr[i++] = ni();
}
return arr;
}
/////////////////////////////////////////////////////////////////////////////////
static int ni() {
return sc.nextInt();
}
static long nl() {
return sc.nextLong();
}
static double nd() {
return sc.nextDouble();
}
/////////////////////////////////////////////////////////////////////////////////
static void pl() {
pw.println();
}
static void p(Object o) {
pw.print(o + " ");
}
static void pl(Object o) {
pw.println(o);
}
/////////////////////////////////////////////////////////////////////////////////
static void print(Object s) {
System.out.println(s);
}
/////////////////////////////////////////////////////////////////////////////////
//Arrays.sort(arr(type int)) uses quick sort whose worst case time complexity is O(N^2) in case of sorted array.
// we can either use Object (Integer, Long)[Here it will use merge sort] array or suffle the array before sorting
// or we can use Collections.sort(list))
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;
}
/////////////////////////////////////////////////////////////////////////////////
//-----------HritikScanner class for faster input----------//
static class HritikScanner {
BufferedReader br;
StringTokenizer st;
public HritikScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//////////////////////////////////////////////////////////////////
public static class Pair implements Comparable<Pair> {
int num, row, col;
Pair(int num, int row, int col) {
this.num = num;
this.row = row;
this.col = col;
}
public int get1() {
return num;
}
public int get2() {
return row;
}
public int compareTo(Pair A) {
return this.num - A.num;
}
public String toString() {
return num + " " + row + " " + col;
}
}
//////////////////////////////////////////////////////////////////
// Function to return gcd of a and b time complexity O(log(a+b))
static long gcd(long a, long b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
// method to return LCM of two numbers
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
//////////////////////////////////////////////////////////////////
static boolean isPrime(long n) {
// Corner cases
if (n <= 1) {
return false;
}
if (n <= 3) {
return true;
}
// This is checked so that we can skip
// middle five numbers in below loop
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 isPowerOfTwo(long n) {
if (n == 0) {
return false;
}
return (long) (Math.ceil((Math.log(n) / Math.log(2))))
== (long) (Math.floor(((Math.log(n) / Math.log(2)))));
}
public static long getFact(int n) {
long ans = 1;
while (n > 0) {
ans *= n;
ans %= MOD;
n--;
}
return ans;
}
public static long pow(long n, int pow) {
if (pow == 0) {
return 1;
}
long temp = pow(n, pow / 2) % MOD;
temp *= temp;
temp %= MOD;
if (pow % 2 == 1) {
temp *= n;
}
temp %= MOD;
return temp;
}
public static long nCr(int n, int r) {
long ans = 1;
int temp = n - r;
while (n > temp) {
ans *= n;
ans %= MOD;
n--;
}
ans *= pow(getFact(r) % MOD, MOD - 2) % MOD;
ans %= MOD;
return ans;
}
//////////////////////////////////////////////////////////////////
// method returns Nth power of A
static double nthRoot(int A, int N) {
// intially guessing a random number between
// 0 and 9
double xPre = Math.random() % 10;
// smaller eps, denotes more accuracy
double eps = 0.001;
// initializing difference between two
// roots by INT_MAX
double delX = 2147483647;
// xK denotes current value of x
double xK = 0.0;
// loop untill we reach desired accuracy
while (delX > eps) {
// calculating current value from previous
// value by newton's method
xK = ((N - 1.0) * xPre
+ (double) A / Math.pow(xPre, N - 1)) / (double) N;
delX = Math.abs(xK - xPre);
xPre = xK;
}
return xK;
}
}
|
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 11
|
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
|
d3c1e5aa5c52fbf9f4fb0b5596044e33
|
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 : Ryan Ranaut
__Hope is a big word, never lose it__
------------- --------------*/
import java.io.*;
import java.util.*;
public class Codeforces1 {
static PrintWriter out = new PrintWriter(System.out);
static final int mod = 1_000_000_007;
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());
}
int[] readIntArray(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());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
/*--------------------------------------------------------------------------*/
//Try seeing general case
static ArrayList<ArrayList<Integer>> adj;
static HashMap<String, Integer> hmp;
static int[] res;
public static void main(String[] args) {
FastReader s = new FastReader();
int t = s.nextInt();
while(t-->0)
{
adj = new ArrayList<>();
hmp = new HashMap<>();
int n = s.nextInt();
res = new int[n-1];
for(int i=0;i<n;i++)
adj.add(new ArrayList<>());
boolean valid = true;
for(int i=0;i<n-1;i++)
{
int u = s.nextInt()-1;
int v = s.nextInt()-1;
adj.get(u).add(v);
adj.get(v).add(u);
String key1 = u+"_"+v;
String key2 = v+"_"+u;
hmp.put(key1, i); hmp.put(key2, i);
if(adj.get(u).size()>2 || adj.get(v).size()>2)
valid = false;
}
int ind = -1;
if(!valid)
out.println("-1");
else {
for (int i = 0; i < n; i++) {
if (adj.get(i).size() == 1) {
ind = i;
break;
}
}
dfs(ind, -1, 1);
for (int x : res)
out.print(x + " ");
}
out.println();
}
out.close();
}
public static void dfs(int u, int par, int flag)
{
for(Integer v: adj.get(u))
{
if(v!=par)
{
String key = u+"_"+v;
int i = hmp.get(key);
res[i] = flag==1?2:3;
dfs(v, u, 1^flag);
}
}
}
/*----------------------------------End of the road--------------------------------------*/
static class DSU {
int[] parent;
int[] ranks;
int[] groupSize;
int size;
public DSU(int n) {
size = n;
parent = new int[n];//0 based
ranks = new int[n];
groupSize = new int[n];//Size of each component
for (int i = 0; i < n; i++) {
parent[i] = i;
ranks[i] = 1; groupSize[i] = 1;
}
}
public int find(int x)//Path Compression
{
if (parent[x] == x)
return x;
else
return parent[x] = find(parent[x]);
}
public void union(int x, int y)//Union by rank
{
int x_rep = find(x);
int y_rep = find(y);
if (x_rep == y_rep)
return;
if (ranks[x_rep] < ranks[y_rep])
{
parent[x_rep] = y_rep;
groupSize[y_rep] += groupSize[x_rep];
}
else if (ranks[x_rep] > ranks[y_rep])
{
parent[y_rep] = x_rep;
groupSize[x_rep] += groupSize[y_rep];
}
else {
parent[y_rep] = x_rep;
ranks[x_rep]++;
groupSize[x_rep] += groupSize[y_rep];
}
size--;//Total connected components
}
}
public static int gcd(int x,int y)
{
return y==0?x:gcd(y,x%y);
}
public static long gcd(long x,long y)
{
return y==0L?x:gcd(y,x%y);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static long pow(long a,long b)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1)
tmp*=a;
a*=a;
b>>=1;
}
return (tmp*a);
}
public static long modPow(long a,long b,long mod)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1L)
tmp*=a;
a*=a;
a%=mod;
tmp%=mod;
b>>=1;
}
return (tmp*a)%mod;
}
static long mul(long a, long b) {
return a*b%mod;
}
static long fact(int n) {
long ans=1;
for (int i=2; i<=n; i++) ans=mul(ans, i);
return ans;
}
static long fastPow(long base, long exp) {
if (exp==0) return 1;
long half=fastPow(base, exp/2);
if (exp%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
static void debug(int ...a)
{
for(int x: a)
out.print(x+" ");
out.println();
}
static void debug(long ...a)
{
for(long x: a)
out.print(x+" ");
out.println();
}
static void debugMatrix(int[][] a)
{
for(int[] x:a)
out.println(Arrays.toString(x));
}
static void debugMatrix(long[][] a)
{
for(long[] x:a)
out.println(Arrays.toString(x));
}
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];
}
static void sort(int[] a)
{
ArrayList<Integer> ls = new ArrayList<>();
for(int x: a) ls.add(x);
Collections.sort(ls);
for(int i=0;i<a.length;i++)
a[i] = ls.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> ls = new ArrayList<>();
for(long x: a) ls.add(x);
Collections.sort(ls);
for(int i=0;i<a.length;i++)
a[i] = ls.get(i);
}
static class Pair{
int x, y;
Pair(int x, int y)
{
this.x = x;
this.y = 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 11
|
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
|
7425e1fdd614639144f9e2cec1ffa170
|
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 : Ryan Ranaut
__Hope is a big word, never lose it__
------------- --------------*/
import java.io.*;
import java.util.*;
public class Codeforces1 {
static PrintWriter out = new PrintWriter(System.out);
static final int mod = 1_000_000_007;
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());
}
int[] readIntArray(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());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
/*--------------------------------------------------------------------------*/
//Try seeing general case
static ArrayList<ArrayList<Integer>> adj;
static HashMap<String, Integer> hmp;
static int[] res;
public static void main(String[] args) {
FastReader s = new FastReader();
int t = s.nextInt();
while(t-->0)
{
adj = new ArrayList<>();
hmp = new HashMap<>();
int n = s.nextInt();
res = new int[n-1];
for(int i=0;i<n;i++)
adj.add(new ArrayList<>());
boolean valid = true;
for(int i=0;i<n-1;i++)
{
int u = s.nextInt()-1;
int v = s.nextInt()-1;
adj.get(u).add(v);
adj.get(v).add(u);
String key1 = u+"_"+v;
String key2 = v+"_"+u;
hmp.put(key1, i); hmp.put(key2, i);
if(adj.get(u).size()>2 || adj.get(v).size()>2)
valid = false;
}
int ind = -1;
if(!valid)
out.println("-1");
else {
for (int i = 0; i < n; i++) {
if (adj.get(i).size() == 1) {
ind = i;
break;
}
}
dfs(ind, -1, 1);
for (int x : res)
out.print(x + " ");
}
out.println();
}
out.close();
}
public static void dfs(int u, int par, int flag)
{
if(par!=-1)
{
String key = u+"_"+par;
int i = hmp.get(key);
res[i] = flag==1?2:3;
}
for(Integer v: adj.get(u))
{
if(v!=par)
dfs(v, u, 1^flag);
}
}
/*----------------------------------End of the road--------------------------------------*/
static class DSU {
int[] parent;
int[] ranks;
int[] groupSize;
int size;
public DSU(int n) {
size = n;
parent = new int[n];//0 based
ranks = new int[n];
groupSize = new int[n];//Size of each component
for (int i = 0; i < n; i++) {
parent[i] = i;
ranks[i] = 1; groupSize[i] = 1;
}
}
public int find(int x)//Path Compression
{
if (parent[x] == x)
return x;
else
return parent[x] = find(parent[x]);
}
public void union(int x, int y)//Union by rank
{
int x_rep = find(x);
int y_rep = find(y);
if (x_rep == y_rep)
return;
if (ranks[x_rep] < ranks[y_rep])
{
parent[x_rep] = y_rep;
groupSize[y_rep] += groupSize[x_rep];
}
else if (ranks[x_rep] > ranks[y_rep])
{
parent[y_rep] = x_rep;
groupSize[x_rep] += groupSize[y_rep];
}
else {
parent[y_rep] = x_rep;
ranks[x_rep]++;
groupSize[x_rep] += groupSize[y_rep];
}
size--;//Total connected components
}
}
public static int gcd(int x,int y)
{
return y==0?x:gcd(y,x%y);
}
public static long gcd(long x,long y)
{
return y==0L?x:gcd(y,x%y);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static long pow(long a,long b)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1)
tmp*=a;
a*=a;
b>>=1;
}
return (tmp*a);
}
public static long modPow(long a,long b,long mod)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1L)
tmp*=a;
a*=a;
a%=mod;
tmp%=mod;
b>>=1;
}
return (tmp*a)%mod;
}
static long mul(long a, long b) {
return a*b%mod;
}
static long fact(int n) {
long ans=1;
for (int i=2; i<=n; i++) ans=mul(ans, i);
return ans;
}
static long fastPow(long base, long exp) {
if (exp==0) return 1;
long half=fastPow(base, exp/2);
if (exp%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
static void debug(int ...a)
{
for(int x: a)
out.print(x+" ");
out.println();
}
static void debug(long ...a)
{
for(long x: a)
out.print(x+" ");
out.println();
}
static void debugMatrix(int[][] a)
{
for(int[] x:a)
out.println(Arrays.toString(x));
}
static void debugMatrix(long[][] a)
{
for(long[] x:a)
out.println(Arrays.toString(x));
}
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];
}
static void sort(int[] a)
{
ArrayList<Integer> ls = new ArrayList<>();
for(int x: a) ls.add(x);
Collections.sort(ls);
for(int i=0;i<a.length;i++)
a[i] = ls.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> ls = new ArrayList<>();
for(long x: a) ls.add(x);
Collections.sort(ls);
for(int i=0;i<a.length;i++)
a[i] = ls.get(i);
}
static class Pair{
int x, y;
Pair(int x, int y)
{
this.x = x;
this.y = 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 11
|
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
|
765b854e5618bc4e03c560227a0995f7
|
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 CF1627C extends PrintWriter {
CF1627C() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1627C o = new CF1627C(); o.main(); o.flush();
}
int[] eo; int[][] eh;
int[] aa, ij;
void append(int i, int h) {
int o = eo[i]++;
if (o >= 2 && (o & o - 1) == 0)
eh[i] = Arrays.copyOf(eh[i], o << 1);
eh[i][o] = h;
}
int d_, i_;
void dfs(int p, int i, int d) {
if (d_ < d) {
d_ = d;
i_ = i;
}
for (int o = eo[i]; o-- > 0; ) {
int h = eh[i][o];
int j = i ^ ij[h];
if (j != p) {
dfs(i, j, d + 1);
aa[h] = 2 + d % 2;
}
}
}
void main() {
int t = sc.nextInt();
out:
while (t-- > 0) {
int n = sc.nextInt();
eo = new int[n]; eh = new int[n][2];
aa = new int[n - 1]; ij = new int[n - 1];
for (int h = 0; h < n - 1; h++) {
int i = sc.nextInt() - 1;
int j = sc.nextInt() - 1;
append(i, h);
append(j, h);
ij[h] = i ^ j;
}
for (int i = 0; i < n; i++)
if (eo[i] >= 3) {
println("-1");
continue out;
}
d_ = -1;
dfs(-1, 0, 0);
d_ = -1;
dfs(-1, i_, 0);
for (int h = 0; h < n - 1; h++)
print(aa[h] + " ");
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 11
|
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
|
8ef44403159def90243f0bde3ac9acef
|
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
|
//<———My cp————
import java.util.*;
import java.io.*;
public class C_Not_Assigning{
public static void main(String[] args) throws Exception{
FastReader fr = new FastReader(System.in);
int t = fr.nextInt();
while(t-->0){
int n = fr.nextInt();
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i = 0;i<=n;i++){
adj.add(new ArrayList<>());
}
ArrayList<String> edges = new ArrayList<>();
for(int i = 0;i<n-1;i++){
int nodeA = fr.nextInt();
int nodeB = fr.nextInt();
adj.get(nodeA).add(nodeB);
adj.get(nodeB).add(nodeA);
edges.add(nodeA+":"+nodeB);
}
boolean poss = true;
for(int i =0;i<=n;i++){
if(adj.get(i).size()>2){
poss=false;
}
}
HashMap<String,Integer> weight = new HashMap<>();
if(poss){
boolean[] visited = new boolean[n+1];
Queue<Integer> queue = new LinkedList<>();
int start = 1;
for(int i = 0;i<adj.size();i++){
if(adj.get(i).size()==1){
start=i;
}
}
queue.add(start);
visited[start]=true;
int last = 2;
while(!queue.isEmpty()){
int node = queue.remove();
ArrayList<Integer> conn = adj.get(node);
for(int i =0;i<conn.size();i++){
int curr = conn.get(i);
if(!visited[curr]){
visited[curr]=true;
queue.add(curr);
if(last==2){
last=3;
}else{
last=2;
}
weight.put(node+":"+curr,last);
weight.put(curr+":"+node,last);
}
}
}
// System.out.println(weight);
for(int i =0;i<edges.size();i++){
System.out.print(weight.get(edges.get(i))+" ");
}
println("");
}else{
System.out.println(-1);
}
}
}
public static void print(Object val){
System.out.print(val);
}
public static void println(Object val){
System.out.println(val);
}
public static int[] sort(int[] vals){
ArrayList<Integer> values = new ArrayList<>();
for(int i = 0;i<vals.length;i++){
values.add(vals[i]);
}
Collections.sort(values);
for(int i =0;i<values.size();i++){
vals[i] = values.get(i);
}
return vals;
}
public static long[] sort(long[] vals){
ArrayList<Long> values = new ArrayList<>();
for(int i = 0;i<vals.length;i++){
values.add(vals[i]);
}
Collections.sort(values);
for(int i =0;i<values.size();i++){
vals[i] = values.get(i);
}
return vals;
}
public static void reverseArray(long[] vals){
int startIndex = 0;
int endIndex = vals.length-1;
while(startIndex<=endIndex){
long temp = vals[startIndex];
vals[startIndex] = vals[endIndex];
vals[endIndex] = temp;
startIndex++;
endIndex--;
}
}
public static void reverseArray(int[] vals){
int startIndex = 0;
int endIndex = vals.length-1;
while(startIndex<=endIndex){
int temp = vals[startIndex];
vals[startIndex] = vals[endIndex];
vals[endIndex] = temp;
startIndex++;
endIndex--;
}
}
static class FastReader{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
public static int GCD(int numA, int numB){
if(numA==0){
return numB;
}else if(numB==0){
return numA;
}else{
if(numA>numB){
return GCD(numA%numB,numB);
}else{
return GCD(numA,numB%numA);
}
}
}
}
|
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 11
|
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
|
426b63f0171ed7738c886a5d9ad6e4cc
|
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
|
/*
Rating: 1378
Date: 27-04-2022
Time: 18-03-49
Author: Kartik Papney
Linkedin: https://www.linkedin.com/in/kartik-papney-4951161a6/
Leetcode: https://leetcode.com/kartikpapney/
Codechef: https://www.codechef.com/users/kartikpapney
----------------------------Jai Shree Ram----------------------------
*/
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class C_Not_Assigning {
public static void find(ArrayList<ArrayList<Integer>> graph, int vtx, int val, HashMap<ArrayList<Integer>, Integer> map) {
for(int nbr : graph.get(vtx)) {
int vtxcpy = vtx;
int nbrcpy = nbr;
if(vtxcpy > nbrcpy) {
int copy = vtxcpy;
vtxcpy = nbrcpy;
nbrcpy = copy;
}
ArrayList<Integer> edge = new ArrayList<>();
edge.add(vtxcpy);
edge.add(nbrcpy);
if(!map.containsKey(edge)) {
map.put(edge, val);
find(graph, nbr, val==2?3:2, map);
}
}
}
public static void s() {
HashMap<ArrayList<Integer>, Integer> map = new HashMap<>();
int n = sc.nextInt();
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
ArrayList<ArrayList<Integer>> values = new ArrayList<>();
for(int i=0; i<=n; i++) graph.add(new ArrayList<>());
for(int i=1; i<=n-1; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
if(x > y) {
int copy = x;
x = y;
y = copy;
}
ArrayList<Integer> xrr = new ArrayList<>();
xrr.add(x);
xrr.add(y);
values.add(xrr);
graph.get(x).add(y);
graph.get(y).add(x);
}
int vtx = -1;
for(int i=1; i<=n; i++) {
if(graph.get(i).size() == 1) {
vtx = i;
}
if(graph.get(i).size() >= 3) {
p.writeln(-1);
return;
}
}
if(vtx == -1) {
p.writeln(-1);
return;
}
find(graph, vtx, 2, map);
// System.out.println(map);
if(map.size() != n-1) {
p.writeln(-1);
return;
}
for(ArrayList<Integer> a : values) {
p.writes(map.get(a));
}
p.writeln();
}
public static void main(String[] args) {
int t = 1;
t = sc.nextInt();
while (t-- != 0) {
s();
}
p.print();
}
public static boolean debug = false;
static void debug(String st) {
if(debug) p.writeln(st);
}
static final Integer MOD = (int) 1e9 + 7;
static final FastReader sc = new FastReader();
static final Print p = new Print();
static class Functions {
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 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);
}
static int max(int... a) {
int max = Integer.MIN_VALUE;
for (int val : a) max = Math.max(val, max);
return max;
}
static int min(int... a) {
int min = Integer.MAX_VALUE;
for (int val : a) min = Math.min(val, min);
return min;
}
static long min(long... a) {
long min = Long.MAX_VALUE;
for (long val : a) min = Math.min(val, min);
return min;
}
static long max(long... a) {
long max = Long.MIN_VALUE;
for (long val : a) max = Math.max(val, max);
return max;
}
static long sum(long... a) {
long sum = 0;
for (long val : a) sum += val;
return sum;
}
static int sum(int... a) {
int sum = 0;
for (int val : a) sum += val;
return sum;
}
public static long mod_add(long a, long b) {
return (a % MOD + b % MOD + MOD) % MOD;
}
public static long pow(long a, long b) {
long res = 1;
while (b > 0) {
if ((b & 1) != 0)
res = mod_mul(res, a);
a = mod_mul(a, a);
b >>= 1;
}
return res;
}
public static long mod_mul(long a, long b) {
long res = 0;
a %= MOD;
while (b > 0) {
if ((b & 1) > 0) {
res = mod_add(res, a);
}
a = (2 * a) % MOD;
b >>= 1;
}
return res;
}
public static long gcd(long a, long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
public static long factorial(long n) {
long res = 1;
for (int i = 1; i <= n; i++) {
res = (i % MOD * res % MOD) % MOD;
}
return res;
}
public static int count(int[] arr, int x) {
int count = 0;
for (int val : arr) if (val == x) count++;
return count;
}
public static ArrayList<Integer> generatePrimes(int n) {
boolean[] primes = new boolean[n];
for (int i = 2; i < primes.length; i++) primes[i] = true;
for (int i = 2; i < primes.length; i++) {
if (primes[i]) {
for (int j = i * i; j < primes.length; j += i) {
primes[j] = false;
}
}
}
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < primes.length; i++) {
if (primes[i]) arr.add(i);
}
return arr;
}
}
static class Print {
StringBuffer strb = new StringBuffer();
public void write(Object str) {
strb.append(str);
}
public void writes(Object str) {
char c = ' ';
strb.append(str).append(c);
}
public void writeln(Object str) {
char c = '\n';
strb.append(str).append(c);
}
public void writeln() {
char c = '\n';
strb.append(c);
}
public void yes() {
char c = '\n';
writeln("YES");
}
public void no() {
writeln("NO");
}
public void writes(int... arr) {
for (int val : arr) {
write(val);
write(' ');
}
}
public void writes(long... arr) {
for (long val : arr) {
write(val);
write(' ');
}
}
public void writeln(int... arr) {
for (int val : arr) {
writeln(val);
}
}
public void print() {
System.out.print(strb);
}
public void println() {
System.out.println(strb);
}
}
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());
}
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;
}
double[] readArrayDouble(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
String nextLine() {
String str = new String();
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 11
|
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
|
2da4243fb0a23ae53cf9bed183a6f8a1
|
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{
int v,c;
edge(int a,int b){
v=a;
c=b;
}
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
StringBuffer sb=new StringBuffer();
int n=sc.nextInt();
int hash[]=new int[n+1];
boolean flag=true;
int num=-1;
List<List<edge>> list=new ArrayList<>();
for(int i=0;i<=n;i++){
list.add(new ArrayList<>());
}
int arr[][]=new int[n-1][2];
for(int i=0;i<n-1;i++){
int a=sc.nextInt();
int b=sc.nextInt();
arr[i][0]=a;
arr[i][1]=b;
list.get(a).add(new edge(b,-1));
list.get(b).add(new edge(a,-1));
hash[a]++;
hash[b]++;
if(hash[a]==3 || hash[b]==3){
flag=false;
}
}
if(!flag){
System.out.print("-1\n");
continue;
}
for(int i=0;i<=n;i++){
if(hash[i]==1){
num=i;
break;
}
}
boolean visit[]=new boolean[n+1];
dfs(list,num,2,visit,-1);
// System.out.println(num);
for(int a[]:arr){
int u=a[0],v=a[1],c=0;
for(edge a1:list.get(u)){
if(a1.v==v){
c=a1.c;
break;
}
}
sb.append(c+" ");
}
System.out.println(sb);
}
}
static void dfs(List<List<edge>> list ,int num,int c,boolean visit[],int p){
if(visit[num]) return;
visit[num]=true;
for(edge a:list.get(num)){
int co=(c==2)?5:2;
if(a.v==p) a.c=c;
else a.c=co;
dfs(list,a.v,co,visit,num);
}
}
}
|
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 11
|
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
|
dd41d8618c26e316d3d432f02031f83a
|
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{
int v,c;
edge(int a,int b){
v=a;
c=b;
}
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
StringBuffer sb=new StringBuffer();
while(t-->0){
int n=sc.nextInt();
int hash[]=new int[n+1];
boolean flag=true;
int num=-1;
List<List<edge>> list=new ArrayList<>();
for(int i=0;i<=n;i++){
list.add(new ArrayList<>());
}
int arr[][]=new int[n-1][2];
for(int i=0;i<n-1;i++){
int a=sc.nextInt();
int b=sc.nextInt();
arr[i][0]=a;
arr[i][1]=b;
list.get(a).add(new edge(b,-1));
list.get(b).add(new edge(a,-1));
hash[a]++;
hash[b]++;
if(hash[a]==3 || hash[b]==3){
flag=false;
}
}
if(!flag){
sb.append("-1\n");
continue;
}
for(int i=0;i<=n;i++){
if(hash[i]==1){
num=i;
break;
}
}
boolean visit[]=new boolean[n+1];
dfs(list,num,2,visit,-1);
// System.out.println(num);
for(int a[]:arr){
int u=a[0],v=a[1],c=0;
for(edge a1:list.get(u)){
if(a1.v==v){
c=a1.c;
break;
}
}
sb.append(c+" ");
}
sb.append("\n");
}
System.out.println(sb);
}
static void dfs(List<List<edge>> list ,int num,int c,boolean visit[],int p){
if(visit[num]) return;
visit[num]=true;
for(edge a:list.get(num)){
int co=(c==2)?5:2;
if(a.v==p) a.c=c;
else a.c=co;
dfs(list,a.v,co,visit,num);
}
}
}
|
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 11
|
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
|
67866e4c9014a3097a13a7d76ca9ee4e
|
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.Practise13001500;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class B{
public static void main(String[] args) throws Exception {new B().run();}
long mod = 1000000000 + 7;
int ans=0;
// int[][] ar;
void solve() throws Exception {
int t=ni();
while(t-->0){
int n = ni();
List<List<int[]>> adj = new ArrayList<>();
for(int i=0;i<=n;i++){
adj.add(new ArrayList<>());
}
for(int i=1;i<n;i++){
int u = ni();
int v = ni();
adj.get(u).add(new int[]{v,i-1});
adj.get(v).add(new int[]{u,i-1});
}
//out.println(adj);
int st=-1;
boolean flag= true;
// for(List<int[]> l:adj){
// for(int[] i:l){
// out.println(i[0]+" "+i[1]);
// }
// }
for(int i=0;i<=n;i++){
if(adj.get(i).size()>2){
flag=false;
}
if(adj.get(i).size()==1) st=i;
}
//out.println(st);
if(!flag){
out.println(-1);
continue;
}
int[] ans= new int[n-1];
boolean[] vis = new boolean[n+1];
dfs(st,adj,vis,ans,0,0);
//ans.remove(ans.size()-1);
for(int i:ans) out.print(i+" ");
out.println();
//out.println(ans);
}
}
void dfs(int v,List<List<int[]>> adj,boolean[] vis,int[] ans,int i,int p){
vis[v]= true;
for(int[] child:adj.get(v)){
if(!vis[child[0]]){
if(child[0]==p)continue;
ans[child[1]]=2+i;
dfs(child[0],adj,vis,ans,i^1,p);
}
}
}
// void buildMatrix(){
//
// for(int i=1;i<=1000;i++){
//
// ar[i][1] = (i*(i+1))/2;
//
// for(int j=2;j<=1000;j++){
// ar[i][j] = ar[i][j-1]+(j-1)+i-1;
// }
// }
// }
/* FAST INPUT OUTPUT & METHODS BELOW */
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
private SpaceCharFilter filter;
PrintWriter out;
int min(int... ar) {
int min = Integer.MAX_VALUE;
for (int i : ar)
min = Math.min(min, i);
return min;
}
long min(long... ar) {
long min = Long.MAX_VALUE;
for (long i : ar)
min = Math.min(min, i);
return min;
}
int max(int... ar) {
int max = Integer.MIN_VALUE;
for (int i : ar)
max = Math.max(max, i);
return max;
}
long max(long... ar) {
long max = Long.MIN_VALUE;
for (long i : ar)
max = Math.max(max, i);
return max;
}
void shuffle(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);
}
long lcm(long a, long b) {
return (a * b) / (gcd(a, b));
}
int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
/*
* for (1/a)%mod = ( a^(mod-2) )%mod ----> use expo to calc -->(a^(mod-2))
*/
long expo(long p, long q) /* (p^q)%mod */
{
long z = 1;
while (q > 0) {
if (q % 2 == 1) {
z = (z * p) % mod;
}
p = (p * p) % mod;
q >>= 1;
}
return z;
}
void run() throws Exception {
in = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
private int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
private int ni() throws IOException {
int c = scan();
while (isSpaceChar(c))
c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = scan();
} while (!isSpaceChar(c));
return res * sgn;
}
private long nl() throws IOException {
long num = 0;
int b;
boolean minus = false;
while ((b = scan()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = scan();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = scan();
}
}
private double nd() throws IOException {
return Double.parseDouble(ns());
}
private String ns() throws IOException {
int c = scan();
while (isSpaceChar(c))
c = scan();
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = scan();
} while (!isSpaceChar(c));
return res.toString();
}
private String nss() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}
private char nc() throws IOException {
int c = scan();
while (isSpaceChar(c))
c = scan();
return (char) c;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
private boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhiteSpace(c);
}
private 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 11
|
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
|
05cccc29ab2f1125f2f6e14239420dce
|
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 codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static class Edge{
int to,index;
Edge(int a, int b){
to=a;
index=b;
}
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t!=0){
t--;
int n = sc.nextInt();
ArrayList<ArrayList<Edge>> adj = new ArrayList<ArrayList<Edge>>(n+1);
for(int i=0;i<=n;i++)
adj.add(new ArrayList<Edge>());
for(int i=0;i<n-1;i++){
int a=sc.nextInt(), b = sc.nextInt();
adj.get(a).add(new Edge(b,i));
adj.get(b).add(new Edge(a,i));
}
int str=-1;boolean fail = false;
for(int i=1;i<=n;i++){
int size = adj.get(i).size();
if(size==1)str=i;
if(!(size==1 || size==2)){fail=true; break;}
}
if(fail){System.out.println("-1"); continue;}
int answer[] =new int[n-1];
int iters = 0;int last=-1;
while(true){
Edge curr = new Edge(-1,-1);
for(Edge e: adj.get(str)){
if(e.to==last)continue;
curr = e;
break;
}
if(curr.to==-1)break;
if(iters%2==0)answer[curr.index]=2;
else answer[curr.index]=3;
last = str;
str = curr.to;
iters++;
}
StringJoiner sj = new StringJoiner(" ");
for(int i=0;i<n-1;i++)
sj.add(""+answer[i]);
System.out.println(sj.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 11
|
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
|
6bbe561f4f97d4d33fc84dccf5df97a1
|
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.time.*;
import static java.lang.Math.*;
@SuppressWarnings("unused")
public class C {
static boolean DEBUG = false;
static Reader fs;
static PrintWriter pw;
static void solve() {
int n = fs.nextInt();
ArrayList<Integer> adj[] = new ArrayList[n + 1];
for (int i = 0; i <= n; i++) {
adj[i] = new ArrayList<Integer>();
}
int edges[][] = new int[n][2];
for (int i = 0; i < n - 1; i++) {
int u = fs.nextInt(), v = fs.nextInt();
edges[i][0] = min(u, v);
edges[i][1] = max(u, v);
adj[u].add(v);
adj[v].add(u);
}
for (int i = 1; i <= n; i++) {
if (adj[i].size() > 2) {
pw.println(-1);
return;
}
}
int leaf = -1;
for (int i = 1; i <= n; i++) {
if (adj[i].size() == 1) {
leaf = i;
break;
}
}
// System.err.println("leaf: " + leaf);
int prev_edges = 2, prev_node = -1;
int index = leaf;
TreeMap<pair, Integer> map = new TreeMap<pair, Integer>();
while(index >= 1 && index <= n) {
int x = -1;
for (int y : adj[index]) {
if (y != prev_node) {
x = y;
}
}
if(x == -1) {
break;
}
if(prev_edges == 2) {
map.put(new pair(min(index, x), max(index, x)), 5);
prev_edges = 5;
}
else {
map.put(new pair(min(index, x), max(index, x)), 2);
prev_edges = 2;
}
prev_node = index;
index = x;
}
// System.err.println(map);
for (int i = 0; i < n-1; i++) {
pair p = new pair(edges[i][0], edges[i][1]);
pw.print(map.get(p) + " ");
}
pw.println();
}
static class pair implements Comparable<pair>{
int f, s;
pair(int f, int s) {
this.f = f;
this.s = s;
}
@Override
public int hashCode() {
return Objects.hash(f, s);
}
@Override
public int compareTo(pair o) {
if(f != o.f)return f - o.f;
else return s - o.s;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{" + f + "," + s + "}");
return sb.toString();
}
}
public static void main(String[] args) throws IOException {
Instant start = Instant.now();
if (args.length == 2) {
System.setIn(new FileInputStream(new File("D:\\program\\javaCPEclipse\\CodeForces\\src\\input.txt")));
// System.setOut(new PrintStream(new File("output.txt")));
System.setErr(new PrintStream(new File("D:\\program\\javaCPEclipse\\CodeForces\\src\\error.txt")));
DEBUG = true;
}
fs = new Reader();
pw = new PrintWriter(System.out);
int t = fs.nextInt();
while (t-- > 0) {
solve();
}
Instant end = Instant.now();
if (DEBUG) {
pw.println(Duration.between(start, end));
}
pw.close();
}
static void sort(int a[]) {
ArrayList<Integer> l = new ArrayList<Integer>();
for (int x : a)
l.add(x);
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
public static void print(long a, long b, long c, PrintWriter pw) {
pw.println(a + " " + b + " " + c);
return;
}
static class Reader {
BufferedReader br;
StringTokenizer st;
public Reader() {
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[] readArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
int[][] read2Array(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] = nextInt();
}
}
return 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 11
|
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
|
c8b507dc2df1f8acd28d3508f8966b57
|
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.time.*;
import static java.lang.Math.*;
@SuppressWarnings("unused")
public class C {
static boolean DEBUG = false;
static Reader fs;
static PrintWriter pw;
static void solve() {
int n = fs.nextInt();
ArrayList<Integer> adj[] = new ArrayList[n + 1];
for (int i = 0; i <= n; i++) {
adj[i] = new ArrayList<Integer>();
}
int edges[][] = new int[n][2];
for (int i = 0; i < n - 1; i++) {
int u = fs.nextInt(), v = fs.nextInt();
edges[i][0] = min(u, v);
edges[i][1] = max(u, v);
adj[u].add(v);
adj[v].add(u);
}
for (int i = 1; i <= n; i++) {
if (adj[i].size() > 2) {
pw.println(-1);
return;
}
}
int leaf = -1;
for (int i = 1; i <= n; i++) {
if (adj[i].size() == 1) {
leaf = i;
break;
}
}
System.err.println("leaf: " + leaf);
int prev_edges = 2, prev_node = -1;
int index = leaf;
TreeMap<pair, Integer> map = new TreeMap<pair, Integer>();
while(index >= 1 && index <= n) {
int x = -1;
for (int y : adj[index]) {
if (y != prev_node) {
x = y;
}
}
if(x == -1) {
break;
}
if(prev_edges == 2) {
map.put(new pair(min(index, x), max(index, x)), 5);
prev_edges = 5;
}
else {
map.put(new pair(min(index, x), max(index, x)), 2);
prev_edges = 2;
}
prev_node = index;
index = x;
}
System.err.println(map);
for (int i = 0; i < n-1; i++) {
pair p = new pair(edges[i][0], edges[i][1]);
pw.print(map.get(p) + " ");
}
pw.println();
}
static class pair implements Comparable<pair>{
int f, s;
pair(int f, int s) {
this.f = f;
this.s = s;
}
@Override
public int hashCode() {
return Objects.hash(f, s);
}
@Override
public int compareTo(pair o) {
if(f != o.f)return f - o.f;
else return s - o.s;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{" + f + "," + s + "}");
return sb.toString();
}
}
public static void main(String[] args) throws IOException {
Instant start = Instant.now();
if (args.length == 2) {
System.setIn(new FileInputStream(new File("D:\\program\\javaCPEclipse\\CodeForces\\src\\input.txt")));
// System.setOut(new PrintStream(new File("output.txt")));
System.setErr(new PrintStream(new File("D:\\program\\javaCPEclipse\\CodeForces\\src\\error.txt")));
DEBUG = true;
}
fs = new Reader();
pw = new PrintWriter(System.out);
int t = fs.nextInt();
while (t-- > 0) {
solve();
}
Instant end = Instant.now();
if (DEBUG) {
pw.println(Duration.between(start, end));
}
pw.close();
}
static void sort(int a[]) {
ArrayList<Integer> l = new ArrayList<Integer>();
for (int x : a)
l.add(x);
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
public static void print(long a, long b, long c, PrintWriter pw) {
pw.println(a + " " + b + " " + c);
return;
}
static class Reader {
BufferedReader br;
StringTokenizer st;
public Reader() {
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[] readArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
int[][] read2Array(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] = nextInt();
}
}
return 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 11
|
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
|
cd06ffee6960f9f2469b6d26480db2ad
|
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 {
static {
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
} catch (Exception e) {}
}
void solve() {
int n = in.nextInt();
ArrayList<Edge>[] graph = new ArrayList[n + 1];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<Edge>();
}
for (int i = 0; i < n - 1; i++) {
int u = in.nextInt();
int v = in.nextInt();
v--; u--;
graph[u].add(new Edge(v, i));
graph[v].add(new Edge(u, i));
}
int[] res = new int[n - 1];
for (int i = 0; i < n; i++) {
if (graph[i].size() > 2) {
out.append("-1\n");
return;
}
}
int start = -1;
for (int i = 0; i < n; i++) {
if (graph[i].size() == 1) {
start = i;
break;
}
}
int currNode = start;
int prevNode = -1;
int weight = 2;
while (true) {
ArrayList<Edge> edges = graph[currNode];
Edge next = edges.get(0);
if (next.node == prevNode) {
if (edges.size() == 1) {
break;
}
next = edges.get(1);
}
res[next.index] = weight;
weight = 5 - weight;
prevNode = currNode;
currNode = next.node;
}
for (int i = 0; i < n - 1; i++) {
out.append(res[i] + " ");
}
out.append("\n");
}
public static void main (String[] args) {
// Its Not Over Untill I Win - Syed Mizbahuddin
Main sol = new Main();
int t = 1;
t = in.nextInt();
while (t-- != 0) {
sol.solve();
}
System.out.print(out);
}
<T> void println(T[] s) {
System.out.println(Arrays.toString(s));
}
<T> void println(T s) {
System.out.println(s);
}
void print(int s) {
System.out.print(s);
}
void println(int s) {
System.out.println(s);
}
void println(int[] a) {
println(Arrays.toString(a));
}
int[] array(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
return a;
}
int[] array1(int n) {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
}
return a;
}
static FastReader in;
static StringBuffer out;
final int MAX;
final int MIN;
int mod ;
Main() {
in = new FastReader();
out = new StringBuffer();
MAX = Integer.MAX_VALUE;
MIN = Integer.MIN_VALUE;
mod = (int)1e9 + 7;
}
}
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;
}
}
class Edge {
int node, index;
Edge(int node, int index) {
this.node = node;
this.index = index;
}
}
|
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 11
|
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
|
3e941f2a90d6f9edd19ad11dfc33aab0
|
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.lang.*;
public class Main{
public static void main(String args[]){
InputReader in=new InputReader(System.in);
TASK solver = new TASK();
int t=1;
t = in.nextInt();
for(int i=1;i<=t;i++)
{
solver.solve(in,i);
}
}
static class TASK {
static int mod = 1000000007;
static ArrayList<Integer> al[];
static int x[] ={2,5};
static int dp[];
static boolean flag[];
static Map<String,Integer> map;
static int ii=0;
static void solve(int idx)
{
flag[idx]=true;
for(int i=0;i<al[idx].size();i++)
{
int xx = al[idx].get(i);
if(!flag[xx])
{
int y = map.get(idx+" "+xx);
dp[y]=x[(ii)%2];
ii++;
solve(xx);
}
}
}
static void solve(InputReader in, int testNumber) {
int n= in.nextInt();
al = new ArrayList[n+1];
dp=new int[n-1];
flag=new boolean[n+1];
for(int i=0;i<=n;i++)
{
al[i]=new ArrayList<>();
}
map = new HashMap<>();
boolean flag = true;
for(int i=0;i<n-1;i++)
{
int x = in.nextInt();
int y = in.nextInt();
al[x].add(y);
al[y].add(x);
if(al[x].size()>2)
flag=false;
if(al[y].size()>2)
flag=false;
map.put(x+" "+y,i);
map.put(y+" "+x,i);
}
if(!flag)
{
System.out.println(-1);
return;
}
int idx=0;
for(int i=1;i<=n;i++)
{
if(al[i].size()==1)
{
idx=i;
}
}
solve(idx);
for(int i=0;i<n-1;i++)
{
System.out.print(dp[i]+" ");
}
System.out.println();
}
}
static class pair{
int x;
long y;
boolean flag;
pair(int x,long y,boolean flag)
{
this.x=x;
this.y=y;
this.flag=false;
}
}
static class ladder{
int a[] = new int[5];
ladder(int a[])
{
for(int i=0;i<5;i++)
{
this.a[i]=a[i];
}
}
}
static class Maths {
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static long factorial(int n) {
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c
== -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
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 11
|
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
|
24ce8cd3b6d14d6c3bcbae3431d8730b
|
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.lang.Math;
public class c {
// static int mod = 998244353;
static int mod = 1000000007;
static int count;
public static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main(String[] args) throws Exception {
Reader scn = new Reader();
PrintWriter pw = new PrintWriter(System.out);
int t = scn.nextInt();
outer : while(t-->0){
int n = scn.nextInt();
count = 0;
ArrayList<Edge>[] graph = new ArrayList[n+1];
for(int i=0; i<graph.length; i++){
graph[i] = new ArrayList<>();
}
int[] degree = new int[n+1];
for(int i=0; i<n-1; i++){
int u = scn.nextInt();
int v = scn.nextInt();
addEdge(graph, u, v, i);
degree[u]++;
degree[v]++;
}
int src = -1;
for(int i=1; i<=n; i++){
if(degree[i] >= 3){
pw.println(-1);
continue outer;
}
if(degree[i] == 1){
src = i;
}
}
boolean[] visited = new boolean[n+1];
dfs(graph, src, visited);
int[] ans = new int[n+1];
for(int i=1; i<=n; i++){
ArrayList<Edge> list = graph[i];
for(var v : list){
ans[v.edgeno] = v.wt;
}
}
for(int i=1; i<n; i++){
pw.print(ans[i] + " ");
}
pw.println();
}
pw.close();
}
private static void dfs(ArrayList<Edge>[] graph, int src, boolean[] visited){
visited[src] = true;
for(Edge e : graph[src]){
if(visited[e.nbr] == false){
if(count % 2 == 0){
e.wt = 2;
Edge ee = graph[e.nbr].get(0);
if(ee.nbr == src){
ee.wt = 2;
}else{
Edge eee = graph[e.nbr].get(1);
eee.wt = 2;
}
}else{
e.wt = 3;
Edge ee = graph[e.nbr].get(0);
if(ee.nbr == src){
ee.wt = 3;
}else{
Edge eee = graph[e.nbr].get(1);
eee.wt = 3;
}
}
count++;
dfs(graph, e.nbr, visited);
}
}
}
private static void addEdge(ArrayList<Edge>[] graph, int u, int v, int no){
graph[u].add(new Edge(v, (no+1), 0));
graph[v].add(new Edge(u, (no+1), 0));
}
public static class Edge{
int nbr;
int edgeno;
int wt;
Edge(int nbr, int edgeno, int wt){
this.nbr = nbr;
this.edgeno = edgeno;
this.wt = wt;
}
}
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);
}
}
private static void sort(long[] arr) {
List<Long> 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);
}
}
// private static void sort(Pair[] arr) {
// List<Pair> 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);
// }
// }
private static 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()); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void reverseSort(long[] arr){
List<Long> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list, Collections.reverseOrder()); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void reverseSort(ArrayList<Integer> list){
Collections.sort(list, Collections.reverseOrder());
}
private static 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;
}
private static 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;
}
private static 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;
}
// (x^y)%p in O(logy)
private 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;
}
public static 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);
}
reverse(arr, last+1, arr.length-1);
return true;
}
private static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static void reverse(int[] arr, int i, int j){
while(i < j){
swap(arr, i++, j--);
}
}
private static String reverseStr(String s){
StringBuilder sb = new StringBuilder(s);
return sb.reverse().toString();
}
// TC- O(logmax(a,b))
private static int gcd(int a, int b) {
if(a == 0){
return b;
}
return gcd(b%a, a);
}
private static long gcd(long a, long b) {
if(a == 0L){
return b;
}
return gcd(b%a, a);
}
private static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
// TC- O(logmax(a,b))
private static int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
private static long inv(long x){
return power(x, mod - 2);
}
private static long summation(long n){
return (n * (n + 1L)) >> 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 11
|
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
|
3b3210c1be6d8f6761eefb9b118cbdcf
|
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.StringTokenizer;
public class C {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
StringBuilder sb = new StringBuilder();
while (t-- > 0) {
int N = Integer.parseInt(br.readLine().trim());
ArrayList<HashMap<Integer, Integer>> graph = new ArrayList<>(N + 1);
ArrayList<int[]> edges = new ArrayList<>(N);
for (int i = 0; i <= N; i++)
graph.add(new HashMap<>(2));
for (int i = 1; i < N; i++) {
int inp[] = nextIntArray(2, br);
edges.add(inp);
graph.get(inp[0]).put(inp[1], 0);
graph.get(inp[1]).put(inp[0], 0);
}
sb.append(solve(graph, edges)).append("\n");
}
br.close();
System.out.println(sb);
}
private static String solve(ArrayList<HashMap<Integer, Integer>> graph, ArrayList<int[]> edges) {
int start = -1;
for (int i = 1; i < graph.size(); i++) {
if (graph.get(i).size() > 2)
return "-1";
if (graph.get(i).size() == 1)
start = i;
}
// System.out.println("Starting Index : " + start);
dfs(graph, 0, start);
StringBuilder sb = new StringBuilder();
for (int[] edge : edges)
sb.append(graph.get(edge[0]).get(edge[1])).append(" ");
return sb.toString();
}
private static void dfs(ArrayList<HashMap<Integer, Integer>> graph, int prev, int cur) {
HashMap<Integer, Integer> connections = graph.get(cur);
int prevDist = connections.getOrDefault(prev, 0);
for (int i : graph.get(cur).keySet()) {
if (i == prev)
continue;
// Updating the Edges for both Nodes cur and I
if (prevDist % 2 == 0) {
graph.get(i).put(cur, 5);
graph.get(cur).put(i, 5);
} else {
graph.get(i).put(cur, 2);
graph.get(cur).put(i, 2);
}
dfs(graph, cur, i);
}
}
private static int[] nextIntArray(int N, BufferedReader br) throws Exception {
StringTokenizer st = new StringTokenizer(br.readLine().trim(), " ");
int arr[] = new int[N];
for (int i = 0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
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 11
|
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
|
a379fa3efbf07a0d1aa25a38203d0c01
|
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.StringTokenizer;
public class C {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
StringBuilder sb = new StringBuilder();
while (t-- > 0) {
int N = Integer.parseInt(br.readLine().trim());
ArrayList<HashMap<Integer, Integer>> graph = new ArrayList<>(N + 1);
ArrayList<int[]> edges = new ArrayList<>(N);
for (int i = 0; i <= N; i++)
graph.add(new HashMap<>());
for (int i = 1; i < N; i++) {
int inp[] = nextIntArray(2, br);
edges.add(inp);
graph.get(inp[0]).put(inp[1], 0);
graph.get(inp[1]).put(inp[0], 0);
}
sb.append(solve(graph, edges)).append("\n");
}
br.close();
System.out.println(sb);
}
private static String solve(ArrayList<HashMap<Integer, Integer>> graph, ArrayList<int[]> edges) {
int start = -1;
for (int i = 1; i < graph.size(); i++) {
if (graph.get(i).size() > 2)
return "-1";
if (graph.get(i).size() == 1)
start = i;
}
// System.out.println("Starting Index : " + start);
dfs(graph, 0, start);
StringBuilder sb = new StringBuilder();
for (int[] edge : edges)
sb.append(graph.get(edge[0]).get(edge[1])).append(" ");
return sb.toString();
}
private static void dfs(ArrayList<HashMap<Integer, Integer>> graph, int prev, int cur) {
HashMap<Integer, Integer> connections = graph.get(cur);
int prevDist = connections.getOrDefault(prev, 0);
for (int i : graph.get(cur).keySet()) {
if (i == prev)
continue;
// Updating the Edges for both Nodes cur and I
if (prevDist % 2 == 0) {
graph.get(i).put(cur, 5);
graph.get(cur).put(i, 5);
} else {
graph.get(i).put(cur, 2);
graph.get(cur).put(i, 2);
}
dfs(graph, cur, i);
}
}
private static int[] nextIntArray(int N, BufferedReader br) throws Exception {
StringTokenizer st = new StringTokenizer(br.readLine().trim(), " ");
int arr[] = new int[N];
for (int i = 0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
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 11
|
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
|
2111f1a7027a313a2eebc9409b6b1dcf
|
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.StringTokenizer;
public class C {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
StringBuilder sb = new StringBuilder();
while (t-- > 0) {
int N = Integer.parseInt(br.readLine().trim());
ArrayList<HashMap<Integer, Integer>> graph = new ArrayList<>(N + 1);
ArrayList<int[]> edges = new ArrayList<>(N);
for (int i = 0; i <= N; i++)
graph.add(new HashMap<>());
for (int i = 1; i < N; i++) {
int inp[] = nextIntArray(2, br);
edges.add(inp);
graph.get(inp[0]).put(inp[1], 0);
graph.get(inp[1]).put(inp[0], 0);
}
sb.append(solve(graph, edges)).append("\n");
}
br.close();
System.out.println(sb);
}
private static String solve(ArrayList<HashMap<Integer, Integer>> graph, ArrayList<int[]> edges) {
int start = -1;
for (int i = 1; i < graph.size(); i++) {
if (graph.get(i).size() > 2)
return "-1";
if (graph.get(i).size() == 1)
start = i;
}
// System.out.println("Starting Index : " + start);
dfs(graph, 0, start);
StringBuilder sb = new StringBuilder();
for (int[] edge : edges)
sb.append(Math.max(graph.get(edge[0]).get(edge[1]), graph.get(edge[1]).get(edge[0]))).append(" ");
return sb.toString();
}
private static void dfs(ArrayList<HashMap<Integer, Integer>> graph, int prev, int cur) {
HashMap<Integer, Integer> connections = graph.get(cur);
int prevDist = connections.getOrDefault(prev, 0);
for (int i : graph.get(cur).keySet()) {
if (i == prev)
continue;
if (prevDist % 2 == 0)
graph.get(i).put(cur, 5);
else
graph.get(i).put(cur, 2);
dfs(graph, cur, i);
}
}
private static int[] nextIntArray(int N, BufferedReader br) throws Exception {
StringTokenizer st = new StringTokenizer(br.readLine().trim(), " ");
int arr[] = new int[N];
for (int i = 0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
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 11
|
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
|
67dc58cf3a03af4104edc6af229afde8
|
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.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class C {
static class scanner {
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()) {
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 long min(long a, long b) {return Math.min(a, b);}
static long min(long a, long b, long c) {return min(a, min(b, c));}
static int min(int a, int b) {return Math.min(a, b);}
static int min(int a, int b, int c) {return min(a, min(b, c));}
static long max(long a, long b) {return Math.max(a, b);}
static long max(long a, long b, long c) {return max(a, max(b, c));}
static int max(int a, int b) {return Math.max(a, b);}
static int max(int a, int b, int c) {return max(a, max(b, c));}
static int abs(int x) {return Math.abs(x);}
static long abs(long x) {return Math.abs(x);}
static long ceil(double x) {return (long) Math.ceil(x);}
static long floor(double x) {return (long) Math.floor(x);}
static int ceil(int x) {return (int) Math.ceil(x);}
static int floor(int x) {return (int) Math.floor(x);}
static double sqrt(double x) {return Math.sqrt(x);}
static double cbrt(double x) {return Math.cbrt(x);}
static long sqrt(long x) {return (long) Math.sqrt(x);}
static long cbrt(long x) {return (long) Math.cbrt(x);}
static int gcd(int a, int b) {if(b == 0)return a;return gcd(b, a % b);}
static long gcd(long a, long b) {if(b == 0)return a;return gcd(b, a % b);}
static double pow(double n, double power) {return Math.pow(n, power);}
static long pow(long n, double power) {return (long) Math.pow(n, power);}
static class Pair {int first, second;public Pair(int first, int second) {this.first = first;this.second = second;}}
public static void main(String[] args) throws IOException {
scanner.init(System.in);
int t = 1;
t = scanner.nextInt();
while (t-- > 0) {
solve();
}
}
static void solve() throws IOException {
int n = scanner.nextInt();
List<List<Pair>> tree = new ArrayList<>();
for (int i = 0; i < n; i++) {
tree.add(new ArrayList<>());
}
for (int i = 0; i < n-1; i++) {
int u = scanner.nextInt()-1;
int v = scanner.nextInt()-1;
tree.get(u).add(new Pair(v, i));
tree.get(v).add(new Pair(u, i));
}
int start = -1;
for (int i = 0; i < n; i++) {
if(tree.get(i).size() > 2) {
System.out.println(-1);
return;
}
else if(tree.get(i).size() == 1) {
start = i;
}
}
int[] res = new int[n-1];
Queue<Integer> q = new LinkedList<>();
q.add(start);
int weight = 2, prev = -1;
while (!q.isEmpty()) {
int u = q.poll();
for(Pair v : tree.get(u)) {
if(v.first != prev) {
q.add(v.first);
res[v.second] = weight;
weight = 5 - weight;
}
}
prev = u;
}
for(int i : res) {
System.out.print(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 11
|
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
|
acbc4ca62fbf3f52f25b2e0a8c1372b7
|
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.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class C {
static class scanner {
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()) {
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 long min(long a, long b) {return Math.min(a, b);}
static long min(long a, long b, long c) {return min(a, min(b, c));}
static int min(int a, int b) {return Math.min(a, b);}
static int min(int a, int b, int c) {return min(a, min(b, c));}
static long max(long a, long b) {return Math.max(a, b);}
static long max(long a, long b, long c) {return max(a, max(b, c));}
static int max(int a, int b) {return Math.max(a, b);}
static int max(int a, int b, int c) {return max(a, max(b, c));}
static int abs(int x) {return Math.abs(x);}
static long abs(long x) {return Math.abs(x);}
static long ceil(double x) {return (long) Math.ceil(x);}
static long floor(double x) {return (long) Math.floor(x);}
static int ceil(int x) {return (int) Math.ceil(x);}
static int floor(int x) {return (int) Math.floor(x);}
static double sqrt(double x) {return Math.sqrt(x);}
static double cbrt(double x) {return Math.cbrt(x);}
static long sqrt(long x) {return (long) Math.sqrt(x);}
static long cbrt(long x) {return (long) Math.cbrt(x);}
static int gcd(int a, int b) {if(b == 0)return a;return gcd(b, a % b);}
static long gcd(long a, long b) {if(b == 0)return a;return gcd(b, a % b);}
static double pow(double n, double power) {return Math.pow(n, power);}
static long pow(long n, double power) {return (long) Math.pow(n, power);}
public static void main(String[] args) throws IOException {
scanner.init(System.in);
int t = 1;
t = scanner.nextInt();
while (t-- > 0) {
solve();
}
}
static void solve() throws IOException {
int n = scanner.nextInt();
List<List<Pair>> tree = new ArrayList<>();
for (int i = 0; i <= n; i++) {
tree.add(new ArrayList<>());
}
for (int i = 0; i < n-1; i++) {
int u = scanner.nextInt()-1;
int v = scanner.nextInt()-1;
tree.get(u).add(new Pair(v, i));
tree.get(v).add(new Pair(u, i));
}
int start = -1;
for (int i = 0; i < n; i++) {
if(tree.get(i).size() > 2) {
System.out.println(-1);
return;
}
else if(tree.get(i).size() == 1) {
start = i;
}
}
res = new int[n-1];
dfs(tree, start, -1, 2);
for(int i : res) {
System.out.print(i + " ");
}
System.out.println();
}
static int[] res;
static void dfs(List<List<Pair>> tree, int u, int parent, int weight) {
for(Pair v : tree.get(u)) {
if(v.first != parent) {
res[v.second] = weight;
dfs(tree, v.first, u, 5-weight);
}
}
}
}
class Pair {
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
}
|
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 11
|
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
|
c56a73022276ff3f4d284a22131ddf1a
|
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 IOException {
try {
int t = sc.nextInt();
while (t-- > 0)
solve();
} catch (Exception e) {
return;
}
out.flush();
}
// SOLUTION STARTS HERE
// :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
static void solve() {
int n = sc.nextInt();
int ind[] = new int[n + 1];
boolean ans = true;
ArrayList<Integer>[] tree = new ArrayList[n + 1];
for (int i = 0; i <= n; i++)
tree[i] = new ArrayList<>();
int edges[][] = new int[n - 1][2];
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt(), v = sc.nextInt();
edges[i][0] = u;
edges[i][1] = v;
ind[u]++;
ind[v]++;
tree[u].add(v);
tree[v].add(u);
if (ind[u] > 2 || ind[v] > 2)
ans = false;
}
// for(int e[] : edges) System.out.println(Arrays.toString(e));
if (!ans) {
System.out.println(-1);
return;
}
int root = -1;
for (int i = 0; i <= n; i++)
if (ind[i] == 1)
root = i;
HashMap<String, Integer> w = new HashMap<>();
boolean vis[] = new boolean[n + 1];
dfs(root, tree, vis, 2, w);
for (int e[] : edges) {
if (w.containsKey(e[0] + " " + e[1])) {
System.out.print(w.get(e[0] + " " + e[1]) + " ");
} else if (w.containsKey(e[1] + " " + e[0])) {
System.out.print(w.get(e[1] + " " + e[0]) + " ");
}
}
System.out.println();
}
static void dfs(int node, ArrayList<Integer>[] tree, boolean[] vis, int curr, HashMap<String, Integer> w) {
vis[node] = true;
for (int next : tree[node]) {
if (!vis[next]) {
vis[next] = true;
w.put(node + " " + next, curr);
dfs(next, tree, vis, 7 - curr, w);
}
}
}
// SOLUTION ENDS HERE
// :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
static class DSU {
int rank[];
int parent[];
DSU(int n) {
rank = new int[n + 1];
parent = new int[n + 1];
for (int i = 1; i <= n; i++) {
parent[i] = i;
}
}
int findParent(int node) {
if (parent[node] == node)
return node;
return parent[node] = findParent(parent[node]);
}
boolean union(int x, int y) {
int px = findParent(x);
int py = findParent(y);
if (px == py)
return false;
if (rank[px] < rank[py]) {
parent[px] = py;
} else if (rank[px] > rank[py]) {
parent[py] = px;
} else {
parent[px] = py;
rank[py]++;
}
return true;
}
}
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[] seiveOfEratosthenes(int n) {
boolean[] isPrime = new boolean[n + 1];
Arrays.fill(isPrime, true);
for (int i = 2; i * i <= n; i++) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
return isPrime;
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean isPrime(long n) {
if (n < 2)
return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
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());
}
char[][] readCharMatrix(int n, int m) {
char a[][] = new char[n][m];
for (int i = 0; i < n; i++) {
String s = sc.next();
for (int j = 0; j < m; j++) {
a[i][j] = s.charAt(j);
}
}
return a;
}
long nextLong() {
return Long.parseLong(next());
}
int[] readIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(next());
}
return a;
}
void printIntArray(int a[]) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
long[] readLongArray(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = Long.parseLong(next());
}
return a;
}
void printLongArray(long a[]) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
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();
}
}
private static final FastReader sc = new FastReader();
private static final FastWriter out = new FastWriter(System.out);
}
|
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 11
|
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
|
2c557114db4f60c1799a7daefd330195
|
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);
// long mod = 1_000_000_007L;
// long mod = 998_244_353L;
int t = sc.nextInt();
for ( int zzz=0; zzz<t; zzz++ ) {
int n = sc.nextInt();
HashMap<Integer, HashSet<Integer>> adj = new HashMap<>();
HashMap<HashSet<Integer>, Integer> inv = new HashMap<>();
boolean f = false;
for ( int i=0; i<n-1; i++ ) {
int u = sc.nextInt();
int v = sc.nextInt();
if ( adj.containsKey(u) ) {
HashSet<Integer> s = adj.get(u);
if ( s.size()>1 ) f = true;
s.add(v);
adj.put(u, s);
} else {
HashSet<Integer> s = new HashSet<>();
s.add(v);
adj.put(u, s);
}
if ( adj.containsKey(v) ) {
HashSet<Integer> s = adj.get(v);
if ( s.size()>1 ) f = true;
s.add(u);
adj.put(v, s);
} else {
HashSet<Integer> s = new HashSet<>();
s.add(u);
adj.put(v, s);
}
HashSet<Integer> si = new HashSet<>();
si.add(u);
si.add(v);
inv.put(si, i);
}
if ( f ) {
System.out.println(-1);
continue;
}
String[] ans = new String[n-1];
boolean g = false;
ArrayDeque<Integer> q = new ArrayDeque<>();
q.addLast(1);
boolean[] seen = new boolean[n+1];
while ( q.size()>0 ) {
int v = q.removeLast();
seen[v] = true;
HashSet<Integer> s = adj.get(v);
for ( int e : s ) {
if ( seen[e] ) continue;
HashSet<Integer> st = new HashSet<>();
st.add(v);
st.add(e);
int pos = inv.get(st);
if ( g ) {
ans[pos] = "3";
} else {
ans[pos] = "2";
}
g = !g;
q.addLast(e);
break;
}
}
g = true;
q.addLast(1);
while ( q.size()>0 ) {
int v = q.removeLast();
seen[v] = true;
HashSet<Integer> s = adj.get(v);
for ( int e : s ) {
if ( seen[e] ) continue;
HashSet<Integer> st = new HashSet<>();
st.add(v);
st.add(e);
int pos = inv.get(st);
if ( g ) {
ans[pos] = "3";
} else {
ans[pos] = "2";
}
g = !g;
q.addLast(e);
break;
}
}
System.out.println(String.join(" ", 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 11
|
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
|
e24a5bc7303dc2b186bb79c24e43679f
|
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.BigInteger;
public class Main {
private static FS sc = new FS();
private static class FS {
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());
}
}
private static class extra {
static int[] intArr(int size) {
int[] a = new int[size];
for(int i = 0; i < size; i++) a[i] = sc.nextInt();
return a;
}
static long[] longArr(int size) {
Scanner scc = new Scanner(System.in);
long[] a = new long[size];
for(int i = 0; i < size; i++) a[i] = sc.nextLong();
return a;
}
static long intSum(int[] a) {
long sum = 0;
for(int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
static long longSum(long[] a) {
long sum = 0;
for(int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
static LinkedList[] graphD(int vertices, int edges) {
LinkedList<Integer>[] temp = new LinkedList[vertices+1];
for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>();
for(int i = 0; i < edges; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
temp[x].add(y);
}
return temp;
}
static LinkedList[] graphUD(int vertices, int edges) {
LinkedList<Integer>[] temp = new LinkedList[vertices+1];
for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>();
for(int i = 0; i < edges; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
temp[x].add(y);
temp[y].add(x);
}
return temp;
}
static void printG(LinkedList[] temp) { for(LinkedList<Integer> aa:temp) System.out.println(aa); }
static long cal(long val, long pow, long mod) {
if(pow == 0) return 1;
long res = cal(val, pow/2, mod);
long ret = (res*res)%mod;
if(pow%2 == 0) return ret;
return (val*ret)%mod;
}
static long gcd(long a, long b) { return b == 0 ? a:gcd(b, a%b); }
}
static int mod = (int) 1e9;
static LinkedList<Integer>[] temp, idx;
static long inf = (long) Long.MAX_VALUE;
// static long inf = Long.MAX_VALUE;
// static int max;
static StringBuilder out;
public static void main(String[] args) {
int t = sc.nextInt();
// int t = 1;
StringBuilder ret = new StringBuilder();
while(t-- > 0) {
int n = sc.nextInt();
temp = new LinkedList[n+1];
HashMap<String, Integer> map1 = new HashMap<>();
for(int i = 0; i <= n; i++) temp[i] = new LinkedList<>();
for(int i = 0; i < n-1; i++) {
int from = sc.nextInt(), to = sc.nextInt();
temp[from].add(to);
temp[to].add(from);
map1.put(from + " " + to, i);
map1.put(to + " " + from, i);
}
int flag = 0;
for(int i = 1; i <= n; i++) if(temp[i].size() > 2) flag = 1;
if(flag == 1) ret.append(-1 + "\n");
else {
int[] a = new int[n-1];
flag = 0;
HashMap<String, Integer> map = new HashMap<>();
dfs(1, -1, 0, a, map);
// System.out.println(map);
for(String aa:map1.keySet()) {
if(map.containsKey(aa)) a[map1.get(aa)] = map.get(aa);
}
for(int aa:a) ret.append(aa + " ");
}
ret.append("\n");
}
System.out.println(ret);
}
static void dfs(int s, int p, int flag, int[] a, HashMap<String, Integer> map) {
for(int aa:temp[s]) {
if(aa != p) {
if(flag == 0) map.put(aa + " " + s, 2);
else map.put(aa + " " + s, 3);
flag ^= 1;
dfs(aa, s, flag, a, map);
}
}
}
}
|
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 11
|
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
|
f5051c3e28acfa33035e2ff7f3e66cba
|
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 codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{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 int mod = 998244353 ;
// static int N = 200005;
// static long factorial_num_inv[] = new long[N+1];
// static long natual_num_inv[] = new long[N+1];
// static long fact[] = new long[N+1];
// static void InverseofNumber()
//{
// natual_num_inv[0] = 1;
// natual_num_inv[1] = 1;
// for (int i = 2; i <= N; i++)
// natual_num_inv[i] = natual_num_inv[mod % i] * (mod - mod / i) % mod;
//}
//static void InverseofFactorial()
//{
// factorial_num_inv[0] = factorial_num_inv[1] = 1;
// for (int i = 2; i <= N; i++)
// factorial_num_inv[i] = (natual_num_inv[i] * factorial_num_inv[i - 1]) % mod;
//}
//static long nCrModP(long N, long R)
//{
// long ans = ((fact[(int)N] * factorial_num_inv[(int)R]) % mod * factorial_num_inv[(int)(N - R)]) % mod;
// return ans%mod;
//}
//static boolean prime[];
//static void sieveOfEratosthenes(int n)
//{
// 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] is not changed, then it is a
// // prime
// if (prime[p] == true)
// {
// // Update all multiples of p
// for (int i = p * p; i <= n; i += p)
// prime[i] = false;
// }
// }
//}
static int visited[];
static HashMap<Pair,Integer> hm;
public static void main (String[] args) throws java.lang.Exception
{
// InverseofNumber();
// InverseofFactorial();
// fact[0] = 1;
// for (long i = 1; i <= 2*100000; i++)
// {
// fact[(int)i] = (fact[(int)i - 1] * i) % mod;
// }
FastReader scan = new FastReader();
PrintWriter pw = new PrintWriter(System.out);
int t = scan.nextInt();
while(t-->0){
int n = scan.nextInt();
List<List<Integer>> a = new ArrayList<List<Integer>>();
for(int i=0;i<=n;i++){
a.add(new ArrayList<Integer>());
}
Pair edge[] = new Pair[n-1];
for(int i=0;i<n-1;i++){
int x = scan.nextInt();
int y = scan.nextInt();
edge[i] = new Pair(x,y);
a.get(x).add(y);
a.get(y).add(x);
}
int flag=0;
int start = -1;
for(int i=1;i<=n;i++){
if(a.get(i).size()>2)
flag = 1;
if(a.get(i).size()==1)
start = i;
}
if(flag==1)
pw.println(-1);
else{
visited = new int[n+1];
hm = new HashMap<Pair,Integer>();
dfs(a,start,2);
for(int i=0;i<n-1;i++){
int x = edge[i].x;
int y = edge[i].y;
pw.print(hm.get(new Pair(x,y))+" ");
}
pw.println();
}
pw.flush();
}
}
static void dfs(List<List<Integer>> a,int start,int parent){
if(visited[start]==0){
visited[start] = 1;
List<Integer> temp = a.get(start);
int len = temp.size();
for(int i=0;i<len;i++){
int end = temp.get(i);
if(parent==2){
hm.put(new Pair(start,end),3);
hm.put(new Pair(end,start),3);
dfs(a,end,3);
}
else{
hm.put(new Pair(start,end),2);
hm.put(new Pair(end,start),2);
dfs(a,end,2);
}
}
}
}
//static long bin_exp_mod(long a,long n){
// long res = 1;
// if(a==0)
// return 0;
// while(n!=0){
// if(n%2==1){
// res = ((res)*(a));
// }
// n = n/2;
// a = ((a)*(a));
// }
// return res;
//}
//static long bin_exp_mod(long a,long n){
// long mod = 1000000007;
// long res = 1;
// a = a%mod;
// if(a==0)
// return 0;
// while(n!=0){
// if(n%2==1){
// res = ((res%mod)*(a%mod))%mod;
// }
// n = n/2;
// a = ((a%mod)*(a%mod))%mod;
// }
// res = res%mod;
// return res;
//}
// static long gcd(long a,long b){
// if(a==0)
// return b;
// return gcd(b%a,a);
// }
// static long lcm(long a,long b){
// return (a/gcd(a,b))*b;
// }
}
class Pair{
Integer x,y;
Pair(int x,int y){
this.x = x;
this.y = y;
}
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(obj instanceof Pair)
{
Pair temp = (Pair) obj;
if(this.x.equals(temp.x) && this.y.equals(temp.y))
return true;
}
return false;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return (this.x.hashCode() + this.y.hashCode());
}
}
//class Compar implements Comparator<Pair>{
// public int compare(Pair p1,Pair p2){
// if(p1.x==p2.x)
// return 0;
// else if(p1.x<p2.x)
// return -1;
// else
// return 1;
// }
//}
//class Node{
// int src,dest,weight;
// Node(int src,int dest,int weight){
// this.src = src;
// this.dest = dest;
// this.weight = weight;
// }
//}
|
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 11
|
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
|
7b8a01cf3640300792ce8ace18e816bf
|
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 class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static FastReader obj = new FastReader();
public static PrintWriter out = new PrintWriter(System.out);
public static void sort(long[] a) {
ArrayList<Long> arr = new ArrayList<>();
for (int i = 0; i < a.length; i++)
arr.add(a[i]);
Collections.sort(arr);
for (int i = 0; i < arr.size(); i++)
a[i] = arr.get(i);
}
public static void revsort(long[] a) {
ArrayList<Long> arr = new ArrayList<>();
for (int i = 0; i < a.length; i++)
arr.add(a[i]);
Collections.sort(arr, Collections.reverseOrder());
for (int i = 0; i < arr.size(); i++)
a[i] = arr.get(i);
}
//Cover the small test cases like for n=1 .
public static class pair {
int a;
int b;
pair(int x, int y) {
a = x;
b = y;
}
}
public static long l() {
return obj.nextLong();
}
public static int i() {
return obj.nextInt();
}
public static String s() {
return obj.next();
}
public static long[] l(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = l();
return arr;
}
public static int[] i(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = i();
return arr;
}
public static long ceil(long a, long b) {
return (a + b - 1) / b;
}
public static void p(long val) {
out.println(val);
}
public static void p(String s) {
out.println(s);
}
public static void pl(long[] arr) {
for (int i = 0; i < arr.length; i++) {
out.print(arr[i] + " ");
}
out.println();
}
public static void p(int[] arr) {
for (int i = 0; i < arr.length; i++) {
out.print(arr[i] + " ");
}
out.println();
}
public static void sortpair(ArrayList<pair> arr) {
//ascending just change return 1 to return -1 and vice versa to get descending.
//compare based on value of pair.a
arr.sort(new Comparator<pair>() {
public int compare(pair o1, pair o2) {
long val = o1.a - o2.a;
if (val == 0)
return 0;
else if (val > 0)
return 1;
else
return -1;
}
});
}
// Take of the small test cases such as when n=1,2 etc.
// remember in case of fenwick tree ft is 1 based but our array should be 0 based.
// in fenwick tree when we update some index it doesn't change the value to val but it
// adds the val value in it so remember to add val-a[i] instead of just adding val.
//in case of finding the inverse mod do it (biexpo(a,mod-2)%mod + mod )%mod
public static ArrayList<ArrayList<pair>> adj;
public static int[] ans;
public static void main(String[] args) {
int len = i();
while (len-- != 0) {
int n = i();
adj=new ArrayList<>(n+1);
ans=new int[n];
int ok=0;
for(int i=0;i<=n;i++)adj.add(new ArrayList<>());
for(int i=0;i<n-1;i++)
{
int a=obj.nextInt();
int b=obj.nextInt();
adj.get(a).add(new pair(b,i));
adj.get(b).add(new pair(a,i));
if(adj.get(a).size()>2)ok=1;
if(adj.get(b).size()>2)ok=1;
}
if(ok==1)out.println(-1);
else
{
int[] vis=new int[n+1];
if(adj.get(1).size()==2)
{
vis[adj.get(1).get(1).a]=1;
dfs(1,vis,11);
vis[adj.get(1).get(1).a]=0;
vis[1]=0;
dfs(1,vis,2);
}
else
{
dfs(1,vis,11);
}
for(int i=0;i<n-1;i++)out.print(ans[i]+" ");
out.println();
}
}
out.flush();
}
public static void dfs(int cur,int[] vis,int c)
{
vis[cur]=1;
for(pair nd:adj.get(cur))
{
if(vis[nd.a]==1)continue;
if(c==2)ans[nd.b]=11;
else ans[nd.b]=2;
dfs(nd.a,vis,ans[nd.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 11
|
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
|
51087effcca5e941e19524b14e12473c
|
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 {
public static void main(String[] args) {
FastIO fio = new FastIO();
int t = fio.nextInt();
for (int i = 0; i < t; i++) {
int n = fio.nextInt();
ArrayList<ArrayList<Tuple>> adjList = new ArrayList<>();
for (int j = 0; j < n; j++) {
adjList.add(new ArrayList<>());
}
for (int j = 0; j < n - 1; j++) {
int u = fio.nextInt() - 1;
int v = fio.nextInt() - 1;
adjList.get(u).add(new Tuple(v, j));
adjList.get(v).add(new Tuple(u, j));
}
boolean possible = true;
for (ArrayList<Tuple> neighbours : adjList) {
if (neighbours.size() > 2) {
possible = false;
break;
}
}
if (!possible) {
fio.println(-1);
continue;
}
int[] assignments = new int[n - 1];
boolean[] visited = new boolean[n];
visited[0] = true;
Queue<Integer> queue = new LinkedList<>();
queue.offer(0);
while (!queue.isEmpty()) {
int u = queue.poll();
List<Tuple> neighbors = adjList.get(u);
for (int j = 0; j < neighbors.size(); j++) {
Tuple tt = neighbors.get(j);
int pi = j;
if (neighbors.size() == 2 && visited[neighbors.get(1 - j).v]) {
pi = 1 - assignments[neighbors.get(1 - j).num];
}
if (!visited[tt.v]) {
assignments[tt.num] = pi;
visited[tt.v] = true;
queue.offer(tt.v);
}
}
}
for (int j = 0; j < n - 1; j++) {
if (j > 0) {
fio.print(" ");
}
fio.print(assignments[j] == 0 ? 2 : 3);
}
fio.println();
}
fio.close();
}
}
class Tuple {
int v, num;
Tuple(int v, int num) {
this.v = v;
this.num = num;
}
}
class State {
int u;
int i;
State(int u, int i) {
this.u = u;
this.i = i;
}
}
/**
* Fast I/O
* @source https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
*/
class FastIO extends PrintWriter
{
BufferedReader br;
StringTokenizer st;
public FastIO()
{
super(new BufferedOutputStream(System.out));
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 11
|
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
|
6b6a3c2b97acc13ce3dee09413a51348
|
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 class Scanner {
Scanner(InputStream in) { this.in = in; } InputStream in;
byte[] bb = new byte[1 << 15]; int i, n;
byte getc() {
if (i == n) {
i = n = 0;
try { n = in.read(bb); } catch (IOException e) {}
}
return i < n ? bb[i++] : 0;
}
int nextInt() {
byte c = 0; while (c <= ' ') c = getc();
int a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); }
return a;
}
}
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
//BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int T = in.nextInt();
int[] U = new int[100100];
int[] V = new int[100100];
int[] deg = new int[100100];
int[] color = new int[100100];
List<Integer>[] edges = new ArrayList[100100];
for (int ts=1; ts<=T; ts++) {
int N = in.nextInt();
for (int i=1; i<N; i++) {
U[i] = in.nextInt();
V[i] = in.nextInt();
if (edges[U[i]] == null) {
edges[U[i]] = new ArrayList<>();
}
edges[U[i]].add(i);
if (edges[V[i]] == null) {
edges[V[i]] = new ArrayList<>();
}
edges[V[i]].add(i);
}
boolean possible = true;
for (int i=1; i<N; i++) {
deg[U[i]]++;
deg[V[i]]++;
if (deg[U[i]] > 2 || deg[V[i]] > 2)
possible = false;
}
int start = -1;
for (int i=1; i<=N; i++) {
if (deg[i] == 1)
start = i;
}
if (possible) {
int prev = 0;
color[prev] = 3;
//out.write("START\n");
//out.write(start + "\n");
for (int i=1; i<N; i++) {
//out.write(start + "\n");
for (Integer edge_id : edges[start]) {
//out.write("hfs " + start + " " + edge_id + " " + prev + "\n");
if (edge_id != prev) {
//out.write("hfs " + start + " " + edge_id + " " + prev + "\n");
//out.write("edge_id: " + edge_id + "\n");
color[edge_id] = 5 - color[prev];
prev = edge_id;
start = (U[edge_id] == start) ? V[edge_id] : U[edge_id];
//out.write("HERE\n");
break;
}
}
}
//out.write("END\n");
out.write(color[1] + "");
for (int i=2; i<N; i++)
out.write(" " + color[i]);
out.write("\n");
} else {
out.write("-1\n");
}
for (int i=1; i<=N; i++) {
edges[i].clear();
deg[i] = 0;
}
//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 11
|
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
|
a820bc799ce9d7e145d2c197f4743f3b
|
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 boolean[] ret;
static boolean[] updated;
static ArrayList<Integer>[] adjacencyList;
static Edge[] edgeList;
static class Edge {
int start, end, number;
public Edge (int _start, int _end, int _number) {
start = _start;
end = _end;
number = _number;
}
}
public static void dfs(int node) {
updated[node] = true;
for (int next : adjacencyList[edgeList[node].start]) {
if (!updated[next]) {
ret[next] = !ret[node];
dfs(next);
}
}
for (int next : adjacencyList[edgeList[node].end]) {
if (!updated[next]) {
ret[next] = !ret[node];
dfs(next);
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int numCases = Integer.parseInt(br.readLine());
for (int i = 0; i < numCases; i++) {
int numVertices = Integer.parseInt(br.readLine());
int[] numEdges = new int[numVertices];
edgeList = new Edge[numVertices - 1];
adjacencyList = new ArrayList[numVertices];
for (int j = 0; j < numVertices; j++) {
adjacencyList[j] = new ArrayList<>();
}
for (int j = 0; j < numVertices - 1; j++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken()) - 1;
int b = Integer.parseInt(st.nextToken()) - 1;
edgeList[j] = new Edge(a, b, j);
numEdges[a]++;
numEdges[b]++;
adjacencyList[a].add(j);
adjacencyList[b].add(j);
}
boolean good = true;
for (int j = 0; j < numVertices; j++) {
if (numEdges[j] > 2) {
good = false;
break;
}
}
if (!good) {
pw.println(-1);
} else {
ret = new boolean[numVertices - 1];
updated = new boolean[numVertices - 1];
dfs(0);
for (boolean b : ret) {
if (b)
pw.print(5 + " ");
else
pw.print(2 + " ");
}
pw.println();
}
}
br.close();
pw.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 11
|
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
|
db5f035f0cf282d9093a778caa91c48c
|
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 {
static FastScanner sc = new FastScanner();
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static class pair{
public pair(int x, int y) {
this.x = x;
this.y = y;
}
int x;
int y;
@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);
}
}
static void solve(){
int n = sc.nextInt();
int[]degree = new int[n];
List<Integer>[]grid = new List[n];
for (int i = 0; i < n; i++) {
grid[i] = new ArrayList();
}
List<pair>list = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
grid[x].add(y);
grid[y].add(x);
degree[x]++;
degree[y]++;
list.add(new pair(Math.min(x,y),Math.max(x,y)));
}
int begin = 0;
for(int i = 0;i < degree.length;i++){
if(degree[i] > 2){
System.out.println(-1);
return;
}
if(degree[i] == 1){
begin = i;
}
}
boolean[]used = new boolean[n];
int[]p = new int[]{5,2,11,2};
int idx = 0;
HashMap<pair,Integer>map = new HashMap<>();
while (!used[begin]){
used[begin] = true;
for(int next : grid[begin]){
if(used[next])
continue;
map.put(new pair(Math.min(begin,next),Math.max(begin,next)),p[idx % 4]);
idx++;
begin = next;
}
}
StringBuilder bd = new StringBuilder();
for(pair pp : list){
bd.append(map.get(pp) + " ");
}
System.out.println(bd.toString().trim());
}
public static void main(String[] args) {
int n = sc.nextInt();
for(int i = 0;i < n;i++){
solve();
}
}
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 11
|
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
|
9670a2721be3e7923f620ace372ae4ee
|
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 11
|
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
|
8af079a57d996397d433ce5b019c72a3
|
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 NotAssigning {
static BufferedInputStream bis;
public static int readInt() throws IOException {
int num = 0;
int b = bis.read();
while ((b < '0' || '9' < b) && b != '-') b = bis.read();
boolean neg = (b == '-');
if (neg) b = bis.read();
while (b >= '0') {
num = num*10 + b - '0';
b = bis.read();
}
return neg?-num:num;
}
public static void main(String[] args) throws IOException {
bis = new BufferedInputStream(System.in);
StringBuilder sb = new StringBuilder();
int T = readInt();
for(int cN=0; cN<T; cN++) {
int N = readInt();
int M = N-1;
int [][] edges = new int [M][2];
int [] deg = new int [N];
int x, y;
boolean good = true;
int [][] adj = new int [N][3];
int [][] adjE = new int [N][3];
for(int i=0; i<M; i++) {
x = readInt()-1;
y = readInt()-1;
edges[i][0] = x;
edges[i][1] = y;
adj[x][deg[x]] = y;
adj[y][deg[y]] = x;
adjE[x][deg[x]] = i;
adjE[y][deg[y]] = i;
deg[x]++;
deg[y]++;
if(!(deg[x] <= 2 && deg[y] <= 2)) {
good = false;
deg[x] = 0;
deg[y] = 0;
//break;
}
}
if(good) {
int [] primes = new int [] {2, 3};
int [] parity = new int [M];
for(int i=0; i<M; i++) parity[i] = -1;
int front = 0, back = 0;
int [] queue = new int [N];
int root = -1;
int tail = -1;
for(int i=0; i<N; i++) {
if(deg[i] == 1) {
if(root < 0) root = i;
else tail = i;
}
}
int p = 0;
parity[adjE[root][0]] = p;
queue[0] = adj[root][0];
p ^= 1;
while(front <= back) {
x = queue[front++];
if(x == tail) break; // all assigned
if(parity[adjE[x][0]] < 0) {
parity[adjE[x][0]] = p;
p ^= 1;
queue[++back] = adj[x][0];
}
else { // search second edge
parity[adjE[x][1]] = p;
p ^= 1;
queue[++back] = adj[x][1];
}
}
sb.append(primes[parity[0]]);
for(int i=1; i<M; i++) {
sb.append(' ').append(primes[parity[i]]);
}
sb.append('\n');
}
else {
sb.append("-1\n");
}
}
System.out.print(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 11
|
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
|
e05f88d074b0c0d6d5fe7da0bff196a3
|
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 {
public static void main(String[] args) {
var io = new Kattio(System.in, System.out);
int t = io.nextInt();
for (int i = 0; i < t; i++) {
solve(io);
}
io.close();
}
public static void solve(Kattio io) {
int n = io.nextInt();
var 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 = io.nextInt();
int v = io.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) {
io.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) {
var edges = graph.get(curNode);
var 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++) {
io.print(weight[i]);
io.print(" ");
}
io.println();
}
static class Edge {
public int node;
public int index;
Edge(int node, int index) {
this.node = node;
this.index = index;
}
}
}
// modified from https://github.com/Kattis/kattio/blob/master/Kattio.java
class Kattio extends PrintWriter {
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public String next() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) { }
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
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 11
|
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
|
7422db2b7fb0ecc2cb2479fbe9331953
|
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 TimePass {
public static int[] solve(int n,ArrayList<int[]>graph[]) {
for(int i=0;i<n;i++) {
if(graph[i].size()>2) return new int[] {-1};
}
int ans[]=new int[n-1];
dfs(0,0,graph,ans,true);
return ans;
}
public static void dfs(int v,int p,ArrayList<int[]>graph[],int ans[],boolean prevEven) {
int W=prevEven?3:2;
for(int next[]:graph[v]) {
int u=next[0];
if(p==u) continue;
int index=next[1];
ans[index]=W;
dfs(u,v,graph,ans,!prevEven);
W=prevEven?2:3;
prevEven=!prevEven;
}
}
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
int testCases=Integer.parseInt(br.readLine());
while(testCases-->0){
int n=Integer.parseInt(br.readLine());
ArrayList<int[]>graph[]=new ArrayList[n];
for(int i=0;i<n;i++) graph[i]=new ArrayList<>();
for(int i=0;i<n-1;i++) {
String input[]=br.readLine().split(" ");
int u=Integer.parseInt(input[0])-1;
int v=Integer.parseInt(input[1])-1;
graph[u].add(new int[] {v,i});
graph[v].add(new int[] {u,i});
}
int ans[]=solve(n,graph);
for(int a:ans) out.print(a+" ");
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 11
|
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
|
f97fa4bec29075468e9fd7e95b97d2f2
|
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.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.cert.X509CRL;
import java.util.*;
import java.lang.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
@SuppressWarnings("unused")
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static String OUTPUT = "";
//global
//private final static long BASE = 998244353L;
private final static int ALPHABET = (int)('z') - (int)('a') + 1;
private final static long BASE = 1000000007l;
private final static int INF_I = (1<<31)-1;
private final static long INF_L = (1l<<63)-1;
private final static int MAXN = 200100;
private final static int MAXK = 31;
private final static int[] DX = {-1,0,1,0};
private final static int[] DY = {0,1,0,-1};
private static List<List<List<Integer>>> G;
private static int[] ans;
private static void dfs(int u, int pa, int side) {
for (List<Integer> ne: G.get(u)) {
int v = ne.get(0);
int id = ne.get(1);
if (v==pa) continue;
int tmp = 2;
if (side == 1) tmp = 3;
ans[id] = tmp;
dfs(v, u, 1-side);
side = 1-side;
}
}
static void solve() {
//int ntest = 1;
int ntest = readInt();
for (int test=0;test<ntest;test++) {
int N = readInt();
int[] deg = new int[N];
G = new ArrayList<>();
for (int i=0;i<N;i++) G.add(new ArrayList<>());
for (int i=0;i<N-1;i++) {
int u = readInt() - 1;
int v = readInt() - 1;
G.get(u).add(Arrays.asList(v,i));
G.get(v).add(Arrays.asList(u,i));
deg[u]++;
deg[v]++;
}
boolean isOk = true;
for (int i=0;i<N;i++) isOk &= (deg[i]<3);
if (!isOk) {
out.println(-1);
continue;
}
ans = new int[N-1];
dfs(0,-1, 0);
for (int i=0;i<N-1;i++) out.print(ans[i] + " ");
out.println();
}
}
public static void main(String[] args) throws Exception
{
long S = System.currentTimeMillis();
if (INPUT=="") {
is = System.in;
} else {
File file = new File(INPUT);
is = new FileInputStream(file);
}
if (OUTPUT == "") out = new PrintWriter(System.out);
else out = new PrintWriter(OUTPUT);
solve();
out.flush();
long G = System.currentTimeMillis();
}
private static class Point<T extends Number & Comparable<T>> implements Comparable<Point<T>> {
private T x;
private T y;
public Point(T x, T y) {
this.x = x;
this.y = y;
}
public T getX() {return x;}
public T getY() {return y;}
@Override
public int compareTo(Point<T> o) {
int cmp = x.compareTo(o.getX());
if (cmp==0) return y.compareTo(o.getY());
return cmp;
}
}
private static class ClassComparator<T extends Comparable<T>> implements Comparator<T> {
public ClassComparator() {}
@Override
public int compare(T a, T b) {
return a.compareTo(b);
}
}
private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> {
public ListComparator() {}
@Override
public int compare(List<T> o1, List<T> o2) {
for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) {
int c = o1.get(i).compareTo(o2.get(i));
if (c != 0) {
return c;
}
}
return Integer.compare(o1.size(), o2.size());
}
}
private static boolean eof()
{
if(lenbuf == -1)return true;
int lptr = ptrbuf;
while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
try {
is.mark(1000);
while(true){
int b = is.read();
if(b == -1){
is.reset();
return true;
}else if(!isSpaceChar(b)){
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inbuf = new byte[1024];
static int lenbuf = 0, ptrbuf = 0;
private static int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
// private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); }
private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private static double readDouble() { return Double.parseDouble(readString()); }
private static char readChar() { return (char)skip(); }
private static String readString()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private static char[] readChar(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private static char[][] readTable(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = readChar(m);
return map;
}
private static int[] readIntArray(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = readInt();
return a;
}
private static long[] readLongArray(int n) {
long[] a = new long[n];
for (int i=0;i<n;i++) a[i] = readLong();
return a;
}
private static int readInt()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static long readLong()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}
|
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 11
|
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
|
bfb9ce5de5e279019c618239523db3e3
|
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.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;
public class cses{
static int count = 0;
public static void main(String[] args) {
int t = io.nextInt();
StringBuilder ans = new StringBuilder();
while(t-->0){
int n = io.nextInt();
int[] e1 = new int[n-1];
int[] e2 = new int[n-1];
HashMap<Integer, Integer> hm = new HashMap<>();
ArrayList<ArrayList<Integer>> tree = new ArrayList<>();
for (int i = 0; i < n; i++) {
tree.add(new ArrayList<>());
}
boolean flag = false;
for (int i = 0; i < n-1; i++) {
e1[i] = io.nextInt()-1;
e2[i] = io.nextInt()-1;
tree.get(e1[i]).add(e2[i]);
tree.get(e2[i]).add(e1[i]);
if(tree.get(e1[i]).size() >= 3 || tree.get(e2[i]).size() >= 3){
flag = true;
}
}
if(flag){
ans.append("-1").append('\n');
continue;
}
int st = -1;
for (int i = 0; i < n; i++) {
if(tree.get(i).size() == 1){
st = i;
break;
}
}
boolean[] vis = new boolean[n];
dfs(st, tree, hm, vis);
for (int i = 0; i < n - 1; i++) {
int te[] = {e1[i], e2[i]};
if(hm.get(e2[i]) < hm.get(e1[i])){
te = new int[]{e2[i], e1[i]};
}
int append = hm.get(te[0]) % 2 == 0 ? 2 : 3;
ans.append(append).append(" ");
}
ans.deleteCharAt(ans.length() - 1);
ans.append("\n");
count = 0;
}
ans.deleteCharAt(ans.length() - 1);
System.out.print(ans);
}
public static void dfs(int n, ArrayList<ArrayList<Integer>> t, HashMap<Integer, Integer> hm, boolean[] visited){
if(visited[n])
return;
visited[n] = true;
hm.put(n, count);
count++;
for (int ele : t.get(n)) {
dfs(ele, t, hm, visited);
}
}
static Kattio29 io = new Kattio29();
static class Kattio29 extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio29() {
this(System.in, System.out);
}
public Kattio29(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio29(String problemName) throws IOException {
super(new FileWriter(problemName + ".out"));
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
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 11
|
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
|
a0daf38a4117e298dcbe78f2dc5d87c4
|
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.math.BigInteger;
import java.util.*;
import java.io.*;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
public class CodeForces {
public void run() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
next : while (t-- > 0) {
int n = Integer.parseInt(br.readLine());
ArrayList<Integer>[] table = (ArrayList<Integer>[]) new ArrayList[n + 1];
for (int i = 0; i < n + 1; i++) {
table[i] = new ArrayList<>();
}
int[][] edge = new int[n - 1][2];
for(int i = 0; i < n - 1; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
edge[i][0] = u;
edge[i][1] = v;
table[u].add(v);
table[v].add(u);
}
int start = 0;
int[] dist = new int[n + 1];
for (int i = 1; i <= n; i++) {
if (table[i].size() > 2) {
System.out.println(-1);
continue next;
}
if (table[i].size() == 1) {
start = i;
}
}
int now = start;
boolean[] searched = new boolean[n + 1];
int d = 0;
while (!searched[now]) {
dist[now] = d++;
searched[now] = true;
for (int i : table[now]) {
if (!searched[i]) {
now = i;
break;
}
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n - 1; i++) {
if (Math.max(dist[edge[i][0]], dist[edge[i][1]]) % 2 == 0) {
sb.append(2);
sb.append(" ");
} else {
sb.append(5);
sb.append(" ");
}
}
System.out.println(sb.toString().trim());
}
}
public static void main(String[] args) throws Exception {
new CodeForces().run();
}
}
|
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 11
|
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
|
0959354c7a2420c22c16ff75e4dbb003
|
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
|
// JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.stream.*;
import java.lang.*;
import java.math.BigInteger;
import java.rmi.ConnectIOException;
import java.text.DecimalFormat;
import java.io.*;
public class Eshan {
static private final String INPUT = "input.txt";
static private final String OUTPUT = "output.txt";
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter out = new PrintWriter(System.out);
static DecimalFormat df = new DecimalFormat("0.0000000");
final static int mod = (int) (1e9 + 7);
final static int MAX = Integer.MAX_VALUE;
final static int MIN = Integer.MIN_VALUE;
final static long INF = Long.MAX_VALUE;
final static long NEG_INF = Long.MIN_VALUE;
static Random rand = new Random();
// ======================= MAIN ==================================
public static void main(String[] args) throws IOException {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
// ==== start ====
input();
// int t = 1;
int t = readInt();
preprocess();
while (t-- > 0) {
solve();
}
out.flush();
// ==== end ====
if (!oj)
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
private static void solve() throws IOException {
int n = readInt();
List<Integer>[] graph = new ArrayList[n + 1];
for (int i = 1; i <= n; i++)
graph[i] = new ArrayList<>();
List<String> list = new ArrayList<>();
for (int i = 1; i < n; i++) {
int u = readInt(), v = readInt();
int min = Math.min(u, v), max = Math.max(u, v);
list.add(min + " " + max);
graph[u].add(v);
graph[v].add(u);
}
Map<String, Integer> map = new HashMap<>();
boolean[] visited = new boolean[n + 1];
visited[1] = true;
Queue<int[]> q = new ArrayDeque<>();
q.add(new int[] { 1, graph[1].get(0), 2 });
if (graph[1].size() == 2)
q.add(new int[] { 1, graph[1].get(1), 3 });
while (!q.isEmpty()) {
int size = q.size();
while (size-- > 0) {
int[] rem = q.remove();
if (visited[rem[1]])
continue;
visited[rem[1]] = true;
int min = Math.min(rem[0], rem[1]), max = Math.max(rem[0], rem[1]);
map.put(min + " " + max, rem[2]);
int count = 0;
for (int nbr : graph[rem[1]]) {
if (!visited[nbr]) {
q.add(new int[] { rem[1], nbr, rem[2] == 2 ? 3 : 2 });
count++;
}
}
if (count > 1) {
out.println(-1);
return;
}
}
}
List<Integer> ans = new ArrayList<>();
for (String s : list) {
if (map.containsKey(s))
ans.add(map.get(s));
else {
out.println(-1);
return;
}
}
printIList(ans);
}
private static void preprocess() {
}
// cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces
// javac Eshan.java
// java Eshan
// javac Eshan.java && java Eshan
// ==================== CUSTOM CLASSES ================================
static class Pair implements Comparable<Pair> {
int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(Pair o) {
if (this.first != o.first)
return this.second - o.second;
return this.first - o.first;
}
}
static class DequeNode {
DequeNode prev, next;
int val;
DequeNode(int val) {
this.val = val;
}
DequeNode(int val, DequeNode prev, DequeNode next) {
this.val = val;
this.prev = prev;
this.next = next;
}
}
// ======================= FOR INPUT ==================================
private static void input() {
FileInputStream instream = null;
PrintStream outstream = null;
try {
instream = new FileInputStream(INPUT);
outstream = new PrintStream(new FileOutputStream(OUTPUT));
System.setIn(instream);
System.setOut(outstream);
} catch (Exception e) {
System.err.println("Error Occurred.");
}
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(readLine());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readString() throws IOException {
return next();
}
static String readLine() throws IOException {
return br.readLine().trim();
}
static int[] readIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = readInt();
return arr;
}
static int[][] read2DIntArray(int n, int m) throws IOException {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
arr[i] = readIntArray(m);
return arr;
}
static List<Integer> readIntList(int n) throws IOException {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(readInt());
return list;
}
static long[] readLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = readLong();
return arr;
}
static long[][] read2DLongArray(int n, int m) throws IOException {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++)
arr[i] = readLongArray(m);
return arr;
}
static List<Long> readLongList(int n) throws IOException {
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(readLong());
return list;
}
static char[] readCharArray(int n) throws IOException {
return readString().toCharArray();
}
static char[][] readMatrix(int n, int m) throws IOException {
char[][] mat = new char[n][m];
for (int i = 0; i < n; i++)
mat[i] = readCharArray(m);
return mat;
}
// ========================= FOR OUTPUT ==================================
private static void printIList(List<Integer> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printLList(List<Long> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printIArray(int[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DIArray(int[][] arr) {
for (int i = 0; i < arr.length; i++)
printIArray(arr[i]);
}
private static void printLArray(long[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DLArray(long[][] arr) {
for (int i = 0; i < arr.length; i++)
printLArray(arr[i]);
}
// ====================== TO CHECK IF STRING IS NUMBER ========================
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static boolean isLong(String s) {
try {
Long.parseLong(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
// ==================== FASTER SORT ================================
private static void sort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void reverseSort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void sort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void reverseSort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
// ==================== MATHEMATICAL FUNCTIONS ===========================
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static long power(long a, long b) {
if (b == 0)
return 1L;
long ans = power(a, b >> 1);
ans *= ans;
if ((b & 1) == 1)
ans *= a;
return ans;
}
private static int mod_power(int a, int b, int mod) {
if (b == 0)
return 1;
int temp = mod_power(a, b >> 1, mod);
temp %= mod;
temp = (int) ((1L * temp * temp) % mod);
if ((b & 1) == 1)
temp = (int) ((1L * temp * a) % mod);
return temp;
}
private static int multiply(int a, int b) {
return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod);
}
private static boolean isPrime(long n) {
for (long i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
private static long nCr(long n, long r) {
if (n - r > r)
r = n - r;
long ans = 1L;
for (long i = r + 1; i <= n; i++)
ans *= i;
for (long i = 2; i <= n - r; i++)
ans /= i;
return ans;
}
// ==================== Primes using Seive =====================
private static List<Integer> getPrimes(int n) {
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, true);
for (int i = 2; i * i <= n; i++) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i)
prime[j] = false;
}
}
// return prime;
List<Integer> list = new ArrayList<>();
for (int i = 2; i <= n; i++)
if (prime[i])
list.add(i);
return list;
}
private static int[] SeivePrime(int n) {
int[] primes = new int[n];
for (int i = 0; i < n; i++)
primes[i] = i;
for (int i = 2; i * i < n; i++) {
if (primes[i] != i)
continue;
for (int j = i * i; j < n; j += i) {
if (primes[j] == j)
primes[j] = i;
}
}
return primes;
}
// ==================== STRING FUNCTIONS ================================
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
private static String sortString(String str) {
int[] arr = new int[256];
for (char ch : str.toCharArray())
arr[ch]++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 256; i++)
while (arr[i]-- > 0)
sb.append((char) i);
return sb.toString();
}
// ==================== LIS & LNDS ================================
private static int LIS(int arr[], int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find1(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find1(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) >= val) {
ret = mid;
j = mid - 1;
} else {
i = mid + 1;
}
}
return ret;
}
private static int LNDS(int[] arr, int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find2(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find2(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) <= val) {
i = mid + 1;
} else {
ret = mid;
j = mid - 1;
}
}
return ret;
}
// =============== Lower Bound & Upper Bound ===========
// less than or equal
private static int lower_bound(List<Integer> list, int val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(List<Long> list, long val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(int[] arr, int val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(long[] arr, long val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
// greater than or equal
private static int upper_bound(List<Integer> list, int val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(List<Long> list, long val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(int[] arr, int val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(long[] arr, long val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
// ==================== UNION FIND =====================
private static int find(int x, int[] parent) {
if (parent[x] == x)
return x;
return parent[x] = find(parent[x], parent);
}
private static boolean union(int x, int y, int[] parent, int[] rank) {
int lx = find(x, parent), ly = find(y, parent);
if (lx == ly)
return false;
if (rank[lx] > rank[ly])
parent[ly] = lx;
else if (rank[lx] < rank[ly])
parent[lx] = ly;
else {
parent[lx] = ly;
rank[ly]++;
}
return true;
}
// ==================== SEGMENT TREE (RANGE SUM) =====================
public static class SegmentTree {
int n;
int[] arr, tree, lazy;
SegmentTree(int arr[]) {
this.arr = arr;
this.n = arr.length;
this.tree = new int[(n << 2)];
this.lazy = new int[(n << 2)];
build(1, 0, n - 1);
}
void build(int id, int start, int end) {
if (start == end)
tree[id] = arr[start];
else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
build(left, start, mid);
build(right, mid + 1, end);
tree[id] = tree[left] + tree[right];
}
}
void update(int l, int r, int val) {
update(1, 0, n - 1, l, r, val);
}
void update(int id, int start, int end, int l, int r, int val) {
distribute(id, start, end);
if (end < l || r < start)
return;
if (start == end)
tree[id] += val;
else if (l <= start && end <= r) {
lazy[id] += val;
distribute(id, start, end);
} else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
update(left, start, mid, l, r, val);
update(right, mid + 1, end, l, r, val);
tree[id] = tree[left] + tree[right];
}
}
int query(int l, int r) {
return query(1, 0, n - 1, l, r);
}
int query(int id, int start, int end, int l, int r) {
if (end < l || r < start)
return 0;
distribute(id, start, end);
if (start == end)
return tree[id];
else if (l <= start && end <= r)
return tree[id];
else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r);
}
}
void distribute(int id, int start, int end) {
if (start == end)
tree[id] += lazy[id];
else {
tree[id] += lazy[id] * (end - start + 1);
lazy[(id << 1)] += lazy[id];
lazy[(id << 1) + 1] += lazy[id];
}
lazy[id] = 0;
}
}
// ==================== TRIE ================================
static class Trie {
class Node {
Node[] children;
boolean isEnd;
Node() {
children = new Node[26];
}
}
Node root;
Trie() {
root = new Node();
}
public void insert(String word) {
Node curr = root;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null)
curr.children[ch - 'a'] = new Node();
curr = curr.children[ch - 'a'];
}
curr.isEnd = true;
}
public boolean find(String word) {
Node curr = root;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null)
return false;
curr = curr.children[ch - 'a'];
}
return curr.isEnd;
}
}
// ==================== FENWICK TREE ================================
static class FT {
long[] tree;
int n;
FT(int[] arr, int n) {
this.n = n;
this.tree = new long[n + 1];
for (int i = 1; i <= n; i++) {
update(i, arr[i - 1]);
}
}
void update(int idx, int val) {
while (idx <= n) {
tree[idx] += val;
idx += idx & -idx;
}
}
long query(int l, int r) {
return getSum(r) - getSum(l - 1);
}
long getSum(int idx) {
long ans = 0L;
while (idx > 0) {
ans += tree[idx];
idx -= idx & -idx;
}
return ans;
}
}
// ==================== BINARY INDEX TREE ================================
static class BIT {
long[][] tree;
int n, m;
BIT(int[][] mat, int n, int m) {
this.n = n;
this.m = m;
tree = new long[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
update(i, j, mat[i - 1][j - 1]);
}
}
}
void update(int x, int y, int val) {
while (x <= n) {
int t = y;
while (t <= m) {
tree[x][t] += val;
t += t & -t;
}
x += x & -x;
}
}
long query(int x1, int y1, int x2, int y2) {
return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1);
}
long getSum(int x, int y) {
long ans = 0L;
while (x > 0) {
int t = y;
while (t > 0) {
ans += tree[x][t];
t -= t & -t;
}
x -= x & -x;
}
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 11
|
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
|
8b6c4825fbf58dfe5939fca28ccc04cf
|
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
|
// ceil using integer division: ceil(x/y) = (x+y-1)/y
import java.lang.reflect.Array;
import java.util.*;
import java.lang.*;
import java.io.*;
public class practice {
public static void main(String[] args) throws IOException {
Reader.init(System.in);
int t = Reader.nextInt();
while(t-->0){
int n = Reader.nextInt();
ArrayList<ArrayList<Pair>> graph = new ArrayList<>();
for(int i = 0;i<n+1;i++){
graph.add(new ArrayList<>());
}
for(int i = 0;i<n-1;i++){
int n1 = Reader.nextInt();
int n2 = Reader.nextInt();
graph.get(n1).add(new Pair(n1,n2,i+1));
graph.get(n2).add(new Pair(n2,n1,i+1));
}
if(n==2){
System.out.println(2);
continue;
}
boolean f1 = true;
for(int i = 0;i<=n;i++){
if(graph.get(i).size()>2){
System.out.println(-1);
f1 = false;
break;
}
}
if(!f1) continue;
boolean[] visited = new boolean[n+1];
int[] ans = new int[n+1];
Queue<Integer> q = new LinkedList<>();
for(int i = 1;i<=n;i++){
if(graph.get(i).size()==2){
visited[i] = true;
ans[graph.get(i).get(0).idx] = 2;
ans[graph.get(i).get(1).idx] = 5;
q.add(graph.get(i).get(0).nbr);
q.add(graph.get(i).get(1).nbr);
break;
}
}
while(q.size()>0){
int size = q.size();
for(int i = 0;i<size;i++){
int root = q.remove();
if(visited[root]) continue;
visited[root] = true;
if(graph.get(root).size()==0 || graph.get(root).size()==1) continue;
if(visited[graph.get(root).get(0).nbr]){
if(ans[graph.get(root).get(0).idx]==2){
ans[graph.get(root).get(1).idx] = 5;
}
else{
ans[graph.get(root).get(1).idx] = 2;
}
q.add(graph.get(root).get(1).nbr);
}
else{
if(ans[graph.get(root).get(1).idx]==2){
ans[graph.get(root).get(0).idx] = 5;
}
else{
ans[graph.get(root).get(0).idx] = 2;
}
q.add(graph.get(root).get(0).nbr);
}
}
}
for(int i = 1;i<n;i++){
System.out.print(ans[i]+" ");
}
System.out.println();
}
}
}
class Pair{
int src, nbr, idx;
public Pair(int src, int nbr, int idx){
this.src = src;
this.nbr = nbr;
this.idx = idx;
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static String nextLine() throws IOException {
return reader.readLine();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException{
return Long.parseLong(next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
|
Java
|
["3\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 11
|
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
|
7379dd4fb2343be934e0804c6be74b4d
|
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.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
public class Graph {
public static int fin=0;
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static class Edge {
int start;
int end;
int len;
public Edge(int source, int destination, int weight) {
this.start = source;
this.end = destination;
this.len = weight;
}
}
static class UGraphMap
{
// static ArrayList<ArrayList<Edge> > adj ;
static HashMap<Integer,ArrayList<Edge>> map;
UGraphMap()
{
map=new HashMap<Integer,ArrayList<Edge>>();
}
static void addEdge(int u, int v,int len)
{
Edge e1 = new Edge(u, v, len);
Edge e2 = new Edge(v, u, len);
if(map.containsKey(u))
{
map.get(u).add(e1);
}
else
{
map.put(u, new ArrayList<Edge>());
map.get(u).add(e1);
}
if(map.containsKey(v))
{
map.get(v).add(e2);
}
else
{
map.put(v, new ArrayList<Edge>());
map.get(v).add(e2);
}
}
static int bfs1(int V,int s,int[] arr,int[] visited) {
int min=1;
if(map.containsKey(s))
{
arr[s]=s+1;
// Integer[] visited=new Integer[V];
// int[] dis=new int[V];
// Arrays.fill(dis, Integer.MAX_VALUE);
// ArrayList<Integer> li=new ArrayList<Integer>();
Queue<Integer> q= new LinkedList<>();
q.add(s);
// li.add(s);
visited[s]=1;
// dis[s]=0;
while(!q.isEmpty())
{
int vertex=q.remove();
for(int i=0;i<map.get(vertex).size();i++)
{
if(visited[map.get(vertex).get(i).end]==0)
{
// dis[adj.get(vertex).get(i).end]=Math.min(dis[adj.get(vertex).get(i).start]+1,dis[adj.get(vertex).get(i).end]);
q.add(map.get(vertex).get(i).end);
// li.add(adj.get(vertex).get(i).end);
visited[map.get(vertex).get(i).end]=1;
arr[map.get(vertex).get(i).end]=s+1;
min++;
}
}
}
// System.out.println(Arrays.toString(dis));
return min;
}
else {arr[s]=s+1;return 1;}
}
}
static class UGraph
{
int V;
static ArrayList<ArrayList<Edge> > adj ;
UGraph(int V)
{
this.V=V;
adj = new ArrayList<ArrayList<Edge> >(V);
for (int i = 0; i < V; i++)
adj.add(new ArrayList<Edge>());
}
static void addEdge(int u, int v,int len)
{
Edge e1 = new Edge(u, v, len);
Edge e2 = new Edge(v, u, len);
adj.get(u).add(e1);
adj.get(v).add(e2);
}
static void printGraph(ArrayList<ArrayList<Edge> > adj)
{
for (int i = 0; i < adj.size(); i++) {
System.out.println("\nAdjacency list of vertex" + i);
System.out.print("head");
for (int j = 0; j < adj.get(i).size(); j++) {
System.out.print(" -> "+adj.get(i).get(j).end);
}
System.out.println();
}
}
}
static class DGraph
{
int V;
static ArrayList<ArrayList<Edge> > adj ;
DGraph(int V)
{
this.V=V;
adj = new ArrayList<ArrayList<Edge> >(V);
for (int i = 0; i < V; i++)
adj.add(new ArrayList<Edge>());
}
static void addEdge(int u, int v,int len)
{
Edge e1 = new Edge(u, v, len);
adj.get(u).add(e1);
}
static void printGraph(ArrayList<ArrayList<Edge> > adj)
{
for (int i = 0; i < adj.size(); i++) {
System.out.println("\nAdjacency list of vertex" + i);
System.out.print("head");
for (int j = 0; j < adj.get(i).size(); j++) {
System.out.print(" -> "+adj.get(i).get(j).end);
}
System.out.println();
}
}
}
public static boolean bip=true;
public static int col1=0;
public static int col2=0;
// public static ArrayList<Integer> dfs(int V, ArrayList<ArrayList<Integer>> adj,int s,int[] col) {
// ArrayList<Integer> list=new ArrayList<Integer>();
// dfsW(adj,s,list,1,col);
// return list;
//
// }
public static HashMap<String,Integer> map =new HashMap<String,Integer>();
public static void dfs(ArrayList<ArrayList<Integer>> adj,int s,int color,int[] col)
{
col[s]=color;
if(adj.get(s).size()>2)
{
bip=false;
}
for(int i=0;i<adj.get(s).size();i++)
{
if(col[adj.get(s).get(i)]==0) {map.put(s+" "+adj.get(s).get(i), color);dfs(adj,adj.get(s).get(i),color==2?3:2,col);color=color==2?3:2;}
}
}
public static ArrayList<Integer> bfs(int V, ArrayList<ArrayList<Edge>> adj,int s) {
Integer[] visited=new Integer[V];
// int[] dis=new int[V];
// Arrays.fill(dis, Integer.MAX_VALUE);
ArrayList<Integer> li=new ArrayList<Integer>();
Queue<Integer> q= new LinkedList<>();
q.add(s);
li.add(s);
visited[s]=1;
// dis[s]=0;
while(!q.isEmpty())
{
int vertex=q.remove();
for(int i=0;i<adj.get(vertex).size();i++)
{
if(visited[adj.get(vertex).get(i).end]==null)
{
// dis[adj.get(vertex).get(i).end]=Math.min(dis[adj.get(vertex).get(i).start]+1,dis[adj.get(vertex).get(i).end]);
q.add(adj.get(vertex).get(i).end);
li.add(adj.get(vertex).get(i).end);
visited[adj.get(vertex).get(i).end]=1;
}
}
}
// System.out.println(Arrays.toString(dis));
return li;
}
public static boolean printGraph1(ArrayList<ArrayList<Edge>> adj)
{
for (int i = 0; i < adj.size(); i++) {
// System.out.println("\nAdjacency list of vertex"
// + i);
// System.out.print("head");
if(adj.get(i).size()>2)return true;
System.out.println();
}
return false;
}
public static long pwmd(long a, long n,long mod) {
if (n == 0)
return 1;
long pt = pwmd(a, n / 2,mod);
pt *= pt;
pt %= mod;
if ((n & 1) > 0) {
pt *= a;
pt %= mod;
}
return pt;
}
public static void main(String[] args) throws IOException
{
// Create a graph given in the above diagram
Reader reader = new Reader();
//Scanner reader=new Scanner(System.in);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList<ArrayList<Integer>> g=new ArrayList<ArrayList<Integer>>();
//int cases=Integer.parseInt(br.readLine());
// int cases=1;
int cases=reader.nextInt();
while (cases-->0){
int N=reader.nextInt();
// System.out.println(bip);
// int M=reader.nextInt();
// int K=reader.nextInt();
// int S=reader.nextInt();
//int circum=reader.nextInt();
//int K=reader.nextInt();
//int N=Integer.parseInt(br.readLine());
//String[] first=br.readLine().split(" ");
//int N=Integer.parseInt(first[0]);
// int M=Integer.parseInt(first[1]);
//int X=reader.nextInt();
//int Y=reader.nextInt();
//String str=br.readLine();
//int max=Integer.MIN_VALUE;
//int min=Integer.MAX_VALUE;
//HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
// ArrayList<Integer> li=new ArrayList<Integer>();
// HashSet<Integer> map=new HashSet<Integer>();
// int[][] arr=new int[N-1][3];
// HashMap<Integer,ArrayList<Integer>> g=new HashMap<Integer,ArrayList<Integer>>();
// int[] arr=new int[N];
int [][] arr2=new int[N][2];
int[] vis=new int[N];
//long[]arr=new long[N];
//arrInpInt(arr,N);
//arrInpLong(arr,N);
//int[] arr1=decSort(arr);
//printArr(arr1);
bip=true;
for(int i=0;i<N;i++)
{
g.add(new ArrayList<Integer>());
}
for(int i=0;i<N-1;i++)
{
int k=reader.nextInt()-1;
int p=reader.nextInt()-1;
arr2[i][0]=k;arr2[i][1]=p;
g.get(k).add(p);
g.get(p).add(k);
}
// System.out.println(g);
int k=0;
for(int i=0;i<N;i++)
{
if(vis[i]==0)
{
dfs(g,i,2,vis);
if(!bip)break;
}
}
// System.out.println(k);
if(!bip)System.out.println(-1);
else
{
for(int i=0;i<N;i++)
{
// System.out.println(map);
if(map.containsKey(arr2[i][0]+" "+arr2[i][1]))
{
System.out.print(map.get(arr2[i][0]+" "+arr2[i][1])+" ");
}
else if(map.containsKey(arr2[i][1]+" "+arr2[i][0]))
{
System.out.print(map.get(arr2[i][1]+" "+arr2[i][0])+" ");
}
}
}
map.clear();
g.clear();
System.out.println();
}
// output.flush();
//System.out.println(1<<p);
}
}
|
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 11
|
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
|
af4c32fef4bb4129c2d573f1a23ae43c
|
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
|
/*
_oo0oo_
o8888888o
88" . "88
(| -_- |)
0\ = /0
___/`---'\___
.' \\| |// '.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' |_/ |
\ .-\__ '-' ___/-. /
___'. .' /--.--\ `. .'___
."" '< `.___\_<|>_/___.' >' "".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `_. \_ __\ /__ _/ .-` / /
=====`-.____`.___ \_____/___.-`___.-'=====
`=---='
*/
import java.util.*;
import java.math.*;
import java.io.*;
import java.lang.Math.*;
public class KickStart2020 {
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());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
public static class Pair implements Comparable<Pair> {
public int index;
public int value;
public Pair(int index, int value) {
this.index = index;
this.value = value;
}
@Override
public int compareTo(Pair other) {
// multiplied to -1 as the author need descending sort order
if(other.index < this.index) return -1;
if(other.index > this.index) return 1;
if(other.value < this.value) return -1;
if(other.value > this.value) return 1;
return 0;
}
@Override
public String toString() {
return this.index + " " + value;
}
}
static boolean isPrime(long d) {
if (d == 1)
return false;
for (int i = 2; i <= (long) Math.sqrt(d); i++) {
if (d % i == 0)
return false;
}
return true;
}
static String decimalTob(int n, int k , String s) {
int x = n % k;
int y = n / k;
s += x;
if(y > 0) {
s = decimalTob(y, k, s);
}
return s;
}
static long powermod(long x, long y, long mod) {
long ans = 1;
x = x % mod;
if (x == 0)
return 0;
int i = 1;
while (y > 0) {
if ((y & 1) != 0)
ans = (ans * x) % mod;
y = y >> 1;
x = (x * x) % mod;
}
return ans;
}
static long power(long x, long y)
{
long res = 1;
while (y > 0)
{
if ((y & 1) != 0)
res = res * x;
y = y >> 1;
x = x * x;
}
return res;
}
static void dfs(int n, boolean hachu[], ArrayList<ArrayList<Integer>> ss, int parent, TreeMap<String, Integer> ssd) {
hachu[n] = true;
for(int e: ss.get(n)) {
if(!hachu[e]) {
ssd.put(e + " " + n, parent);
ssd.put(n + " " + e, parent);
parent = (parent == 2)? 3: 2;
dfs(e, hachu, ss, parent, ssd);
}
}
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = sc.nextInt();
outerloop:
while(t-- > 0) {
int n = sc.nextInt();
String arr[] = new String[n - 1];
ArrayList<ArrayList<Integer>> ss = new ArrayList<>();
for(int i = 0; i <= n; i++) ss.add(new ArrayList<>());
for(int i = 0; i < n - 1; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
ss.get(u).add(v);
ss.get(v).add(u);
arr[i] = u + " " + v;
}
for(ArrayList<Integer> e: ss) {
if(e.size() > 2) {out.println(-1);
continue outerloop;
}
}
boolean hachu[] = new boolean[n + 1];
TreeMap<String, Integer> ssd = new TreeMap<>();
dfs(1, hachu, ss, 2, ssd);
for(String s: arr) {
out.print(ssd.get(s) + " ");
}
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 11
|
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
|
fd50e3dafef9c74ff0d42c54791e62b4
|
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 Not_assigning
{
static ArrayList<Integer> ans = new ArrayList<>();
public static void AssignNode(HashMap<Integer, ArrayList<Node>> hm, int vertice1, int vertice2, int edge)
{
if(!hm.containsKey(vertice1))
{
hm.put(vertice1, new ArrayList<Node>());
}
hm.get(vertice1).add(new Node(edge, vertice2));
}
public static void main(String args[])
{
HashMap<Integer, ArrayList<Node>> hm = new HashMap<>();
ArrayList<Integer> deg1 = new ArrayList<Integer>();
ArrayList<Integer> ans = new ArrayList<Integer>();
int num,n,u,v,curr,end,prime,p,prev;
boolean possible;
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out), true);
num = sc.nextInt();
for(int i=0;i<num;i++)
{
possible = true;
n = sc.nextInt();
for(int j=0;j<n-1;j++)
{
u = sc.nextInt(); v = sc.nextInt();
if(possible)
{
ans.add(0); // allocate space for answers
AssignNode(hm, u, v, j);
AssignNode(hm, v, u, j);
if(hm.get(u).size() >= 3 || hm.get(v).size() >= 3) possible = false;
}
}
if(!possible) out.println("-1");
else
{
ArrayList<Node> node;
for(Map.Entry element: hm.entrySet())
{
node = (ArrayList<Node>)element.getValue();
if(node.size() == 1) deg1.add((Integer)element.getKey());
}
node = hm.get(deg1.get(0));
curr = node.get(0).vertice;
prev = deg1.get(0);
end = deg1.get(1);
ans.set(node.get(0).edge, 2);
prime = 2; // starting with 2;
while(curr != end)
{
node = hm.get(curr); // get list of nodes connected to curr
p = 0;
while(node.get(p).vertice == prev) p++; // find the right node
ans.set(node.get(p).edge, (2^3)^prime);
prev = curr;
curr = node.get(p).vertice;
prime = (2^3)^prime;
}
for(int j=0;j<n - 1;j++)
{
out.print(ans.get(j) + " ");
out.flush();
}
out.println();
}
hm.clear(); deg1.clear(); ans.clear();
}
}
}
class Node
{
int edge;
int vertice;
Node(int edge, int vertice)
{
this.edge = edge;
this.vertice = vertice;
}
}
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 11
|
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
|
1a4500c58b27e4bbdc23c8417f952683
|
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 static java.lang.System.out;
import java.io.*;
import java.util.*;
// import org.apache.commons.lang3.ArrayUtils;
public class C_Not_Assigning {
static int mod=(int)1e9+7;
static Map<Pair,Integer> mp=new HashMap<>();
static ArrayList<id> grp[]=new ArrayList[200001];
static void dfs(int u,int p,int val)
{
if(val==2) val++;
else val--;
for(id x:grp[u]){
if(x.x!=p){
mp.putIfAbsent(x.p, val);
// mp.putIfAbsent(new Pair(u,x), val);
dfs(x.x,u,val);
if(val==2) val++;
else val--;
}
}
}
public static void main(String[] args) {
int testCase = 1;
FastScanner fs = new FastScanner();
PrintWriter out=new PrintWriter(System.out);
testCase=fs.nextInt();
// int k=1;
for (int TT = 0; TT < testCase; TT++) {
int n=fs.nextInt();
for(int i=1;i<=n;i++) grp[i]=new ArrayList<>();
mp.clear();
int deg[]=new int[n+1];
ArrayList<Pair> edges=new ArrayList<>();
boolean pos=true;
// grp[0].add(1);
for(int i=0;i<n-1;i++){
int u=fs.nextInt(),v=fs.nextInt();
Pair p=new Pair(u,v);
edges.add(p);
grp[u].add(new id(v,p));
grp[v].add(new id(u,p));
deg[u]++;
deg[v]++;
if(deg[u]>2 || deg[v]>2){
pos=false;
}
}
if(pos){
dfs(1,0,3);
// out.println(mp);
for(Pair p:edges){
out.print(mp.get(p)+" ");
// if(k==2) k++;
// else k--;
}
}
else out.print(-1);
out.println();
// out.println("Case #" + k + ": ");
// k++;
}
out.close();
}
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
static int power(int x, int y, int p)
{
int res = 1;
x = x % p;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % p;
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
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 printArr(int[] arr) {
for (int x : arr)
System.out.print(x + " ");
System.out.println();
}
static int mod_mul(int a, int b){ a = a % mod; b = b % mod; return (((a * b) % mod) + mod) % mod;}
static int mod_add(int a, int b){ a = a % mod; b = b % mod; return (((a + b) % mod) + mod) % mod;}
static int mod_sub(int a, int b){ a = a % mod; b = b % mod; return (((a - b) % mod) + mod) % mod;}
}
class id{
int x;
Pair p;
id(int x,Pair p){
this.p=p;
this.x=x;
}
}
class Pair {
int a,b;
Pair(int a,int b) {
this.a=a;
this.b=b;
}
}
class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
private char NC = (char) 0;
private char c = NC;
private double cnt = 1;
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());
}
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;
}
}
|
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 11
|
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
|
5fc3d0c96ce1efa73c0edcb589ab7c95
|
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 {
static String votes;
static int[] arr;
public static void main(String[] args) {
MyScanner s = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int testcases=s.nextInt();
while(testcases-->0) {
int n=s.nextInt();
// int[][] edges=new int[n-1][2];
ArrayList<int[]>[] list=new ArrayList[n+1];
for(int i=0;i<n-1;i++) {
int n1=s.nextInt();
int n2=s.nextInt();
if(list[n1]==null)list[n1]=new ArrayList<>();
if(list[n2]==null)list[n2]=new ArrayList<>();
// edges[i][0]=n1;
// edges[i][1]=n2;
list[n1].add(new int[] {n2,i});
list[n2].add(new int[] {n1,i});
}
boolean flag=false;
int mindeg=0;
for(int i=1;i<=n;i++) {
if(list[i].size()>2) {
flag=true;
break;
}
if(list[i].size()==1) {
mindeg=i;
}
}
if(flag) {
out.println(-1);
continue;
}
int[] ans=new int[n-1];
int prev=2;
int previn=mindeg;
ans[list[mindeg].get(0)[1]]=2;
mindeg=list[mindeg].get(0)[0];
while(list[mindeg].size()!=1) {
int fren,ind;
if(list[mindeg].get(0)[0]!=previn) {
fren=list[mindeg].get(0)[0];
ind=list[mindeg].get(0)[1];
}else {
fren=list[mindeg].get(1)[0];
ind=list[mindeg].get(1)[1];
}
if(prev==2)ans[ind]=5;
else ans[ind]=2;
prev=ans[ind];
previn=mindeg;
mindeg=fren;
}
for(int i : ans)out.print(i+ " ");
out.println();
}
out.close();
}
static long gcd(long a, long b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a - b, b);
return gcd(a, b - a);
}
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 11
|
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
|
3cf15a575fa6b991b38437b99612f113
|
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 NotAssigning {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while(t-- > 0){
int n = in.nextInt();
HashMap<Integer,ArrayList<Integer>> map = new HashMap<>();
HashMap<String,Integer> pos = new HashMap<>();
int [] deg = new int[n+1];
for(int i = 0;i < n-1;i++){
int u = in.nextInt();
int v = in.nextInt();
map.putIfAbsent(u,new ArrayList<Integer>());
map.putIfAbsent(v,new ArrayList<Integer>());
map.get(u).add(v);
map.get(v).add(u);
String s1 = u + "*" +v ;
String s2 = v + "*" + u;
pos.put(s1,i);
pos.put(s2,i);
deg[u]++;
deg[v]++;
}
boolean is = false;
int s = -1,e = -1;
for(int i = 1;i < deg.length;i++){
if(deg[i] >= 3){
is = true;
break;
}
if(deg[i] == 1){
if(s == -1) s = i;
else e = i;
}
}
if(is){
System.out.println(-1);
continue;
}
int [] arr = new int[n-1];
int cur = s;
int weight = 2;
boolean [] visited = new boolean[n+1];
while(cur != e){
int nxt = map.get(cur).get(0);
if(visited[nxt]){
nxt = map.get(cur).get(1);
}
String key = cur + "*" + nxt;
arr[pos.get(key)] = weight;
if(weight == 2) weight = 3;
else weight = 2;
visited[cur] = true;
cur = nxt;
}
for(int i = 0;i < arr.length;i++)
System.out.print(arr[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 11
|
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
|
eb8c3a18ef58546327e192552f0042e1
|
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.lang.Math.*;
public class C{
static int n;
static class Edge{
int i, to;
public Edge(int a, int b) {
i = a;
to = b;
}
}
static void dfs(int i, int p, int cdol) {
for (Edge x: adj[i]) {
if (x.to==p) continue;
col[x.i] = cdol;
dfs(x.to, i, cdol^1);
}
}
static int[] col;
static List<Edge>[] adj;
public static void main(String[] args) throws IOException{
// br = new BufferedReader(new FileReader(".in"));
// out = new PrintWriter(new FileWriter(".out"));
// new Thread(null, new (), "fisa balls", 1<<28).start();
int t= readInt();
outer: while(t-->0) {
// if deg >= 3 just fail
n =readInt();
adj = new List[n];col = new int[n-1];
for (int i = 0; i < n; i++) adj[i] = new ArrayList<Edge>();
for (int i = 0; i < n-1; i++) {
int u =readInt()-1;
int v =readInt()-1;
adj[u].add(new Edge(i,v));
adj[v].add(new Edge(i,u));
}
for (int i = 0; i < n; i++) if (adj[i].size()>=3) {
out.println(-1);
continue outer;
}
// otherwise just dfs fill with 2 3
for (int i = 0; i < n; i++) if (adj[i].size() == 1) {
dfs(i,i,0);
break;
}
for (int x: col) out.print(x + 2 + " ");
out.println();
}
out.close();
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static StringTokenizer st = new StringTokenizer("");
static String read() throws IOException{
while (!st.hasMoreElements()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public static int readInt() throws IOException{return Integer.parseInt(read());}
public static long readLong() throws IOException{return Long.parseLong(read());}
}
|
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 11
|
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
|
76c7292e1242736b40cf779ac1f6521e
|
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 tc = sc.nextInt();
while(tc>0)
{
tc--;
int ans = 0;
int n = sc.nextInt();
int in[] = new int[n];
int wx[] = new int[n-1];
int wy[] = new int[n-1];
ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
HashMap<String,Integer> h = new HashMap<String,Integer>();
HashSet<Integer> h2 = new HashSet<Integer>();
for(int i=0;i<n;i++)
{
arr.add(new ArrayList<Integer>());
}
for(int i=0;i<n-1;i++)
{
int x = sc.nextInt();
int y = sc.nextInt();
x--;
y--;
in[x]++;
in[y]++;
if(in[x]>2 || in[y]>2)
{
ans = -1;
}
else if(ans!=-1)
{
arr.get(x).add(y);
arr.get(y).add(x);
wx[i] = x;
wy[i] = y;
}
}
if(ans == -1)
{
System.out.println("-1");
}
else
{
int vis[] = new int[n];
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
q.add(0);
vis[0] = 1;
while(q.size()>0)
{
int x = q.removeFirst();
for(int i=0;i<arr.get(x).size();i++)
{
int y = arr.get(x).get(i);
String temp =String.valueOf(x);
if(vis[y] == 0)
{
vis[y] = 1;
if(h2.contains(y) || h2.contains(x))
{
String s1 = temp+"_"+String.valueOf(y);
String s2 = String.valueOf(y)+"_"+temp;
h.put(s1,11);
h.put(s2,11);
}
else
{
String s1 = temp+"_"+String.valueOf(y);
String s2 = String.valueOf(y)+"_"+temp;
h.put(s1,2);
h.put(s2,2);
h2.add(x);
h2.add(y);
}
q.add(y);
}
}
}
for(int i=0;i<wx.length;i++)
{
String s1 = String.valueOf(wx[i])+"_"+String.valueOf(wy[i]);
System.out.print(h.get(s1)+" ");
}
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 11
|
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
|
5528ee672d65909d9d73e3e415da7a1c
|
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
{
static ArrayList<Integer>[] tree;
static HashMap<Pair , Integer> map = new HashMap<Pair , Integer>();
static void dfs(int x , int par , int val)
{
if(par!=-1)
{
map.put(new Pair(x , par) , val);
map.put(new Pair(par , x) , val);
}
for(int i:tree[x])
{
if(i!=par)
{
dfs(i , x , (5 - val));
}
}
}
static long mod = (int)1e9+7;
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main (String[] args) throws java.lang.Exception
{
FastReader sc =new FastReader();
int t=sc.nextInt();
// int t=1;
while(t-->0)
{
int n = sc.nextInt();
tree = new ArrayList[n];
Pair arr[] = new Pair[n - 1];
for(int i=0;i<n;i++)
{
tree[i] = new ArrayList<Integer>();
}
for(int i=0;i<n - 1;i++)
{
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
arr[i] = new Pair(x , y);
tree[x].add(y);
tree[y].add(x);
}
boolean flag = true;
for(int i=0;i<n;i++)
{
if(tree[i].size() >= 3)
{
flag = false;
break;
}
}
if(!flag)
{
out.println(-1);
}
else
{
for(int i=0;i<n;i++)
{
if(tree[i].size() == 1)
{
dfs(i , -1 , 2);
break;
}
}
for(Pair p:arr)
{
out.print(map.get(p)+" ");
}
out.println();
}
}
out.flush();
}
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());
}
float nextFloat()
{
return Float.parseFloat(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readArrayLong(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
public static int[] radixSort2(int[] a)
{
int n = a.length;
int[] c0 = new int[0x101];
int[] c1 = new int[0x101];
int[] c2 = new int[0x101];
int[] c3 = new int[0x101];
for(int v : a) {
c0[(v&0xff)+1]++;
c1[(v>>>8&0xff)+1]++;
c2[(v>>>16&0xff)+1]++;
c3[(v>>>24^0x80)+1]++;
}
for(int i = 0;i < 0xff;i++) {
c0[i+1] += c0[i];
c1[i+1] += c1[i];
c2[i+1] += c2[i];
c3[i+1] += c3[i];
}
int[] t = new int[n];
for(int v : a)t[c0[v&0xff]++] = v;
for(int v : t)a[c1[v>>>8&0xff]++] = v;
for(int v : a)t[c2[v>>>16&0xff]++] = v;
for(int v : t)a[c3[v>>>24^0x80]++] = v;
return a;
}
static void reverse_sorted(int[] arr)
{
ArrayList<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);
}
}
static int LowerBound(int a[], int x) { // x is the target value or key
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;
}
static int UpperBound(ArrayList<Integer> list, int x) {// x is the key or target value
int l=-1,r=list.size();
while(l+1<r) {
int m=(l+r)>>>1;
if(list.get(m)<=x) l=m;
else r=m;
}
return l+1;
}
public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm)
{
// Create a list from elements of HashMap
List<Map.Entry<Integer, Integer> > list =
new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet());
// Sort the list
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() {
public int compare(Map.Entry<Integer, Integer> o1,
Map.Entry<Integer, Integer> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
// put data from sorted list to hashmap
HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
static class Queue_Pair implements Comparable<Queue_Pair> {
int first , second;
public Queue_Pair(int first, int second) {
this.first=first;
this.second=second;
}
public int compareTo(Queue_Pair o) {
return Integer.compare(o.first, first);
}
}
static void leftRotate(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
leftRotatebyOne(arr, n);
}
static void leftRotatebyOne(int arr[], int n)
{
int i, temp;
temp = arr[0];
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[n-1] = temp;
}
static boolean isPalindrome(String str)
{
// Pointers pointing to the beginning
// and the end of the string
int i = 0, j = str.length() - 1;
// While there are characters to compare
while (i < j) {
// If there is a mismatch
if (str.charAt(i) != str.charAt(j))
return false;
// Increment first pointer and
// decrement the other
i++;
j--;
}
// Given string is a palindrome
return true;
}
static boolean palindrome_array(char arr[], int n)
{
// Initialise flag to zero.
int flag = 0;
// Loop till array size n/2.
for (int i = 0; i <= n / 2 && n != 0; i++) {
// Check if first and last element are different
// Then set flag to 1.
if (arr[i] != arr[n - i - 1]) {
flag = 1;
break;
}
}
// If flag is set then print Not Palindrome
// else print Palindrome.
if (flag == 1)
return false;
else
return true;
}
static boolean allElementsEqual(int[] arr,int n)
{
int z=0;
for(int i=0;i<n-1;i++)
{
if(arr[i]==arr[i+1])
{
z++;
}
}
if(z==n-1)
{
return true;
}
else
{
return false;
}
}
static boolean allElementsDistinct(int[] arr,int n)
{
int z=0;
for(int i=0;i<n-1;i++)
{
if(arr[i]!=arr[i+1])
{
z++;
}
}
if(z==n-1)
{
return true;
}
else
{
return false;
}
}
public static void reverse(int[] array)
{
// Length of the array
int n = array.length;
// Swaping the first half elements with last half
// elements
for (int i = 0; i < n / 2; i++) {
// Storing the first half elements temporarily
int temp = array[i];
// Assigning the first half to the last half
array[i] = array[n - i - 1];
// Assigning the last half to the first half
array[n - i - 1] = temp;
}
}
public static void reverse_Long(long[] array)
{
// Length of the array
int n = array.length;
// Swaping the first half elements with last half
// elements
for (int i = 0; i < n / 2; i++) {
// Storing the first half elements temporarily
long temp = array[i];
// Assigning the first half to the last half
array[i] = array[n - i - 1];
// Assigning the last half to the first half
array[n - i - 1] = temp;
}
}
static boolean isSorted(int[] a)
{
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
static boolean isReverseSorted(int[] a)
{
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] < a[i + 1]) {
return false;
}
}
return true;
}
static int[] rearrangeEvenAndOdd(int arr[], int n)
{
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<n;i++)
{
if(arr[i]%2==0)
{
list.add(arr[i]);
}
}
for(int i=0;i<n;i++)
{
if(arr[i]%2!=0)
{
list.add(arr[i]);
}
}
int len = list.size();
int[] array = list.stream().mapToInt(i->i).toArray();
return array;
}
static long[] rearrangeEvenAndOddLong(long arr[], int n)
{
ArrayList<Long> list = new ArrayList<>();
for(int i=0;i<n;i++)
{
if(arr[i]%2==0)
{
list.add(arr[i]);
}
}
for(int i=0;i<n;i++)
{
if(arr[i]%2!=0)
{
list.add(arr[i]);
}
}
int len = list.size();
long[] array = list.stream().mapToLong(i->i).toArray();
return array;
}
static boolean isPrime(long n)
{
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (long i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
static long getSum(long n)
{
long sum = 0;
while (n != 0)
{
sum = sum + n % 10;
n = n/10;
}
return sum;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static long gcdLong(long a, long b)
{
if (b == 0)
return a;
return gcdLong(b, a % b);
}
static void swap(int i, int j)
{
int temp = i;
i = j;
j = temp;
}
static int countDigit(int n)
{
return (int)Math.floor(Math.log10(n) + 1);
}
}
class Pair implements Comparable<Pair> {
long x;
long y;
public Pair(long x, long 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 Long(x).hashCode() * 31 + new Long(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);
}
}
|
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 11
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.