message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0
instruction
0
7,402
13
14,804
"Correct Solution: ``` n,m = map(int,input().split()) INF = 10**18 d = [[INF]*n for _ in range(n)] nd = [[INF]*n for _ in range(n)] for i in range(n): d[i][i] = 0 nd[i][i] = 0 for _ in range(m): a,b,c = map(int,input().split()) a -= 1 b -= 1 d[a][b] = c d[b][a] = c nd[a][b] = c nd[b][a] = c for k in range(n): for i in range(n): for j in range(n): nd[i][j] = min(nd[i][j], nd[i][k]+nd[k][j]) cnt = 0 for i in range(n): for j in range(n): if d[i][j] == INF: continue if nd[i][j] < d[i][j]: cnt += 1 print(cnt//2) ```
output
1
7,402
13
14,805
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0
instruction
0
7,403
13
14,806
"Correct Solution: ``` INF = float("inf") def WarshallFloyd(M): N = len(M) for k in range(N): for j in range(N): for i in range(N): M[i][j] = min(M[i][j], M[i][k] + M[k][j]) return M N, M, *ABC = map(int, open(0).read().split()) E = [[INF] * (N + 1) for _ in range(N + 1)] for a, b, c in zip(*[iter(ABC)] * 3): E[a][b] = c E[b][a] = c D = WarshallFloyd(E) print(sum(D[a][b] < c for a, b, c in zip(*[iter(ABC)] * 3))) ```
output
1
7,403
13
14,807
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0
instruction
0
7,404
13
14,808
"Correct Solution: ``` N, M = list(map(int, input().split())) abc = [list(map(int, input().split())) for _ in range(M)] inf = 1000000 L = [[0] * N for _ in range(N)] C = [[inf] * N for _ in range(N)] for i in range(M): a, b, c = abc[i] a -= 1 b -= 1 C[a][b] = c C[b][a] = c for i in range(N): C[i][i] = 0 for k in range(N): for i in range(N): for j in range(N): if C[i][j] > C[i][k] + C[k][j]: C[i][j] = C[i][k] + C[k][j] L[i][j] = 1 n = 0 for i in range(N): for j in range(N): if L[i][j] == 1: n += 1 print(M - ((N * (N - 1) // 2) - (n // 2))) ```
output
1
7,404
13
14,809
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0
instruction
0
7,405
13
14,810
"Correct Solution: ``` N, M = map(int, input().split()) inf = 10**6 abc = [] d = [[inf]*N for i in range(N)] for i in range(M): a, b, c = map(int, input().split()) d[a-1][b-1] = c d[b-1][a-1] = c abc.append((a-1,b-1,c)) for k in range(N): for i in range(N): for j in range(N): d[i][j] = min(d[i][k]+d[k][j], d[i][j]) ans = 0 for i in range(M): a, b, c = abc[i] if d[a][b] < inf and d[a][b] < c: ans += 1 print(ans) ```
output
1
7,405
13
14,811
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0
instruction
0
7,406
13
14,812
"Correct Solution: ``` def warshall_floyd(d): for k in range(N): for i in range(N): for j in range(N): d[i][j] = min(d[i][j], d[i][k] + d[k][j]) return d N, M = map(int, input().split()) d = [[float('inf') for i in range(N)] for i in range(N)] edges = [] for i in range(M): a,b,c = map(int, input().split()) a -= 1 b -= 1 d[a][b] = c d[b][a] = c edges.append([a,b,c]) warshall_floyd(d) # 与えられた頂点間の辺の距離が求めた最短距離より大きければ # その辺は使われない cnt = 0 for edge in edges: if d[edge[0]][edge[1]] != edge[2]: cnt += 1 print(cnt) ```
output
1
7,406
13
14,813
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0
instruction
0
7,407
13
14,814
"Correct Solution: ``` n,m=[int(x) for x in input().split()] path=[] d=[[float("inf") for _ in [0]*n] for _2 in [0]*n] for _ in [0]*m: a,b,c=[int(x) for x in input().split()] path.append((a-1,b-1,c)) d[a-1][b-1]=d[b-1][a-1]=c from itertools import product for k,i,j in product(range(n),range(n),range(n)): if d[i][j]>d[i][k]+d[k][j]: d[i][j]=d[i][k]+d[k][j] ans=0 for a,b,c in path: if d[a][b]!=c: ans+=1 print(ans) ```
output
1
7,407
13
14,815
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0
instruction
0
7,408
13
14,816
"Correct Solution: ``` # -*- coding: utf-8 -*- def inpl(): return map(int, input().split()) N, M = inpl() INF = float("inf") G = [[INF]*(N) for _ in range(N)] E = [] for _ in range(M): a, b, c = inpl() G[a-1][b-1] = c G[b-1][a-1] = c E.append([a-1, b-1, c]) for k in range(N): for i in range(N): for j in range(N): G[i][j] = min(G[i][j], G[i][k] + G[k][j]) print(sum([G[a][b] < c for a, b, c in E])) ```
output
1
7,408
13
14,817
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0
instruction
0
7,409
13
14,818
"Correct Solution: ``` n,m=map(int,input().split()) inf=float("inf") data=[[inf]*(n+1) for i in range(n+1)] for i in range(1,n+1): data[i][i]=0 lst=[] for u in range(m): a,b,c=map(int,input().split()) data[a][b]=c data[b][a]=c lst.append([a,b,c]) for k in range(1,n+1): for i in range(1,n+1): for j in range(1,n+1): data[i][j]=min(data[i][j],data[i][k]+data[k][j]) ans=0 for u in lst: a,b,c=u if data[a][b]!=c: ans+=1 print(ans) ```
output
1
7,409
13
14,819
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0 Submitted Solution: ``` N,M=[int(i) for i in input().split()] edges=[[2**60 for i in range(N)] for j in range(N)] for i in range(M): a,b,c=[int(i) for i in input().split()] a-=1 b-=1 edges[a][b]=edges[b][a]=c mini=[[edges[i][j] for i in range(N)] for j in range(N)] for k in range(N): for i in range(N): for j in range(N): mini[i][j]=min(mini[i][j],mini[i][k]+mini[k][j]) res=0 for r in range(N): for l in range(r): #print(l,".",r,"->",edges[l][r],mini[l][r]) if edges[l][r] != 2**60 and mini[l][r]<edges[l][r]: res+=1 print(res) ```
instruction
0
7,410
13
14,820
Yes
output
1
7,410
13
14,821
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0 Submitted Solution: ``` from copy import deepcopy N, M = map(int, input().split()) INF = 10000000 D = [[INF for _ in range(N)] for _ in range(N)] for _ in range(M): a, b, c = map(int, input().split()) D[a-1][b-1] = c D[b-1][a-1] = c F = deepcopy(D) for k in range(N): for i in range(N): for j in range(N): F[i][j] = min(F[i][j], F[i][k]+F[k][j]) a = 0 for i in range(N): for j in range(N): if D[i][j] == F[i][j]: a += 1 a //= 2 print(M-a) ```
instruction
0
7,411
13
14,822
Yes
output
1
7,411
13
14,823
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0 Submitted Solution: ``` n,m = map(int,input().split()) INF = 10**18 d = [[INF]*n for _ in range(n)] for i in range(n): d[i][i] = 0 A = [0]*m B = [0]*m C = [0]*m for i in range(m): a,b,c = map(int,input().split()) a -= 1 b -= 1 A[i] = a B[i] = b C[i] = c d[a][b] = c d[b][a] = c for k in range(n): for i in range(n): for j in range(n): d[i][j] = min(d[i][j], d[i][k]+d[k][j]) ans = 0 for i in range(m): if d[A[i]][B[i]] < C[i]: ans += 1 print(ans) ```
instruction
0
7,412
13
14,824
Yes
output
1
7,412
13
14,825
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0 Submitted Solution: ``` def warshall_floyd(d,n): #d[i][j]: iからjへの最短距離 for k in range(n): for i in range(n): for j in range(n): d[i][j] = min(d[i][j],d[i][k] + d[k][j]) return d N,M = [int(x) for x in input().split()] INF = float('inf') edges = [] d = [[INF]*N for _ in range(N)] for _ in range(M): a,b,c = [int(x) for x in input().split()] a-=1 b-=1 d[a][b]=c d[b][a]=c edges.append([a,b,c]) warshall_floyd(d,N) cnt = 0 for e in edges: if(d[e[0]][e[1]]!=e[2]): cnt+=1 print(cnt) ```
instruction
0
7,413
13
14,826
Yes
output
1
7,413
13
14,827
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0 Submitted Solution: ``` inf = 10**10 N, M = map(int, input().split()) g = [[0 for _ in range(N)] for _ in range(N)] for _ in range(M): a, b, c = map(int, input().split()) g[a-1][b-1] = c g[b-1][a-1] = c g2 = [[inf if not i else i for i in j] for j in g] for i in range(N): g2[i][i] = 0 ans = 0 for i in range(N): for j in range(N): if g[i][j]: f = 1 else: f = 0 for k in range(N): if f == 1 and g2[i][j] > g2[i][k] + g2[k][j]: ans += 1 f = 0 g2[i][j] = min(g2[i][j],g2[i][k]+g2[k][j]) g2[j][i] = min(g2[i][j],g2[i][k]+g2[k][j]) print(ans) ```
instruction
0
7,414
13
14,828
No
output
1
7,414
13
14,829
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0 Submitted Solution: ``` N,M=map(int,input().split()) import heapq def dijkstra_heap(s): #始点sから各頂点への最短距離 dist=[float("inf")]*size_v used=[False]*size_v prev=[-1]*size_v dist[s]=0 used[s]=True hq_edge=[] for v,w,i in graph[s]: heapq.heappush(hq_edge,(w,v,i)) while hq_edge: min_w,min_v,ei=heapq.heappop(hq_edge) #まだ使われてない頂点の中から最小の距離のものを探す if used[min_v]: continue dist[min_v]=min_w used[min_v]=True prev[min_v]=ei for v,w,ei2 in graph[min_v]: if not used[v]: heapq.heappush(hq_edge,(min_w+w,v,ei2)) #return dist return prev graph=[[] for _ in range(N+1)] for i in range(M): a,b,c=map(int,input().split()) graph[a].append((b,c,i)) graph[b].append((a,c,i)) #print(graph) size_v=N+1 answer_set=set() for i in range(1,N+1): prev=dijkstra_heap(i) #print(prev) for j in range(1,N+1): if i==j: continue answer_set.add(prev[j]) #print(answer_set) print(M-len(answer_set)) ```
instruction
0
7,415
13
14,830
No
output
1
7,415
13
14,831
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0 Submitted Solution: ``` import sys input = sys.stdin.readline n,m=map(int,input().split()) d=[[100000]*n for _ in range(n)] a=[0]*m b=[0]*m c=[0]*m for i in range(m): a0,b0,c0=map(int,input().split()) a[i]=a0-1 b[i]=b0-1 c[i]=c0 d[a0-1][b0-1]=c0 d[b0-1][a0-1]=c0 for i in range(n): d[i][i]=0 for k in range(n): for i in range(n): for j in range(n): d[i][j]=min(d[i][j],d[i][k]+d[k][j]) count=0 for edge in range(m): flag=False for j in range(n): for k in range(n): if d[j][a[edge]]+c[edge]==d[j][b[edge]]: flag=True break if flag: break else: count+=1 print(count) ```
instruction
0
7,416
13
14,832
No
output
1
7,416
13
14,833
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). A connected graph is a graph where there is a path between every pair of different vertices. Find the number of the edges that are not contained in any shortest path between any pair of different vertices. Constraints * 2≤N≤100 * N-1≤M≤min(N(N-1)/2,1000) * 1≤a_i,b_i≤N * 1≤c_i≤1000 * c_i is an integer. * The given graph contains neither self-loops nor double edges. * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices. Examples Input 3 3 1 2 1 1 3 1 2 3 3 Output 1 Input 3 2 1 2 1 2 3 1 Output 0 Submitted Solution: ``` n,m = map(int,input().split()) l = [list(map(int,input().split())) for _ in range(m)] dp = [[0 for _ in range(n)] for _ in range(n)] INF = 10**18 for i in range(n): for j in range(n): if i!=j: dp[i][j] = INF for a,b,t in l: dp[a-1][b-1] = t dp[b-1][a-1] = t #print(dp) #最短リスト for c in range(n): for f in range(n): for la in range(n): dp[f][la] = min(dp[f][la] , dp[f][c] + dp[c][la]) #各辺が何かしらの最短ルートに含まれているか ans = 0 for a, b, t in l: cou = 0 for j in range(n): for k in range(n): #jからkの最短ルートにa,bが入ってるいるか if dp[j][k] != dp[j][a-1] + t + dp[b-1][k]: cou += 1 if cou==n**2: ans += 1 print(ans) ```
instruction
0
7,417
13
14,834
No
output
1
7,417
13
14,835
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers.
instruction
0
7,582
13
15,164
Tags: dfs and similar, graphs Correct Solution: ``` import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from collections import defaultdict def dfs(node): vis[node]=1 colour[node]=0 arr[0]+=1 stack=[node] while stack: cur=stack.pop() for j in edge[cur]: if vis[j]==0: stack.append(j) colour[j]=colour[cur]^1 vis[j]=1 arr[colour[j]]+=1 else: if colour[cur]==colour[j]: return False return True t=int(input()) for _ in range(t): n,m=list(map(int,input().split())) edge=defaultdict(list) z=998244353 for i in range(m): u,v=list(map(int,input().split())) edge[u].append(v) edge[v].append(u) ans=1 s=0 vis=[0]*(n+1) colour=[0]*(n+1) for i in range(1,n+1): if vis[i]==0: arr=[0,0] if dfs(i): a=1 b=1 for j in range(arr[0]): a*=2 a%=z for j in range(arr[1]): b*=2 b%=z ans*=(a+b) ans%=z else: s+=1 break if s==1: print(0) else: print(ans) ```
output
1
7,582
13
15,165
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers.
instruction
0
7,583
13
15,166
Tags: dfs and similar, graphs Correct Solution: ``` from sys import stdin,stdout from collections import defaultdict import sys, threading sys.setrecursionlimit(10**6) # max depth of recursion threading.stack_size(2**25) def main(): def power(x, p): re = 1 mode= 998244353 while p: if p & 1: re = re * x % mode x = x * x % mode p >>= 1 return re; def dfs(node,col): visited[node]=True c[col]+=1 color[node]=col for j in dic[node]: if not visited[j]: if not dfs(j, col ^ 1): return False else: if color[j]==color[node]: return False return True t=int(stdin.readline()) for _ in range(t): mod=998244353 n,m=map(int,stdin.readline().split()) dic=defaultdict(list) for i in range(m): u,v=map(int,stdin.readline().split()) dic[u].append(v) dic[v].append(u) visited=[False]*(n+1) color=[-1]*(n+1) c=[0]*2 result=1 flag=0 #print(dic) for i in range(1,n+1): if not visited[i]: res=dfs(i,0) if not res: flag=1 break else: result=(result*(power(2,c[0])+power(2,c[1])))%mod c[0]=0 c[1]=0 if flag==1: stdout.write("0\n") else: stdout.write(str(result)+"\n") threading.Thread(target=main).start() ```
output
1
7,583
13
15,167
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers.
instruction
0
7,584
13
15,168
Tags: dfs and similar, graphs Correct Solution: ``` # aadiupadhyay import os.path from math import gcd, floor, ceil from collections import * import sys from heapq import * mod = 998244353 INF = float('inf') def st(): return list(sys.stdin.readline().strip()) def li(): return list(map(int, sys.stdin.readline().split())) def mp(): return map(int, sys.stdin.readline().split()) def inp(): return int(sys.stdin.readline()) def pr(n): return sys.stdout.write(str(n)+"\n") def prl(n): return sys.stdout.write(str(n)+" ") if os.path.exists('input.txt'): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') def solve(): def dfs(x): visited[x] = 1 stack = [x] color[x] = 0 val = [0, 0] while stack: a = stack.pop() val[color[a]] += 1 for i in d[a]: if visited[i]: if color[i] == color[a]: return 0 else: color[i] = color[a] ^ 1 visited[i] = 1 stack.append(i) ans = 0 for i in val: ans += pow(2, i, mod) ans %= mod return ans n, m = mp() d = defaultdict(list) for i in range(m): a, b = mp() d[a].append(b) d[b].append(a) visited = defaultdict(int) ans = 1 color = defaultdict(lambda: -1) for i in range(1, n+1): if not visited[i]: cur = dfs(i) if cur == 0: pr(0) return ans *= cur ans %= mod pr(ans) for _ in range(inp()): solve() ```
output
1
7,584
13
15,169
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers.
instruction
0
7,585
13
15,170
Tags: dfs and similar, graphs Correct Solution: ``` # einlesen # dfs für jede cc # Zählen, wie viele w/r # wenn cooring nicht möglich -> Ergebnis 0 # sonst 2^w+2^r M=998244353 t=int(input()) n,m=0,0 g=[] v=[] def dfs(r): s=[r] v[r]=1 c=[0,1] while s: x=s.pop() for j in g[x]: if v[j]==v[x]:return 0 if v[j]==-1: v[j]=v[x]^1 c[v[j]]+=1 s.append(j) if c[0]==0 or c[1]==0:return 3 return ((2**c[0])%M + (2**c[1])%M)%M o=[] for i in range(t): n,m=map(int,input().split()) g=[[]for _ in range(n)] for _ in range(m): a,b=map(int,input().split()) g[a-1].append(b-1) g[b-1].append(a-1) v=[-1]*n ox=1 for j in range(n): if v[j]==-1: ox=(ox*dfs(j))%M o.append(ox) print('\n'.join(map(str,o))) ```
output
1
7,585
13
15,171
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers.
instruction
0
7,586
13
15,172
Tags: dfs and similar, graphs Correct Solution: ``` ###pyrival template for fast IO import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") mod=998244353 def graph_undirected(): n,e=[int(x) for x in input().split()] graph={} #####adjecancy list using dict for i in range(e): vertex,neighbour=[int(x) for x in input().split()] if vertex in graph: graph[vertex].append(neighbour) else: graph[vertex]=[neighbour] if neighbour in graph: #####for undirected part remove to get directed graph[neighbour].append(vertex) else: graph[neighbour]=[vertex] return graph,n #########check a graph is biparte (bfs+graph coloring to detect odd lenght cycle) from collections import deque def cycle_bfs(graph,n,node):###odd len cycle q=deque([node]);color[node]=0 while q: currnode=q.popleft();visited[currnode]=True; a[color[currnode]]+=1 if color[currnode]==0:currcolor=1 else:currcolor=0 if currnode in graph: for neighbour in graph[currnode]: if visited[neighbour]==False: visited[neighbour]=True color[neighbour]=currcolor q.append(neighbour) else: if color[neighbour]!=currcolor: return False return True k=3*(10**5)+10 pow2=[1 for x in range(k)] pow3=[1 for x in range(k)] for i in range(1,k): pow2[i]=pow2[i-1]*2 pow3[i]=pow3[i-1]*3 pow2[i]%=mod pow3[i]%=mod t=int(input()) while t: t-=1 graph,n=graph_undirected() c=0 for i in range(1,n+1): if i not in graph: c+=1 visited=[False for x in range(n+1)] color=[None for x in range(n+1)] res=1 a=[0,0] for i in range(1,n+1): if visited[i]==False and i in graph: a=[0,0] ans=cycle_bfs(graph,n,i) if ans: res*=(pow2[a[0]]+pow2[a[1]])%mod res%=mod else: res=0 break res*=pow3[c]%mod sys.stdout.write(str(res%mod)+"\n") ```
output
1
7,586
13
15,173
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers.
instruction
0
7,587
13
15,174
Tags: dfs and similar, graphs Correct Solution: ``` M=998244353 t=int(input()) n,m=0,0 g=[] v=[] def dfs(r): s=[r] v[r]=1 c=[0,1] while s: x=s.pop() for j in g[x]: if v[j]==v[x]:return 0 if v[j]==-1: v[j]=v[x]^1 c[v[j]]+=1 s.append(j) if c[0]==0 or c[1]==0:return 3 return ((2**c[0])%M + (2**c[1])%M)%M o=[] for i in range(t): n,m=map(int,input().split()) g=[[]for _ in range(n)] for _ in range(m): a,b=map(int,input().split()) g[a-1].append(b-1) g[b-1].append(a-1) v=[-1]*n ox=1 for j in range(n): if v[j]==-1: ox=(ox*dfs(j))%M o.append(ox) print('\n'.join(map(str,o))) ```
output
1
7,587
13
15,175
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers.
instruction
0
7,588
13
15,176
Tags: dfs and similar, graphs Correct Solution: ``` from collections import defaultdict from collections import deque import sys input = sys.stdin.readline mod = 998244353 def bfs(node,v,p): ans=1 q=deque() q.append(node) v[node]=1 a,b=0,0 while q: i=q.popleft() if p[i]==1: a=a+1 else: b=b+1 for j in d[i]: if v[j]==0: v[j]=1 v[j]=1 q.append(j) p[j]=1 if p[i]==0 else 0 else: if p[j]==p[i]: return 0 return (2**a + 2**b)%mod t=int(input()) for _ in range(t): n,m=map(int,input().split()) d=defaultdict(list) p={} for i in range(m): x,y=map(int,input().split()) d[x].append(y) d[y].append(x) v=[0]*(n+1) ans=1 for i in d: if v[i]==0: p[i]=1 f=bfs(i,v,p) ans=(ans*f)%mod for i in range(1,n+1): if v[i]==0: ans=(ans*3)%mod print(ans%mod) ```
output
1
7,588
13
15,177
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers.
instruction
0
7,589
13
15,178
Tags: dfs and similar, graphs Correct Solution: ``` from sys import stdin,stdout from collections import defaultdict import sys, threading sys.setrecursionlimit(10**5) # max depth of recursion threading.stack_size(2**25) def main(): def power(x, p): re = 1 mode= 998244353 while p: if p & 1: re = re * x % mode x = x * x % mode p >>= 1 return re; def dfs(node,col): visited[node]=True c[col]+=1 color[node]=col for j in dic[node]: if not visited[j]: if not dfs(j, col ^ 1): return False else: if color[j]==color[node]: return False return True t=int(stdin.readline()) for _ in range(t): mod=998244353 n,m=map(int,stdin.readline().split()) dic=defaultdict(list) for i in range(m): u,v=map(int,stdin.readline().split()) dic[u].append(v) dic[v].append(u) visited=[False]*(n+1) color=[-1]*(n+1) c=[0]*2 result=1 flag=0 #print(dic) for i in range(1,n+1): if not visited[i]: res=dfs(i,0) if not res: flag=1 break else: result=(result*(power(2,c[0])+power(2,c[1])))%mod c[0]=0 c[1]=0 if flag==1: stdout.write("0\n") else: stdout.write(str(result)+"\n") threading.Thread(target=main).start() ```
output
1
7,589
13
15,179
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers. Submitted Solution: ``` mod=998244353 import sys input = sys.stdin.readline from collections import deque from collections import Counter def calc(s,a): return (pow(2,s,mod)+pow(2,a-s,mod))%mod def find(x): while Group[x] != x: x=Group[x] return x def Union(x,y): if find(x) != find(y): Group[find(y)]=Group[find(x)]=min(find(y),find(x)) testcase=int(input()) for test in range(testcase): n,m=map(int,input().split()) EDGE=[list(map(int,input().split())) for i in range(m)] EDGELIST=[[] for j in range(n+1)] ANS=1 Group=[j for j in range(n+1)] for a,b in EDGE: Union(a,b) EDGELIST[a].append(b) EDGELIST[b].append(a) testing=[None]*(n+1) flag=1 for i in range(1,n+1): if testing[i]!=None: continue score=1 allscore=1 testing[i]=1 QUE = deque([i]) while QUE: x=QUE.pop() for to in EDGELIST[x]: if testing[to]==-testing[x]: continue if testing[to]==testing[x]: flag=0 break testing[to]=-testing[x] if testing[to]==1: score+=1 allscore+=1 QUE.append(to) if flag==0: break if flag==0: break #print(score,allscore) ANS=ANS*calc(score,allscore)%mod if flag==0: print(0) continue print(ANS) ```
instruction
0
7,590
13
15,180
Yes
output
1
7,590
13
15,181
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers. Submitted Solution: ``` from sys import stdin input=lambda : stdin.readline().strip() from math import ceil,sqrt,factorial,gcd from collections import deque from bisect import bisect_left def dfs(x): stack=[[x,1]] a,b=0,0 while stack: x,v=stack.pop() if visited[x]==0: if v==1: a+=1 t=2 else: b+=1 t=1 visited[x]=v for i in graph[x]: if visited[i]==0: stack.append([i,t]) graph[i].remove(x) return a,b def check(x): stack=[x] s=set() while stack: x=stack.pop() s.add(x) for i in graph[x]: if i not in s: stack.append(i) if (visited[x]+visited[i])%2==0: return 0 return 1 for _ in range(int(input())): n,m=map(int,input().split()) graph={i:set() for i in range(n)} visited=[0 for i in range(n)] for i in range(m): a,b=map(int,input().split()) graph[a-1].add(b-1) graph[b-1].add(a-1) f=1 mod=998244353 count=1 for i in range(n): if visited[i]==0 and len(graph[i])!=0: a,b=dfs(i) f=check(i) if f==0: print(0) break else: count=(count*(pow(2,a,mod)+pow(2,b,mod)))%mod if f==1: print((count*pow(3,visited.count(0),mod))%mod) ```
instruction
0
7,591
13
15,182
Yes
output
1
7,591
13
15,183
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ########################################################## import math import bisect mod=998244353 # for _ in range(int(input())): from collections import Counter # sys.setrecursionlimit(10**6) # dp=[[-1 for i in range(n+5)]for j in range(cap+5)] # arr= list(map(int, input().split())) #n,l= map(int, input().split()) # arr= list(map(int, input().split())) # for _ in range(int(input())): # n=int(input()) #for _ in range(int(input())): import bisect from heapq import * from collections import defaultdict #n=int(input()) #n,m,s,d=map(int, input().split()) #arr = sorted(list(map(int, input().split()))) #ls=list(map(int, input().split())) #d=defaultdict(list) from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc mod = 998244353 def power(base, exp): base %= mod if exp < 3: return (base ** exp) % mod half = power(base * base, exp // 2) return (half * base) % mod if exp % 2 == 1 else half % mod def solve(): n, m = map(int, input().split()) graph = [[] for _ in range(n + 1)] count, visited = [0, 0], [-1 for _ in range(n + 1)] for _ in range(m): u, v = map(int, input().split()) graph[u].append(v) graph[v].append(u) possible, ans = True, 1 @bootstrap def dfs(node, par, parity): nonlocal possible, visited, graph, count if visited[node] != -1: possible = False if visited[node] != parity else possible yield None visited[node] = parity count[parity] += 1 for child in graph[node]: if child != par: yield dfs(child, node, 1 - parity) yield # check for each node and update the answer for i in range(1, n + 1): if visited[i] == -1: count = [0, 0] dfs(i, -1, 1) ans *= (power(2, count[0]) + power(2, count[1])) % mod ans %= mod # print(ans if possible else 0) sys.stdout.write(str(ans) if possible else '0') sys.stdout.write('\n') def main(): tests = 1 tests = int(input().strip()) for test in range(tests): solve() main() ```
instruction
0
7,592
13
15,184
Yes
output
1
7,592
13
15,185
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers. Submitted Solution: ``` from collections import defaultdict import sys #sys.setrecursionlimit(10**6) #sys.stdin = open('E56D_input.txt', 'r') #sys.stdout = open('output.txt', 'w') input=sys.stdin.readline #print=sys.stdout.write graph = defaultdict(list) color = [0] * ((3 * 10 ** 5) + 1000) bipertite = True MOD = 998244353 result = 1 color_count = [0] * 2 pow_value=[] """ def dfs(s, c): global color global bipertite global color_count color[s] = c color_count[c] += 1 for i in range(0, len(graph[s])): if color[graph[s][i]] == -1: dfs(graph[s][i], 1-c) if color[s] == color[graph[s][i]]: bipertite = False """ t = int((input())) #precomputing powers pow_value.append(1) for i in range(1,(3*10**5)+1000): next_value=(pow_value[i-1]*2)%MOD pow_value.append(next_value) #------------------------ while t: n, m = map(int, input().split()) if m==0: print(pow(3,n,MOD)) t-=1 continue graph.clear() bipertite=True result=1 for node in range(0,n+1): color[node]=-1 while m: u, v = map(int, input().split()) graph[u].append(v) graph[v].append(u) m -= 1 for i in range(1, n + 1): if (color[i] != -1): continue #bfs--- bipertite = True color_count[0] = color_count[1] = 0 queue=[] queue.append(i) color[i] = 0 color_count[0] += 1 while queue: # print(color_count[0],' ',color_count[1]) if bipertite==False: break front_node=queue.pop() for child_node in range(0, len(graph[front_node])): if color[graph[front_node][child_node]] == -1: color[graph[front_node][child_node]] = 1-color[front_node] queue.append(graph[front_node][child_node]) color_count[color[graph[front_node][child_node]]] += 1 elif color[front_node]==color[graph[front_node][child_node]]: bipertite = False break #bfs end if bipertite == False: print(0) break current=(pow_value[color_count[0]]+pow_value[color_count[1]])%MOD result = (result * current) % MOD if bipertite: print(result) t -= 1 ```
instruction
0
7,593
13
15,186
Yes
output
1
7,593
13
15,187
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers. Submitted Solution: ``` for _ in range(int(input())): n,m=map(int,input().split()) a=[[] for i in range(n+1)] b=[] for i in range(m): c,d=map(int,input().split()) a[d].append(c) a[c].append(d) b.append([c,d]) vis=[0]*(n+1) vis[1]='e' st=[1] while st: x=st.pop() for i in a[x]: if vis[i]==0: if vis[x]=='e': vis[i]='o' else: vis[i]='e' st.append(i) fl=0 for i in b: if vis[i[0]]==vis[i[1]]: print(0) fl=1 break if fl==0: x=vis.count('o') y=vis.count('e') m=1 for i in range(x): m*=2 m%=998244353 ans=m m=1 for i in range(y): m*=2 m%=998244353 ans+=m print(ans%998244353) ```
instruction
0
7,594
13
15,188
No
output
1
7,594
13
15,189
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers. Submitted Solution: ``` from collections import * mod = 998244353 class graph: # initialize graph def __init__(self, gdict=None): if gdict is None: gdict = defaultdict(list) self.gdict, self.edges = gdict, [] # add edge def add_edge(self, node1, node2): self.gdict[node1].append(node2) self.gdict[node2].append(node1) self.edges.append([node1, node2]) def get_vertices(self): return list(self.gdict.keys()) def bfs_util(self, i, c): queue, tem, self.color = deque([[i, c - 1]]), c, defaultdict(int, {i: c - 1}) self.visit[i] = 1 while queue: # dequeue parent vertix s = queue.popleft() # enqueue child vertices for i in self.gdict[s[0]]: if self.visit[i] == 0: if s[1] % 2 == 0: tem = (tem * 2) % mod queue.append([i, s[1] ^ 1]) self.visit[i] = 1 self.color[i] = s[1] ^ 1 else: if s[1] % 2 and self.color[i] % 2 or s[1] % 2 == 0 and self.color[i] % 2 == 0: return 0 return tem def bfs(self, c): self.visit, self.cnt = defaultdict(int), 0 for i in self.get_vertices(): if self.visit[i] == 0: self.cnt += self.bfs_util(i, c) return self.cnt for i in range(int(input())): n, m = map(int, input().split()) g, ans = graph(), 0 for j in range(m): u, v = map(int, input().split()) g.add_edge(u, v) if m: ans += g.bfs(2) + g.bfs(1) print(ans % mod) ```
instruction
0
7,595
13
15,190
No
output
1
7,595
13
15,191
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers. Submitted Solution: ``` from collections import defaultdict, deque t = int(input()) for _ in range(t): matrix = defaultdict(list) n,m = list(map(int, input().split())) False_Mat = 1 Tru_Mat = 0 bipartite = False if n == 1: print(3) continue for _ in range(m): u, v = list(map(int, input().split())) matrix[u].append(v) matrix[v].append(u) colors = [False] * (n + 1) visited = [False] * (n + 1) #False = {1, 3} True = {2} queue = deque([1]) while queue and not bipartite: src = queue.popleft() visited[src] = True for dests in matrix[src]: if visited[dests] and colors[src] == colors[dests]: #Not bipartite bipartite = True break if not visited[dests]: queue.append(dests) colors[dests] = not colors[src] if colors[dests]: Tru_Mat += 1 else: False_Mat += 1 if bipartite: print(0) else: print(4 * False_Mat * Tru_Mat) ```
instruction
0
7,596
13
15,192
No
output
1
7,596
13
15,193
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways to write numbers 1, 2 and 3 on vertices so the graph becomes beautiful. Since this number may be large, print it modulo 998244353. Note that you have to write exactly one number on each vertex. The graph does not have any self-loops or multiple edges. Input The first line contains one integer t (1 ≤ t ≤ 3 ⋅ 10^5) — the number of tests in the input. The first line of each test contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ m ≤ 3 ⋅ 10^5) — the number of vertices and the number of edges, respectively. Next m lines describe edges: i-th line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) — indices of vertices connected by i-th edge. It is guaranteed that ∑_{i=1}^{t} n ≤ 3 ⋅ 10^5 and ∑_{i=1}^{t} m ≤ 3 ⋅ 10^5. Output For each test print one line, containing one integer — the number of possible ways to write numbers 1, 2, 3 on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo 998244353. Example Input 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 0 Note Possible ways to distribute numbers in the first test: 1. the vertex 1 should contain 1, and 2 should contain 2; 2. the vertex 1 should contain 3, and 2 should contain 2; 3. the vertex 1 should contain 2, and 2 should contain 1; 4. the vertex 1 should contain 2, and 2 should contain 3. In the second test there is no way to distribute numbers. Submitted Solution: ``` # /////////////////////////////////////////////////////////////////////////// # //////////////////// PYTHON IS THE BEST //////////////////////// # /////////////////////////////////////////////////////////////////////////// import sys,os,io from sys import stdin import math from collections import defaultdict from heapq import heappush, heappop, heapify from bisect import bisect_left , bisect_right from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") alphabets = list('abcdefghijklmnopqrstuvwxyz') #for deep recursion__________________________________________- from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den,p - 2, p)) % p def primeFactors(n): l = [] while n % 2 == 0: l.append(2) n = n / 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: l.append(int(i)) n = n / i if n > 2: l.append(n) # c = dict(Counter(l)) return list(set(l)) # return c def power(x, y, p) : res = 1 x = x % p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res #____________________GetPrimeFactors in log(n)________________________________________ def sieveForSmallestPrimeFactor(): MAXN = 100001 spf = [0 for i in range(MAXN)] spf[1] = 1 for i in range(2, MAXN): spf[i] = i for i in range(4, MAXN, 2): spf[i] = 2 for i in range(3, math.ceil(math.sqrt(MAXN))): if (spf[i] == i): for j in range(i * i, MAXN, i): if (spf[j] == j): spf[j] = i return spf def getPrimeFactorizationLOGN(x): spf = sieveForSmallestPrimeFactor() ret = list() while (x != 1): ret.append(spf[x]) x = x // spf[x] return ret #____________________________________________________________ def SieveOfEratosthenes(n): #time complexity = nlog(log(n)) prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 return prime def si(): return input() def divideCeil(n,x): if (n%x==0): return n//x return n//x+1 def ii(): return int(input()) def li(): return list(map(int,input().split())) # /////////////////////////////////////////////////////////////////////////// # //////////////////// DO NOT TOUCH BEFORE THIS LINE //////////////////////// # /////////////////////////////////////////////////////////////////////////// if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w") else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") @bootstrap def dfs(node,parent,level,adj,color,vis,colors): vis[node]=True for kid in adj[node]: if color[kid]==color[node]: yield False if color[kid]==-1: level[kid]=level[node]+1 color[kid]=abs(1-color[node]) colors[color[kid]%2]+=1 yield dfs(kid,parent,level,adj,color,vis,colors) yield True def solve(): n,m = li() adj = [[] for i in range(n)] mod = 998244353 for i in range(m): u,v = li() u-=1 v-=1 adj[u].append(v) adj[v].append(u) vis = [False]*n level = [0]*n color = [-1]*n ans = 0 total = 1 for i in range(n): if color[i]!=-1: continue if vis[i]==False: vis[i]=True color[i]=0 colors = [1,0] a = dfs(i,-1,level,adj,color,vis,colors) if a==False: print(0) return else: ans=pow(2,colors[0],mod) ans+=pow(2,colors[1],mod) total*=ans total%=mod ans%=mod print(total) t = 1 t = ii() for _ in range(t): solve() ```
instruction
0
7,597
13
15,194
No
output
1
7,597
13
15,195
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2.
instruction
0
7,800
13
15,600
Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` import sys from collections import deque input = sys.stdin.readline def solve(): n = int(input()) G = [[] for _ in range(n)] for _ in range(n-1): a,b = map(int,input().split()) G[a].append(b) G[b].append(a) size = [0]*n par = [-1]*n stk = [0] visited = [False]*n while stk: x = stk[-1] if not visited[x]: visited[x] = True for y in G[x]: if not visited[y]: par[y] = x stk.append(y) else: stk.pop() for y in G[x]: size[x] += size[y] size[x] += 1 visited = [False]*n ans = [0]*(n+1) for y in G[0]: ans[0] += size[y] * (size[y]-1) // 2 P = n*(n-1)//2 P -= ans[0] visited[0] = True l,r = 0,0 for i in range(1,n): if visited[i]: ans[i] = P - size[r] * size[l] continue u = i acc = 0 while not visited[u]: visited[u] = True if par[u] == 0: size[0] -= size[u] u = par[u] if u == l: ans[i] = P - size[r] * size[i] l = i P = size[r] * size[l] elif u == r: ans[i] = P - size[l] * size[i] r = i P = size[r] * size[l] else: ans[i] = P P = 0 break ans[-1] = P print(*ans) for nt in range(int(input())): solve() ```
output
1
7,800
13
15,601
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2.
instruction
0
7,801
13
15,602
Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` import sys;from collections import Counter;input = sys.stdin.readline def tree_dfs(g, root=0): s = [root];d = [1] * len(g);order = [] while s:p = s.pop();d[p] = 0;order.append(p);s += [node for node in g[p] if d[node]] return order class LCA: def __init__(self,n,s,edge): self.logn=n.bit_length() self.parent=[n*[-1]for _ in range(self.logn)] self.dist=[0]*n stack=[s] visited={s} for i in stack: for j in edge[i]: if j in visited:continue stack.append(j) visited.add(j) self.parent[0][j]=i self.dist[j]=self.dist[i]+1 for k in range(1,self.logn):self.parent[k][j]=self.parent[k-1][self.parent[k-1][j]] def query(self,a,b): if self.dist[a]<self.dist[b]:a,b=b,a if self.dist[a]>self.dist[b]: for i in range(self.logn): if (self.dist[a]-self.dist[b])&(1<<i):a=self.parent[i][a] if a==b:return a for i in range(self.logn-1,-1,-1): if self.parent[i][a]!=self.parent[i][b]: a=self.parent[i][a] b=self.parent[i][b] return self.parent[0][a] def path_range(self,a,b):return self.dist[a]+self.dist[b]-2*self.dist[self.query(a,b)] def x_in_abpath(self,x,a,b):return self.path_range(a,x)+self.path_range(b,x)==self.path_range(a,b) for _ in range(int(input())): n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()); g[a].append(b); g[b].append(a) ans = [0] * (n + 1); ans[0] = n * (n - 1) // 2; order = tree_dfs(g); d = [0] * n for v in order[::-1]:d[v] += (sum([d[node] for node in g[v]]) + 1) lca = LCA(n, 0, g);a, b = 0, 0 for node in g[0]: a += d[node]; b += d[node] * d[node] if lca.query(node, 1) == node: d[0] -= d[node] ans[1] = (a * a - b) // 2 + n - 1; l, r = 0, 0 for i in range(1, n): if lca.x_in_abpath(i, l, r): ans[i + 1] = ans[i]; continue elif lca.query(i, l) == l and lca.query(i, r) == 0: l = i elif lca.query(i, r) == r and lca.query(i, l) == 0: r = i else: break ans[i + 1] = d[l] * d[r] for i in range(n):ans[i] = ans[i] - ans[i + 1] print(*ans) ```
output
1
7,801
13
15,603
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2.
instruction
0
7,802
13
15,604
Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` import sys from collections import Counter input = sys.stdin.readline def tree_dfs(g, root=0): s = [root] d = [1] * len(g) order = [] while s: p = s.pop() d[p] = 0 order.append(p) for node in g[p]: if d[node]: s.append(node) return order class LCA: def __init__(self,n,s,edge): self.logn=n.bit_length() self.parent=[n*[-1]for _ in range(self.logn)] self.dist=[0]*n stack=[s] visited={s} for i in stack: for j in edge[i]: if j in visited:continue stack.append(j) visited.add(j) self.parent[0][j]=i self.dist[j]=self.dist[i]+1 for k in range(1,self.logn):self.parent[k][j]=self.parent[k-1][self.parent[k-1][j]] def query(self,a,b): if self.dist[a]<self.dist[b]:a,b=b,a if self.dist[a]>self.dist[b]: for i in range(self.logn): if (self.dist[a]-self.dist[b])&(1<<i):a=self.parent[i][a] if a==b:return a for i in range(self.logn-1,-1,-1): if self.parent[i][a]!=self.parent[i][b]: a=self.parent[i][a] b=self.parent[i][b] return self.parent[0][a] def path_range(self,a,b):return self.dist[a]+self.dist[b]-2*self.dist[self.query(a,b)] def x_in_abpath(self,x,a,b):return self.path_range(a,x)+self.path_range(b,x)==self.path_range(a,b) t = int(input()) for _ in range(t): n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) g[a].append(b) g[b].append(a) ans = [0] * (n + 1) ans[0] = n * (n - 1) // 2 order = tree_dfs(g) d = [0] * n for v in order[::-1]: for node in g[v]: d[v] += d[node] d[v] += 1 lca = LCA(n, 0, g) a, b = 0, 0 for node in g[0]: a += d[node] b += d[node] * d[node] if lca.query(node, 1) == node: d[0] -= d[node] ans[1] = (a * a - b) // 2 + n - 1 l, r = 0, 0 for i in range(1, n): if lca.x_in_abpath(i, l, r): ans[i + 1] = ans[i] continue elif lca.query(i, l) == l and lca.query(i, r) == 0: l = i elif lca.query(i, r) == r and lca.query(i, l) == 0: r = i else: break ans[i + 1] = d[l] * d[r] for i in range(n): ans[i] = ans[i] - ans[i + 1] print(*ans) ```
output
1
7,802
13
15,605
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2.
instruction
0
7,803
13
15,606
Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num): if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n,mod=0): self.BIT = [0]*(n+1) self.num = n self.mod = mod def query(self,idx): res_sum = 0 mod = self.mod while idx > 0: res_sum += self.BIT[idx] if mod: res_sum %= mod idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): mod = self.mod while idx <= self.num: self.BIT[idx] += x if mod: self.BIT[idx] %= mod idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num self.size = n for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): if r==self.size: r = self.num res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import gcd,log input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) for _ in range(int(input())): n = int(input()) edge = [[] for i in range(n)] for _ in range(n-1): u,v = mi() edge[u].append(v) edge[v].append(u) stack = [0] cnt = [0 for i in range(n)] parent = [-1 for i in range(n)] begin = [0 for i in range(n)] end = [0 for i in range(n)] size = [1 for i in range(n)] next_id = 1 while stack: v = stack[-1] if cnt[v]==len(edge[v]): pv = parent[v] if pv!=-1: size[pv] += size[v] end[v] = next_id next_id += 1 stack.pop() else: nv = edge[v][cnt[v]] cnt[v] += 1 if nv==parent[v]: continue parent[nv] = v stack.append(nv) begin[nv] = next_id next_id += 1 def is_child(u,v): return begin[u] <= begin[v] and end[v] <= end[u] res = [0 for i in range(n+1)] res[0] = n*(n-1)//2 res[1] = n*(n-1)//2 a = 1 pa = -1 b = -1 pb = -1 for v in edge[0]: res[1] -= size[v] * (size[v]-1)//2 if is_child(v,1): res[2] = size[1] * (n - size[v]) pa = v for i in range(2,n): if is_child(a,i): a = i elif is_child(i,a): pass elif b==-1: for v in edge[0]: if is_child(v,i): pb = v break if pa==pb: break else: b = i elif is_child(b,i): b = i elif is_child(i,b): pass else: break if b==-1: res[i+1] = size[a] * (n-size[pa]) else: res[i+1] = size[a] * size[b] for i in range(n): res[i] -= res[i+1] print(*res) ```
output
1
7,803
13
15,607
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2.
instruction
0
7,804
13
15,608
Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` import sys from sys import stdin from collections import deque def NC_Dij(lis,start): N = len(lis) ret = [float("inf")] * len(lis) ret[start] = 0 chnum = [1] * N q = deque([start]) plis = [i for i in range(len(lis))] while len(q) > 0: now = q.popleft() for nex in lis[now]: if ret[nex] > ret[now] + 1: ret[nex] = ret[now] + 1 plis[nex] = now q.append(nex) td = [(ret[i],i) for i in range(N)] td.sort() td.reverse() for tmp,i in td: if plis[i] != i: chnum[ plis[i] ] += chnum[i] return ret,plis,chnum tt = int(stdin.readline()) for loop in range(tt): n = int(stdin.readline()) lis = [ [] for i in range(n) ] for i in range(n-1): u,v = map(int,stdin.readline().split()) lis[u].append(v) lis[v].append(u) dlis,plis,chnum = NC_Dij(lis,0) ans = [0] * (n+1) ans[0] = n * (n-1)//2 in_flag = [False] * n in_flag[0] = True l,r = 0,0 llast = None #parent is 0 and l is child flag = True for v in range(n): nv = v if in_flag[nv] == False: while True: if in_flag[nv] == True: if nv == l: l = v elif nv == r: r = v else: flag = False break in_flag[nv] = True nv = plis[nv] if not flag: break if l == 0 and r == 0: nans = n * (n-1)//2 for nex in lis[0]: nans -= chnum[nex] * (chnum[nex]-1)//2 elif r == 0: if llast == None: tv = l while plis[tv] != 0: tv = plis[tv] llast = tv nans = chnum[l] * (n-chnum[llast]) else: nans = chnum[l] * chnum[r] ans[v+1] = nans for i in range(n): ans[i] -= ans[i+1] #print (chnum) print (*ans) ```
output
1
7,804
13
15,609
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2.
instruction
0
7,805
13
15,610
Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` import sys def putin(): return map(int, sys.stdin.readline().split()) def sol(): n = int(sys.stdin.readline()) G = [] for i in range(n): G.append([]) for i in range(n - 1): u, v = putin() G[u].append(v) G[v].append(u) parents = [0] * n parents[0] = -1 capacity = [0] * n DFS_stack = [0] colors = [0] * n while DFS_stack: new_v = DFS_stack[-1] if colors[new_v] == 0: colors[new_v] = 1 for elem in G[new_v]: if colors[elem] == 0: DFS_stack.append(elem) parents[elem] = new_v elif colors[new_v] == 1: colors[new_v] = 2 DFS_stack.pop() S = 0 for elem in G[new_v]: if colors[elem] == 2: S += capacity[elem] capacity[new_v] = S + 1 else: DFS_stack.pop() L = 0 R = 0 answer = [n * (n - 1) // 2] S = 0 for children in G[0]: S += capacity[children] * (capacity[children] - 1) // 2 answer.append(n * (n - 1) // 2 - S) cur_v = 0 path = {0} while len(answer) < n + 1: cur_v += 1 ancestor = cur_v while ancestor not in path: path.add(ancestor) if parents[ancestor] == 0: capacity[0] -= capacity[ancestor] ancestor = parents[ancestor] if ancestor != cur_v: if ancestor != L and ancestor != R: break if ancestor == L: L = cur_v else: R = cur_v answer.append((capacity[L]) * (capacity[R])) while len(answer) < n + 2: answer.append(0) for i in range(n + 1): print(answer[i] - answer[i + 1], end=' ') print() for iter in range(int(sys.stdin.readline())): sol() ```
output
1
7,805
13
15,611
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2.
instruction
0
7,806
13
15,612
Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` import sys from collections import Counter input = sys.stdin.readline def tree_dfs(g, root=0): s = [root] d = [1] * len(g) order = [] while s: p = s.pop() d[p] = 0 order.append(p) for node in g[p]: if d[node]: s.append(node) return order class LCA: def __init__(self,n,s,edge): self.logn=n.bit_length() self.parent=[n*[-1]for _ in range(self.logn)] self.dist=[0]*n stack=[s] visited={s} for i in stack: for j in edge[i]: if j in visited:continue stack.append(j) visited.add(j) self.parent[0][j]=i self.dist[j]=self.dist[i]+1 for k in range(1,self.logn):self.parent[k][j]=self.parent[k-1][self.parent[k-1][j]] def query(self,a,b): if self.dist[a]<self.dist[b]:a,b=b,a if self.dist[a]>self.dist[b]: for i in range(self.logn): if (self.dist[a]-self.dist[b])&(1<<i):a=self.parent[i][a] if a==b:return a for i in range(self.logn-1,-1,-1): if self.parent[i][a]!=self.parent[i][b]: a=self.parent[i][a] b=self.parent[i][b] return self.parent[0][a] def path_range(self,a,b):return self.dist[a]+self.dist[b]-2*self.dist[self.query(a,b)] def x_in_abpath(self,x,a,b):return self.path_range(a,x)+self.path_range(b,x)==self.path_range(a,b) for _ in range(int(input())): n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) g[a].append(b) g[b].append(a) ans = [0] * (n + 1) ans[0] = n * (n - 1) // 2 order = tree_dfs(g) d = [0] * n for v in order[::-1]: for node in g[v]: d[v] += d[node] d[v] += 1 lca = LCA(n, 0, g) a, b = 0, 0 for node in g[0]: a += d[node] b += d[node] * d[node] if lca.query(node, 1) == node: d[0] -= d[node] ans[1] = (a * a - b) // 2 + n - 1 l, r = 0, 0 for i in range(1, n): if lca.x_in_abpath(i, l, r): ans[i + 1] = ans[i] continue elif lca.query(i, l) == l and lca.query(i, r) == 0: l = i elif lca.query(i, r) == r and lca.query(i, l) == 0: r = i else: break ans[i + 1] = d[l] * d[r] for i in range(n): ans[i] = ans[i] - ans[i + 1] print(*ans) ```
output
1
7,806
13
15,613
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2.
instruction
0
7,807
13
15,614
Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` #CF1527D from bisect import bisect,bisect_left from collections import * from heapq import * from math import gcd,ceil,sqrt,floor,inf from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def A(n):return [0]*n def AI(n,x): return [x]*n def A2(n,m): return [[0]*m for i in range(n)] def G(n): return [[] for i in range(n)] def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)] #------------------------------------------------------------------------ from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc mod=10**9+7 farr=[1] ifa=[] def fact(x,mod=0): if mod: while x>=len(farr): farr.append(farr[-1]*len(farr)%mod) else: while x>=len(farr): farr.append(farr[-1]*len(farr)) return farr[x] def ifact(x,mod): global ifa fact(x,mod) ifa.append(pow(farr[-1],mod-2,mod)) for i in range(x,0,-1): ifa.append(ifa[-1]*i%mod) ifa.reverse() def per(i,j,mod=0): if i<j: return 0 if not mod: return fact(i)//fact(i-j) return farr[i]*ifa[i-j]%mod def com(i,j,mod=0): if i<j: return 0 if not mod: return per(i,j)//fact(j) return per(i,j,mod)*ifa[j]%mod def catalan(n): return com(2*n,n)//(n+1) def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1)) if a==0:return b//c*(n+1) if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2 m=(a*n+b)//c return n*m-floorsum(c,c-b-1,a,m-1) def inverse(a,m): a%=m if a<=1: return a return ((1-inverse(m,a)*m)//a)%m def lowbit(n): return n&-n class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans class ST: def __init__(self,arr):#n!=0 n=len(arr) mx=n.bit_length()#取不到 self.st=[[0]*mx for i in range(n)] for i in range(n): self.st[i][0]=arr[i] for j in range(1,mx): for i in range(n-(1<<j)+1): self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1]) def query(self,l,r): if l>r:return -inf s=(r+1-l).bit_length()-1 return max(self.st[l][s],self.st[r-(1<<s)+1][s]) class DSU:#容量+路径压缩 def __init__(self,n): self.c=[-1]*n def same(self,x,y): return self.find(x)==self.find(y) def find(self,x): if self.c[x]<0: return x self.c[x]=self.find(self.c[x]) return self.c[x] def union(self,u,v): u,v=self.find(u),self.find(v) if u==v: return False if self.c[u]>self.c[v]: u,v=v,u self.c[u]+=self.c[v] self.c[v]=u return True def size(self,x): return -self.c[self.find(x)] class UFS:#秩+路径 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv class UF:#秩+路径+容量,边数 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n self.size=AI(n,1) self.edge=A(n) def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: self.edge[pu]+=1 return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu self.edge[pu]+=self.edge[pv]+1 self.size[pu]+=self.size[pv] if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv self.edge[pv]+=self.edge[pu]+1 self.size[pv]+=self.size[pu] def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return prime def dij(s,graph): d=AI(n,inf) d[s]=0 heap=[(0,s)] vis=A(n) while heap: dis,u=heappop(heap) if vis[u]: continue vis[u]=1 for v,w in graph[u]: if d[v]>d[u]+w: d[v]=d[u]+w heappush(heap,(d[v],v)) return d def bell(s,g):#bellman-Ford dis=AI(n,inf) dis[s]=0 for i in range(n-1): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change=A(n) for i in range(n): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change[v]=1 return dis def lcm(a,b): return a*b//gcd(a,b) def lis(nums): res=[] for k in nums: i=bisect.bisect_left(res,k) if i==len(res): res.append(k) else: res[i]=k return len(res) def RP(nums):#逆序对 n = len(nums) s=set(nums) d={} for i,k in enumerate(sorted(s),1): d[k]=i bi=BIT([0]*(len(s)+1)) ans=0 for i in range(n-1,-1,-1): ans+=bi.query(d[nums[i]]-1) bi.update(d[nums[i]],1) return ans class DLN: def __init__(self,val): self.val=val self.pre=None self.next=None def nb(i,j,n,m): for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]: if 0<=ni<n and 0<=nj<m: yield ni,nj def topo(n): q=deque() res=[] for i in range(1,n+1): if ind[i]==0: q.append(i) res.append(i) while q: u=q.popleft() for v in g[u]: ind[v]-=1 if ind[v]==0: q.append(v) res.append(v) return res @bootstrap def gdfs(r,p): for ch in g[r]: if ch!=p: yield gdfs(ch,r) yield None @bootstrap def dfs(r,p): par[r]=p for ch in g[r]: if ch!=p: yield dfs(ch,r) cnt[r]+=cnt[ch] yield None #from random import randint t=N() for i in range(t): n=N() g=G(n) ans=A(n+1) for i in range(n-1): u,v=RL() g[u].append(v) g[v].append(u) par=A(n) cnt=AI(n,1) dfs(0,-1) vis=A(n) vis[0]=1 for v in g[0]: ans[0]+=cnt[v]*(cnt[v]-1)//2 u=1 while par[u]: vis[u]=1 u=par[u] vis[u]=1 k=n-cnt[1] ans[1]=n*(n-1)//2-ans[0]-cnt[1]*(n-cnt[u]) l=0 lc=n-cnt[u] rc=cnt[1] r=1 f=True for i in range(2,n): if vis[i]: continue u=i while not vis[u]: vis[u]=1 u=par[u] if u==l: ans[i]=(lc-cnt[i])*rc l=i lc=cnt[l] elif u==r: ans[i]=(rc-cnt[i])*lc r=i rc=cnt[r] else: ans[i]=lc*rc f=False break if f: ans[-1]=1 print(*ans) ```
output
1
7,807
13
15,615
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` import sys def putin(): return map(int, sys.stdin.readline().split()) def sol(): n = int(sys.stdin.readline()) G = [] for i in range(n): G.append([]) for i in range(n - 1): u, v = putin() G[u].append(v) G[v].append(u) parents = [0] * n parents[0] = -1 capacity = [0] * n DFS_stack = [0] colors = [0] * n while DFS_stack: new_v = DFS_stack[-1] if colors[new_v] == 0: colors[new_v] = 1 for elem in G[new_v]: if colors[elem] == 0: DFS_stack.append(elem) parents[elem] = new_v elif colors[new_v] == 1: colors[new_v] = 2 DFS_stack.pop() S = 0 for elem in G[new_v]: if colors[elem] == 2: S += capacity[elem] capacity[new_v] = S + 1 else: DFS_stack.pop() L = 0 R = 0 answer = [n * (n - 1) // 2] S = 0 for children in G[0]: S += capacity[children] * (capacity[children] - 1) // 2 answer.append(n * (n - 1) // 2 - S) path = {0} for cur_v in range(1, n): if cur_v not in path: ancestor = cur_v while ancestor not in path: path.add(ancestor) if parents[ancestor] == 0: capacity[0] -= capacity[ancestor] ancestor = parents[ancestor] if ancestor == L: L = cur_v elif ancestor == R: R = cur_v else: break answer.append((capacity[L]) * (capacity[R])) while len(answer) < n + 2: answer.append(0) for i in range(n + 1): print(answer[i] - answer[i + 1], end=' ') print() for iter in range(int(sys.stdin.readline())): sol() ```
instruction
0
7,808
13
15,616
Yes
output
1
7,808
13
15,617
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` import sys;from collections import Counter;input = sys.stdin.readline def tree_dfs(g, root=0): s = [root];d = [1] * len(g);order = [] while s:p = s.pop();d[p] = 0;order.append(p);s += [node for node in g[p] if d[node]] return order class LCA: def __init__(self,n,s,edge): self.logn=n.bit_length();self.parent=[n*[-1]for _ in range(self.logn)];self.dist=[0]*n;stack=[s];visited={s} for i in stack: for j in edge[i]: if j in visited:continue stack.append(j); visited.add(j); self.parent[0][j]=i; self.dist[j]=self.dist[i]+1 for k in range(1,self.logn):self.parent[k][j]=self.parent[k-1][self.parent[k-1][j]] def query(self,a,b): if self.dist[a]<self.dist[b]:a,b=b,a if self.dist[a]>self.dist[b]: for i in range(self.logn): if (self.dist[a]-self.dist[b])&(1<<i):a=self.parent[i][a] if a==b:return a for i in range(self.logn-1,-1,-1): if self.parent[i][a]!=self.parent[i][b]: a=self.parent[i][a]; b=self.parent[i][b] return self.parent[0][a] def path_range(self,a,b):return self.dist[a]+self.dist[b]-2*self.dist[self.query(a,b)] def x_in_abpath(self,x,a,b):return self.path_range(a,x)+self.path_range(b,x)==self.path_range(a,b) for _ in range(int(input())): n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()); g[a].append(b); g[b].append(a) ans = [0] * (n + 1); ans[0] = n * (n - 1) // 2; order = tree_dfs(g); d = [0] * n for v in order[::-1]:d[v] += (sum([d[node] for node in g[v]]) + 1) lca = LCA(n, 0, g);a, b = 0, 0 for node in g[0]: a += d[node]; b += d[node] * d[node] if lca.query(node, 1) == node: d[0] -= d[node] ans[1] = (a * a - b) // 2 + n - 1; l, r = 0, 0 for i in range(1, n): if lca.x_in_abpath(i, l, r): ans[i + 1] = ans[i]; continue elif lca.query(i, l) == l and lca.query(i, r) == 0: l = i elif lca.query(i, r) == r and lca.query(i, l) == 0: r = i else: break ans[i + 1] = d[l] * d[r] for i in range(n):ans[i] = ans[i] - ans[i + 1] print(*ans) ```
instruction
0
7,809
13
15,618
Yes
output
1
7,809
13
15,619
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` import math from bisect import bisect_left import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") sys.setrecursionlimit(2*10**5) def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def solve(): n = int(input()) MA = n + 1 level = 25 tree = [[] for i in range(MA)] depth = [0 for i in range(MA)] parent = [[0 for i in range(level)] for j in range(MA)] size = [1 for i in range(MA)] ans= [0 for i in range(MA)] @bootstrap def dfs(cur, prev): depth[cur] = depth[prev] + 1 parent[cur][0] = prev for i in range(len(tree[cur])): if (tree[cur][i] != prev): yield dfs(tree[cur][i], cur) size[cur]+=size[tree[cur][i]] yield def precomputeSparseMatrix(n): for i in range(1, level): for node in range(n): if (parent[node][i - 1] != -1): parent[node][i] = parent[parent[node][i - 1]][i - 1] def lca(u, v): if (depth[v] < depth[u]): u, v = v, u diff = depth[v] - depth[u] for i in range(level): if ((diff >> i) & 1): v = parent[v][i] if (u == v): return u i = level - 1 while (i >= 0): if (parent[u][i] != parent[v][i]): u = parent[u][i] v = parent[v][i] i += -1 return parent[u][0] def add(a, b): tree[a].append(b) tree[b].append(a) for j in range(n-1): u,v=map(int,input().split()) add(u,v) dfs(0, -1) precomputeSparseMatrix(n) s1=0 for j in tree[0]: ans[0]+=(size[j]*(size[j]-1))//2 if lca(j,1)==j: s1=n-size[j] rem=n*(n-1)//2-ans[0] ans[1]=rem-s1*size[1] rem=s1*size[1] size[0]=s1 u=1 v=0 for i in range(2,n): if v==0: val1=1 p1=lca(u,i) p2=lca(v,i) if p1==u: u=i elif p1==i: pass elif p1==0: if lca(v,i)==v: v=i else: val1=0 if val1!=0: val1=size[u]*size[v] ans[i]=rem-val1 rem=val1 else: p1=lca(u,i) p2=lca(v,i) if p1==u: u=i val1 = size[u] * size[v] elif p2==v: v=i val1 = size[u] * size[v] elif p1==i: val1=size[u]*size[v] elif p2==i: val1 = size[u] * size[v] else: val1=0 ans[i]=rem-val1 rem=val1 if rem==0: break ans[-1]=rem print(*ans) t=int(input()) for _ in range(t): solve() ```
instruction
0
7,810
13
15,620
Yes
output
1
7,810
13
15,621
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` class RangeQuery: def __init__(self, data, func=min): self.func = func self._data = _data = [list(data)] i, n = 1, len(_data[0]) while 2 * i <= n: prev = _data[-1] _data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)]) i <<= 1 def query(self, begin, end): depth = (end - begin).bit_length() - 1 return self.func(self._data[depth][begin], self._data[depth][end - (1 << depth)]) class LCA: def __init__(self, root, graph): self.time = [-1] * len(graph) self.path = [-1] * len(graph) P = [-1] * len(graph) t = -1 dfs = [root] while dfs: node = dfs.pop() self.path[t] = P[node] self.time[node] = t = t + 1 for nei in graph[node]: if self.time[nei] == -1: P[nei] = node dfs.append(nei) self.rmq = RangeQuery(self.time[node] for node in self.path) def __call__(self, a, b): if a == b: return a a = self.time[a] b = self.time[b] if a > b: a, b = b, a return self.path[self.rmq.query(a, b)] import sys,io,os try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline except:Z=lambda:sys.stdin.readline().encode() Y=lambda:map(int,Z().split()) O=[] for _ in range(int(Z())): n=int(Z());g=[[]for i in range(n)] for i in range(n-1):u,v=Y();g[u].append(v);g[v].append(u) L=LCA(0,g);e=[1,0];r=[0]*(n+1) c=[-1]*n;d=[0]*n;p=[-1]*n;q=[0] while q: v=q.pop() if c[v]==-1: c[v]=0 for i in g[v]: if i!=p[v]:p[i]=v;q.append(i);c[v]+=1 if c[v]==0: d[v]+=1 if p[v]!=-1: d[p[v]]+=d[v];c[p[v]]-=1 if c[p[v]]==0:q.append(p[v]) u,w=p[1],1 while u:u,w=p[u],u d[0]-=d[w];t=0 for i in g[0]: v=d[i];r[0]+=(v*v-v)//2 if i==w:v-=d[1] r[1]+=t*v+v;t+=v for i in range(2,n): v=L(i,e[0]) if v==i:continue elif v==e[0]:r[i]=d[e[1]]*(d[v]-d[i]);e[0]=i;continue elif v!=0:r[i]=d[e[0]]*d[e[1]];break v=L(i,e[1]) if v==i:continue elif v==e[1]:r[i]=d[e[0]]*(d[v]-d[i]);e[1]=i;continue r[i]=d[e[0]]*d[e[1]];break else:r[-1]=1 O.append(' '.join(map(str,r))) print('\n'.join(O)) ```
instruction
0
7,811
13
15,622
Yes
output
1
7,811
13
15,623
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` from sys import stdin, gettrace if gettrace(): def inputi(): return input() else: def input(): return next(stdin)[:-1] def inputi(): return stdin.buffer.readline() def readGraph(n, m): adj = [[] for _ in range(n)] for _ in range(m): u, v = map(int, input().split()) adj[u].append(v) adj[v].append(u) return adj def readTree(n): return readGraph(n, n - 1) def euler_dfs(n, adj): parent = [None] * n depth = [-1] * n depth[0] = 0 stack = [(0, adj[0])] euler = [] eulerfirst = [-1] * n eulerlast = [-1] * n dcount = [0] * n pcount = [0] * n seen = 0 while stack: p, aa = stack.pop() if eulerfirst[p] == -1: pcount[p] = seen seen += 1 eulerfirst[p] = len(euler) eulerlast[p] = len(euler) dcount[p] = seen - pcount[p] euler.append(p) for c in aa[::-1]: if c != parent[p]: parent[c] = p depth[c] = depth[p] + 1 stack.append((p, [])) stack.append((c, adj[c])) return eulerfirst, eulerlast, parent, dcount def solve(): n = int(input()) adj = readTree(n) eulerfirst, eulerlast, parent, dcount = euler_dfs(n, adj) def is_decendant(u, v): return eulerfirst[v] < eulerfirst[u] < eulerlast[v] res = [0] * (n + 1) paths = [0] * n res[0] = sum(dcount[v] * (dcount[v] - 1) for v in adj[0]) // 2 paths[0] = (n * (n - 1)) // 2 - res[0] oneb = 1 while oneb not in adj[0]: oneb = parent[oneb] paths[1] = dcount[1] * (n - dcount[oneb]) pends = [1] for i in range(2, n): for x, e in enumerate(pends): if is_decendant(e, i): break elif is_decendant(i, e): pends[x] = i break else: if len(pends) == 2: break p = parent[i] j = 0 while p != 0: if p < i: j = p break p = parent[p] if j != 0: break pends.append(i) if len(pends) == 2: paths[i] = dcount[pends[0]] * dcount[pends[1]] else: paths[i] = dcount[pends[0]] * (n - dcount[oneb]) for i in range(1, n): res[i] = paths[i - 1] - paths[i] res[n] = paths[n - 1] print(' '.join(map(str, res))) def main(): t = int(input()) for _ in range(t): solve() if __name__ == "__main__": main() ```
instruction
0
7,812
13
15,624
No
output
1
7,812
13
15,625
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` from collections import deque import sys input = sys.stdin.readline def bfs(s): q = deque() q.append(s) visit = [0] * n visit[s] = 1 p = deque() parent = [-1] * n while q: i = q.popleft() p.append(i) for j in G[i]: if not visit[j]: visit[j] = 1 q.append(j) parent[j] = i childcnt = [1] * n p.popleft() while p: i = p.pop() childcnt[parent[i]] += childcnt[i] return parent, childcnt t = int(input()) for _ in range(t): n = int(input()) G = [[] for _ in range(n)] for _ in range(n - 1): u, v = map(int, input().split()) G[u].append(v) G[v].append(u) parent, childcnt = bfs(0) x = n * (n - 1) // 2 c = 0 for i in G[0]: cc = childcnt[i] c += cc * (cc - 1) // 2 ans = [c] x -= c i, j = 1, 1 ok = set() ok.add(0) while not i in ok: ok.add(i) j = i i = parent[i] c = [] for i in G[0]: cc = childcnt[i] if i == j: cc -= childcnt[1] c.append(cc) childcnt[0] -= childcnt[j] c0 = [] y = 0 for i in range(len(c)): y += c[i] c0.append(y) cc = 0 for i in range(len(c) - 1): cc += c0[i] * c[i + 1] cc += c0[-1] x -= cc ans.append(cc) lr = set([0, 1]) ng = 0 for i in range(2, n): if ng: ans.append(0) continue if i in ok: continue j = i while not j in ok: ok.add(j) j = parent[j] if j in lr: childcnt[j] -= childcnt[i] c = 1 for k in lr: c *= childcnt[k] ans.append(c) x -= c lr.remove(j) lr.add(i) else: childcnt[j] -= childcnt[i] c = 1 for k in lr: c *= childcnt[k] ans.append(c) x -= c ng = 1 continue while not len(ans) == n: ans.append(0) x = 1 for i in G: if len(i) > 2: x = 0 break ans.append(x) print(*ans) ```
instruction
0
7,813
13
15,626
No
output
1
7,813
13
15,627
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` import sys input = sys.stdin.readline def solve(): n = int(input()) G = [[] for _ in range(n)] for _ in range(n-1): a,b = map(int,input().split()) G[a].append(b) G[b].append(a) size = [0]*n par = [-1]*n stk = [0] visited = [False]*n while stk: x = stk[-1] if not visited[x]: visited[x] = True for y in G[x]: if not visited[y]: par[y] = x stk.append(y) else: stk.pop() for y in G[x]: size[x] += size[y] size[x] += 1 visited = [False]*n ans = [0]*(n+1) for y in G[0]: ans[0] += size[y] * (size[y]-1) // 2 P = n*(n-1)//2 P -= ans[0] visited[0] = True l,r = 0,0 for i in range(1,n): u = i while not visited[u]: visited[u] = True size[par[u]] -= size[u] u = par[u] if n == 200000: print("is 1 a child of 0?",1 in G[0]) print("size[0]",size[0],"size[1]",size[1],"P",P) if u == l: ans[i] = P - size[r] * size[i] l = i P -= ans[i] elif u == r: ans[i] = P - size[l] * size[i] r = i P -= ans[i] else: ans[i] = size[l] * size[r] P -= ans[i] break ans[-1] = P print(*ans) for nt in range(int(input())): solve() ```
instruction
0
7,814
13
15,628
No
output
1
7,814
13
15,629
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` import sys from collections import Counter input = sys.stdin.readline def tree_dfs(g, root=0): s = [root] d = [1] * len(g) order = [] while s: p = s.pop() d[p] = 0 order.append(p) for node in g[p]: if d[node]: s.append(node) return order class LCA: def __init__(self,n,s,edge): self.logn=n.bit_length() self.parent=[n*[-1]for _ in range(self.logn)] self.dist=[0]*n stack=[s] visited={s} for i in stack: for j in edge[i]: if j in visited:continue stack.append(j) visited.add(j) self.parent[0][j]=i self.dist[j]=self.dist[i]+1 for k in range(1,self.logn):self.parent[k][j]=self.parent[k-1][self.parent[k-1][j]] def query(self,a,b): if self.dist[a]<self.dist[b]:a,b=b,a if self.dist[a]>self.dist[b]: for i in range(self.logn): if (self.dist[a]-self.dist[b])&(1<<i):a=self.parent[i][a] if a==b:return a for i in range(self.logn-1,-1,-1): if self.parent[i][a]!=self.parent[i][b]: a=self.parent[i][a] b=self.parent[i][b] return self.parent[0][a] def path_range(self,a,b):return self.dist[a]+self.dist[b]-2*self.dist[self.query(a,b)] def x_in_abpath(self,x,a,b):return self.path_range(a,x)+self.path_range(b,x)==self.path_range(a,b) t = int(input()) for _ in range(t): n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) g[a].append(b) g[b].append(a) ans = [0] * (n + 1) ans[0] = n * (n - 1) // 2 order = tree_dfs(g) d = [0] * n for v in order[::-1]: for node in g[v]: d[v] += d[node] d[v] += 1 lca = LCA(n, 0, g) a, b = 0, 0 for node in g[0]: a += d[node] b += d[node] * d[node] if lca.query(node, 1) == node: d[0] -= d[node] ans[1] = (a * a - b) // 2 + n - 1 l, r = 0, 0 for i in range(1, n): if lca.x_in_abpath(i, l, r): ans[i + 1] = ans[i] continue elif lca.query(i, l) == l: l = i elif lca.query(i, r) == r: r = i else: break ans[i + 1] = d[l] * d[r] for i in range(n): ans[i] = ans[i] - ans[i + 1] print(*ans) ```
instruction
0
7,815
13
15,630
No
output
1
7,815
13
15,631
Provide tags and a correct Python 3 solution for this coding contest problem. You're given a tree with n vertices. Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size. Input The first line contains an integer n (1 ≤ n ≤ 10^5) denoting the size of the tree. The next n - 1 lines contain two integers u, v (1 ≤ u, v ≤ n) each, describing the vertices connected by the i-th edge. It's guaranteed that the given edges form a tree. Output Output a single integer k — the maximum number of edges that can be removed to leave all connected components with even size, or -1 if it is impossible to remove edges in order to satisfy this property. Examples Input 4 2 4 4 1 3 1 Output 1 Input 3 1 2 1 3 Output -1 Input 10 7 1 8 4 8 10 4 7 6 5 9 3 3 5 2 10 2 5 Output 4 Input 2 1 2 Output 0 Note In the first example you can remove the edge between vertices 1 and 4. The graph after that will have two connected components with two vertices in each. In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is -1.
instruction
0
8,152
13
16,304
Tags: dfs and similar, dp, graphs, greedy, trees Correct Solution: ``` from sys import stdin inp = stdin.readline n, ans = int(inp()), 0 if n & 1: print(-1) exit() g = {i: [set(), 0] for i in range(1, n + 1)} visited = [0] * (n + 1) for _ in range(n - 1): a, b = map(int, inp().split()) g[a][0].add(b) g[b][0].add(a) visited = [0, 1] + [0] * (n - 1) q = [1] p = [0] * (n + 1) while q: v = q.pop() if v != 1 and len(g[v][0]) == 1: g[p[v]][0].remove(v) g[p[v]][1] += g[v][1] + 1 q.append(p[v]) if g[v][1] & 1: ans += 1 continue for i in g[v][0]: if not visited[i]: visited[i] = True p[i] = v q.append(i) if min(g[v][1], g[i][1]) & 1: ans += 1 print(ans) ```
output
1
8,152
13
16,305
Provide tags and a correct Python 3 solution for this coding contest problem. You're given a tree with n vertices. Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size. Input The first line contains an integer n (1 ≤ n ≤ 10^5) denoting the size of the tree. The next n - 1 lines contain two integers u, v (1 ≤ u, v ≤ n) each, describing the vertices connected by the i-th edge. It's guaranteed that the given edges form a tree. Output Output a single integer k — the maximum number of edges that can be removed to leave all connected components with even size, or -1 if it is impossible to remove edges in order to satisfy this property. Examples Input 4 2 4 4 1 3 1 Output 1 Input 3 1 2 1 3 Output -1 Input 10 7 1 8 4 8 10 4 7 6 5 9 3 3 5 2 10 2 5 Output 4 Input 2 1 2 Output 0 Note In the first example you can remove the edge between vertices 1 and 4. The graph after that will have two connected components with two vertices in each. In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is -1.
instruction
0
8,153
13
16,306
Tags: dfs and similar, dp, graphs, greedy, trees Correct Solution: ``` from sys import stdin input=lambda : stdin.readline().strip() from math import ceil,sqrt,factorial,gcd from collections import deque n=int(input()) d={i:set() for i in range(1,n+1)} for i in range(n-1): a,b=map(int,input().split()) d[a].add(b) d[b].add(a) stack=deque() stack.append([1,0]) ans=[[0,0]for i in range(n+1)] l=[] while stack: x=stack.pop() # print(x) try: l[x[1]].append(x[0]) except: l.append([x[0]]) for i in d[x[0]]: ans[i][0]=x[0] d[i].remove(x[0]) stack.appendleft([i,x[1]+1]) count=0 if n%2!=0: print(-1) exit() while l: stack=[i for i in l.pop()] while stack: x=stack.pop() if ans[x][1]>0 and (ans[x][1]+1)%2==0: count+=1 else: ans[ans[x][0]][1]+=ans[x][1]+1 # print(ans[1:]) print(count-1) ```
output
1
8,153
13
16,307