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
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes. * Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i. Constraints * N is an integer. * 1 \leq N \leq 10^{5} Input Input is given from Standard Input in the following format: N Output If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format: a_{1} b_{1} \vdots a_{2N-1} b_{2N-1} Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order. Examples Input 3 Output Yes 1 2 2 3 3 4 4 5 5 6 Input 1 Output No Submitted Solution: ``` N=int(input()) if (N&-N)==N: print('No') exit() print('Yes') P=[[] for i in range(2*N)] X=1 while 2*X-1<=N: X*=2 X-=1 for i in range(X-1): P[i].append(i+1) P[N+i].append(N+i+1) P[X-1].append(N) while X+2<=N: P[X].append(X+1) P[0].append(X+1) P[0].append(X+N) P[X+N].append(X+N+1) X+=2 if X!=N: X=N&(-N) P[X-1].append(N-1) if X==2: P[N-X].append(2*N-1) else: P[2*N-X-1].append(2*N-1) for i in range(len(P)): for j in range(len(P[i])): print(i+1,P[i][j]+1) ```
instruction
0
79,744
13
159,488
Yes
output
1
79,744
13
159,489
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes. * Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i. Constraints * N is an integer. * 1 \leq N \leq 10^{5} Input Input is given from Standard Input in the following format: N Output If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format: a_{1} b_{1} \vdots a_{2N-1} b_{2N-1} Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order. Examples Input 3 Output Yes 1 2 2 3 3 4 4 5 5 6 Input 1 Output No Submitted Solution: ``` from bisect import bisect_left, bisect_right; from collections import Counter, defaultdict, deque, OrderedDict; from copy import deepcopy; from fractions import gcd; from functools import lru_cache, reduce; from math import ceil, floor; from sys import stdin, setrecursionlimit import heapq as hq; import itertools as its; import operator as op # globals inf = float('inf') input = stdin.readline def main(): n = get_int() m = n.bit_length() if 2 ** (m - 1) == n: print('No') return print('Yes') if m == 2: # no node between 1 and N + 1 for i in range(1, 6): print(i, i + 1) return for i in range(1, 2 ** (m - 1) - 1): print(i, i + 1) print(n + i, n + i + 1) print(2 ** (m - 1) - 1, n + 1) x, y = 1, 1 if n % 2 == 0: x, y = 2, 3 for i in range(2 ** (m - 1), n, 2): print(x, i) print(i, i + 1) print(y, n + i + 1) print(n + i + 1, n + i) if n % 2 == 0: print(x, n) print(2 ** (m - 1), 2 * n) return def get_int(): return int(input()) def get_float(): return float(input()) def get_str(): return input().strip() def get_li(): return [int(i) for i in input().split()] def get_lf(): return [float(f) for f in input().split()] def get_lc(): return list(input().strip()) def gets(n, types, sep=None): if len(types) == 1: return [types[0](input().strip()) for _ in range(n)] return list(zip(*( [t(x) for t, x in zip(types, input().strip().split(sep=sep))] for _ in range(n) ))) if __name__ == '__main__': setrecursionlimit(4100000) main() ```
instruction
0
79,745
13
159,490
No
output
1
79,745
13
159,491
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes. * Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i. Constraints * N is an integer. * 1 \leq N \leq 10^{5} Input Input is given from Standard Input in the following format: N Output If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format: a_{1} b_{1} \vdots a_{2N-1} b_{2N-1} Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order. Examples Input 3 Output Yes 1 2 2 3 3 4 4 5 5 6 Input 1 Output No Submitted Solution: ``` pow2 = [2**i - 1 for i in range(20)] N = int(input()) rest = 0 if N == 1: print("No") exit() for i in range(1,20): if pow2[i] < N: continue if pow2[i] == N: print("Yes") break rest = N - (pow2[i-1] + 1) if rest in pow2: print("Yes") break print("No") exit() base = N - rest - 1 base_list = [x+1 if x < base else N+(x%base)+1 for x in range(2*base)] for i in range(len(base_list)-1): print(base_list[i], base_list[i+1]) if rest > 0: start = base + 1 end = N for i in range(start, end+1): if i < end: print(i, i+1) else: print(i, rest) for i in range(start, end+1): if i > start: print(N+i, N+i+1) else: print(rest, N+i) ```
instruction
0
79,746
13
159,492
No
output
1
79,746
13
159,493
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes. * Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i. Constraints * N is an integer. * 1 \leq N \leq 10^{5} Input Input is given from Standard Input in the following format: N Output If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format: a_{1} b_{1} \vdots a_{2N-1} b_{2N-1} Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order. Examples Input 3 Output Yes 1 2 2 3 3 4 4 5 5 6 Input 1 Output No Submitted Solution: ``` n = int(input()) if n != 1 and 2 ** 17 - 1 & n == n: print('Yes') for i in range(1,2 * n): print(str(i) + ' ' + str(i + 1)) else: print('No') ```
instruction
0
79,747
13
159,494
No
output
1
79,747
13
159,495
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes. * Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i. Constraints * N is an integer. * 1 \leq N \leq 10^{5} Input Input is given from Standard Input in the following format: N Output If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format: a_{1} b_{1} \vdots a_{2N-1} b_{2N-1} Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order. Examples Input 3 Output Yes 1 2 2 3 3 4 4 5 5 6 Input 1 Output No Submitted Solution: ``` def main(): import sys input = sys.stdin.readline N = int(input()) k = N.bit_length() if 1<<(k-1) == N: print('No') exit() print('Yes') if N == 3: for i in range(1, 6): print(i, i+1) exit() N0 = 1<<(k-1) e = [(N0-1, N+1)] for i in range(1, N0-1): e.append((i, i+1)) e.append((i+N, i+1+N)) for i in range(N0, N+1): if i%2 == 0: e.append((i, 2)) e.append((i+N, i+1+N)) else: e.append((i, i-1)) e.append((i+N, 3+N)) if N % 2 == 0: e.pop() e.append((N+N, 2+N)) for edge in e: print(*edge) if __name__ == '__main__': main() ```
instruction
0
79,748
13
159,496
No
output
1
79,748
13
159,497
Provide a correct Python 3 solution for this coding contest problem. The best night ever in the world has come! It's 8 p.m. of December 24th, yes, the night of Cristmas Eve. Santa Clause comes to a silent city with ringing bells. Overtaking north wind, from a sleigh a reindeer pulls she shoot presents to soxes hanged near windows for children. The sleigh she is on departs from a big christmas tree on the fringe of the city. Miracle power that the christmas tree spread over the sky like a web and form a paths that the sleigh can go on. Since the paths with thicker miracle power is easier to go, these paths can be expressed as undirected weighted graph. Derivering the present is very strict about time. When it begins dawning the miracle power rapidly weakens and Santa Clause can not continue derivering any more. Her pride as a Santa Clause never excuses such a thing, so she have to finish derivering before dawning. The sleigh a reindeer pulls departs from christmas tree (which corresponds to 0th node), and go across the city to the opposite fringe (n-1 th node) along the shortest path. Santa Clause create presents from the miracle power and shoot them from the sleigh the reindeer pulls at his full power. If there are two or more shortest paths, the reindeer selects one of all shortest paths with equal probability and go along it. By the way, in this city there are p children that wish to see Santa Clause and are looking up the starlit sky from their home. Above the i-th child's home there is a cross point of the miracle power that corresponds to c[i]-th node of the graph. The child can see Santa Clause if (and only if) Santa Clause go through the node. Please find the probability that each child can see Santa Clause. Constraints * 3 ≤ n ≤ 100 * There are no parallel edges and a edge whose end points are identical. * 0 < weight of the edge < 10000 Input Input consists of several datasets. The first line of each dataset contains three integers n, m, p, which means the number of nodes and edges of the graph, and the number of the children. Each node are numbered 0 to n-1. Following m lines contains information about edges. Each line has three integers. The first two integers means nodes on two endpoints of the edge. The third one is weight of the edge. Next p lines represent c[i] respectively. Input terminates when n = m = p = 0. Output For each dataset, output p decimal values in same order as input. Write a blank line after that. You may output any number of digit and may contain an error less than 1.0e-6. Example Input 3 2 1 0 1 2 1 2 3 1 4 5 2 0 1 1 0 2 1 1 2 1 1 3 1 2 3 1 1 2 0 0 0 Output 1.00000000 0.50000000 0.50000000
instruction
0
79,863
13
159,726
"Correct Solution: ``` from heapq import heappush, heappop INF = 10 ** 20 while True: n, m, p = map(int, input().split()) if n == 0: break edges = [[] for _ in range(n)] for _ in range(m): x, y, w = map(int, input().split()) edges[x].append((y, w)) edges[y].append((x, w)) que = [] heappush(que, (0, 0)) shortest_counter = [[0] * n for _ in range(n)] shortest_counter[0][0] = 1 dist = [INF] * n dist[0] = 0 path_counter = [0] * n path_counter[0] = 1 while que: total, node = heappop(que) count = shortest_counter[node] for to, w in edges[node]: new_total = total + w new_count = [i for i in count] new_count[to] += path_counter[node] if dist[to] > new_total: dist[to] = new_total shortest_counter[to] = [i for i in new_count] path_counter[to] = path_counter[node] heappush(que, (new_total, to)) elif dist[to] == new_total: shortest_counter[to] = [i + j for i, j in zip(shortest_counter[to], new_count)] path_counter[to] += path_counter[node] for _ in range(p): print(shortest_counter[n - 1][int(input())] / path_counter[n - 1]) print() ```
output
1
79,863
13
159,727
Provide a correct Python 3 solution for this coding contest problem. The best night ever in the world has come! It's 8 p.m. of December 24th, yes, the night of Cristmas Eve. Santa Clause comes to a silent city with ringing bells. Overtaking north wind, from a sleigh a reindeer pulls she shoot presents to soxes hanged near windows for children. The sleigh she is on departs from a big christmas tree on the fringe of the city. Miracle power that the christmas tree spread over the sky like a web and form a paths that the sleigh can go on. Since the paths with thicker miracle power is easier to go, these paths can be expressed as undirected weighted graph. Derivering the present is very strict about time. When it begins dawning the miracle power rapidly weakens and Santa Clause can not continue derivering any more. Her pride as a Santa Clause never excuses such a thing, so she have to finish derivering before dawning. The sleigh a reindeer pulls departs from christmas tree (which corresponds to 0th node), and go across the city to the opposite fringe (n-1 th node) along the shortest path. Santa Clause create presents from the miracle power and shoot them from the sleigh the reindeer pulls at his full power. If there are two or more shortest paths, the reindeer selects one of all shortest paths with equal probability and go along it. By the way, in this city there are p children that wish to see Santa Clause and are looking up the starlit sky from their home. Above the i-th child's home there is a cross point of the miracle power that corresponds to c[i]-th node of the graph. The child can see Santa Clause if (and only if) Santa Clause go through the node. Please find the probability that each child can see Santa Clause. Constraints * 3 ≤ n ≤ 100 * There are no parallel edges and a edge whose end points are identical. * 0 < weight of the edge < 10000 Input Input consists of several datasets. The first line of each dataset contains three integers n, m, p, which means the number of nodes and edges of the graph, and the number of the children. Each node are numbered 0 to n-1. Following m lines contains information about edges. Each line has three integers. The first two integers means nodes on two endpoints of the edge. The third one is weight of the edge. Next p lines represent c[i] respectively. Input terminates when n = m = p = 0. Output For each dataset, output p decimal values in same order as input. Write a blank line after that. You may output any number of digit and may contain an error less than 1.0e-6. Example Input 3 2 1 0 1 2 1 2 3 1 4 5 2 0 1 1 0 2 1 1 2 1 1 3 1 2 3 1 1 2 0 0 0 Output 1.00000000 0.50000000 0.50000000
instruction
0
79,864
13
159,728
"Correct Solution: ``` # AOJ 1058 Winter Bells # Python3 2018.7.7 bal4u import heapq INF = 0x7fffffff def dijkstra(V, to, start): dist, path = [INF]*V, [0]*V Q = [] dist[start], path[start] = 0, 1 heapq.heappush(Q, (0, start)) while Q: t, s = heapq.heappop(Q) if dist[s] < t: continue for e, cost in to[s]: nt = t + cost if dist[e] < nt: continue if dist[e] > nt: path[e] = 0 dist[e] = nt heapq.heappush(Q, (nt, e)) path[e] += path[s] return [dist, path] while True: n, m, p = map(int, input().split()) if n == 0: break to = [[] for i in range(n)] for i in range(m): a, b, c = map(int, input().split()) to[a].append((b, c)) to[b].append((a, c)) dist1, path1 = dijkstra(n, to, 0) dist2, path2 = dijkstra(n, to, n-1) for i in range(p): c = int(input()) if dist1[c]+dist2[c] == dist2[0]: print((path1[c]*path2[c])/path2[0]) else: print(0) print() ```
output
1
79,864
13
159,729
Provide a correct Python 3 solution for this coding contest problem. The best night ever in the world has come! It's 8 p.m. of December 24th, yes, the night of Cristmas Eve. Santa Clause comes to a silent city with ringing bells. Overtaking north wind, from a sleigh a reindeer pulls she shoot presents to soxes hanged near windows for children. The sleigh she is on departs from a big christmas tree on the fringe of the city. Miracle power that the christmas tree spread over the sky like a web and form a paths that the sleigh can go on. Since the paths with thicker miracle power is easier to go, these paths can be expressed as undirected weighted graph. Derivering the present is very strict about time. When it begins dawning the miracle power rapidly weakens and Santa Clause can not continue derivering any more. Her pride as a Santa Clause never excuses such a thing, so she have to finish derivering before dawning. The sleigh a reindeer pulls departs from christmas tree (which corresponds to 0th node), and go across the city to the opposite fringe (n-1 th node) along the shortest path. Santa Clause create presents from the miracle power and shoot them from the sleigh the reindeer pulls at his full power. If there are two or more shortest paths, the reindeer selects one of all shortest paths with equal probability and go along it. By the way, in this city there are p children that wish to see Santa Clause and are looking up the starlit sky from their home. Above the i-th child's home there is a cross point of the miracle power that corresponds to c[i]-th node of the graph. The child can see Santa Clause if (and only if) Santa Clause go through the node. Please find the probability that each child can see Santa Clause. Constraints * 3 ≤ n ≤ 100 * There are no parallel edges and a edge whose end points are identical. * 0 < weight of the edge < 10000 Input Input consists of several datasets. The first line of each dataset contains three integers n, m, p, which means the number of nodes and edges of the graph, and the number of the children. Each node are numbered 0 to n-1. Following m lines contains information about edges. Each line has three integers. The first two integers means nodes on two endpoints of the edge. The third one is weight of the edge. Next p lines represent c[i] respectively. Input terminates when n = m = p = 0. Output For each dataset, output p decimal values in same order as input. Write a blank line after that. You may output any number of digit and may contain an error less than 1.0e-6. Example Input 3 2 1 0 1 2 1 2 3 1 4 5 2 0 1 1 0 2 1 1 2 1 1 3 1 2 3 1 1 2 0 0 0 Output 1.00000000 0.50000000 0.50000000
instruction
0
79,865
13
159,730
"Correct Solution: ``` while 1: n,m,p=map(int,input().split()) if (n,m,p)==(0,0,0): break es=[] for i in range(m): u,v,w=map(int,input().split()) es.extend([(u,v,w),(v,u,w)]) d=[[float("inf")]*n for _ in range(n)] for i in range(n): d[i][i]=0 for e in es: d[e[0]][e[1]]=e[2] for k in range(n): d=[[min(d[i][j],d[i][k]+d[k][j]) for j in range(n)] for i in range(n)] dp=[[0]*n for _ in range(n)] for e in es: if d[0][e[0]]+e[2]+d[e[1]][-1]==d[0][-1]: dp[e[0]][e[1]]=1 for k in range(n): dp=[[dp[i][j]+dp[i][k]*dp[k][j] for j in range(n)] for i in range(n)] for _ in range(p): c=int(input()) print(dp[0][c]*dp[c][-1]/dp[0][-1]) ```
output
1
79,865
13
159,731
Provide a correct Python 3 solution for this coding contest problem. The best night ever in the world has come! It's 8 p.m. of December 24th, yes, the night of Cristmas Eve. Santa Clause comes to a silent city with ringing bells. Overtaking north wind, from a sleigh a reindeer pulls she shoot presents to soxes hanged near windows for children. The sleigh she is on departs from a big christmas tree on the fringe of the city. Miracle power that the christmas tree spread over the sky like a web and form a paths that the sleigh can go on. Since the paths with thicker miracle power is easier to go, these paths can be expressed as undirected weighted graph. Derivering the present is very strict about time. When it begins dawning the miracle power rapidly weakens and Santa Clause can not continue derivering any more. Her pride as a Santa Clause never excuses such a thing, so she have to finish derivering before dawning. The sleigh a reindeer pulls departs from christmas tree (which corresponds to 0th node), and go across the city to the opposite fringe (n-1 th node) along the shortest path. Santa Clause create presents from the miracle power and shoot them from the sleigh the reindeer pulls at his full power. If there are two or more shortest paths, the reindeer selects one of all shortest paths with equal probability and go along it. By the way, in this city there are p children that wish to see Santa Clause and are looking up the starlit sky from their home. Above the i-th child's home there is a cross point of the miracle power that corresponds to c[i]-th node of the graph. The child can see Santa Clause if (and only if) Santa Clause go through the node. Please find the probability that each child can see Santa Clause. Constraints * 3 ≤ n ≤ 100 * There are no parallel edges and a edge whose end points are identical. * 0 < weight of the edge < 10000 Input Input consists of several datasets. The first line of each dataset contains three integers n, m, p, which means the number of nodes and edges of the graph, and the number of the children. Each node are numbered 0 to n-1. Following m lines contains information about edges. Each line has three integers. The first two integers means nodes on two endpoints of the edge. The third one is weight of the edge. Next p lines represent c[i] respectively. Input terminates when n = m = p = 0. Output For each dataset, output p decimal values in same order as input. Write a blank line after that. You may output any number of digit and may contain an error less than 1.0e-6. Example Input 3 2 1 0 1 2 1 2 3 1 4 5 2 0 1 1 0 2 1 1 2 1 1 3 1 2 3 1 1 2 0 0 0 Output 1.00000000 0.50000000 0.50000000
instruction
0
79,866
13
159,732
"Correct Solution: ``` INF=int(1e9) while 1: n,m,p=map(int,input().split()) if (n,m,p)==(0,0,0): break es=[] for i in range(m): u,v,w=map(int,input().split()) es.extend([(u,v,w),(v,u,w)]) d=[[INF]*n for _ in range(n)] for i in range(n): d[i][i]=0 for e in es: d[e[0]][e[1]]=e[2] 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]) dp=[[0]*n for _ in range(n)] for e in es: if d[0][e[0]]+e[2]+d[e[1]][-1]==d[0][-1]: dp[e[0]][e[1]]=1 for k in range(n): for i in range(n): for j in range(n): dp[i][j]+=dp[i][k]*dp[k][j]; for _ in range(p): c=int(input()) print("{:.9f}".format(dp[0][c]*dp[c][-1]/dp[0][-1])) ```
output
1
79,866
13
159,733
Provide a correct Python 3 solution for this coding contest problem. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7
instruction
0
79,905
13
159,810
"Correct Solution: ``` import sys import queue # input n = int(input()) tree = [[] for _ in range(n)] for _ in range(n - 1): s, t, w = map(int, sys.stdin.readline().strip().split()) tree[s].append((t, w)) tree[t].append((s, w)) def search(current): distance = [0] * n foot_print = [False] * n que = queue.LifoQueue() que.put((current, 0)) while not que.empty(): current_node, current_dist = que.get() # print(f'corrent_node: {current_node}, current_dist: {current_dist}') distance[current_node] = current_dist foot_print[current_node] = True for node, dist in tree[current_node]: # print(f'node: {node}, dist: {dist}') if foot_print[node] is True: continue que.put((node, dist + current_dist)) return distance dist = search(0) # 適当な点から開始 furthest_node = dist.index(max(dist)) # 最遠点の取得 dist = search(furthest_node) # 最遠点からの距離の取得 diameter = max(dist) print(diameter) ```
output
1
79,905
13
159,811
Provide a correct Python 3 solution for this coding contest problem. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7
instruction
0
79,906
13
159,812
"Correct Solution: ``` # -*- coding: utf-8 -*- from collections import deque if __name__ == '__main__': n = int(input()) E = [set() for _ in range(n)] for _ in range(n - 1): s, t, d = map(int, input().split()) E[s].add((t, d)) E[t].add((s, d)) Q = deque() def bfs(s): d = [float("inf")] * n Q.append(s) d[s] = 0 while Q: u = Q.popleft() for v, w in E[u]: if d[v] == float("inf"): d[v] = d[u] + w Q.append(v) return d d = bfs(0) tgt = d.index(max(d)) d = bfs(tgt) print(max(d)) ```
output
1
79,906
13
159,813
Provide a correct Python 3 solution for this coding contest problem. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7
instruction
0
79,907
13
159,814
"Correct Solution: ``` import sys readline = sys.stdin.readline def dfs(root): visited = [False] * n queue = [(0, root)] longest = (-1, -1) while queue: total_weight, node = queue.pop() if visited[node]: continue visited[node] = True longest = max(longest, (total_weight, node)) queue += [(total_weight + w, t) for w, t in edges[node] if not visited[t]] return longest n = int(readline()) edges = [set() for _ in range(n)] for _ in range(n - 1): s, t, w = map(int, readline().split()) edges[s].add((w, t)) edges[t].add((w, s)) _, ln = dfs(0) ld, _ = dfs(ln) print(ld) ```
output
1
79,907
13
159,815
Provide a correct Python 3 solution for this coding contest problem. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7
instruction
0
79,908
13
159,816
"Correct Solution: ``` import sys readline = sys.stdin.readline from collections import deque def dfs(root): visited = [False] * n queue = deque([(0, root)]) longest = (-1, -1) while queue: total_weight, node = queue.pop() if visited[node]: continue visited[node] = True longest = max(longest, (total_weight, node)) for w, t in edges[node]: if not visited[t]: queue.append((total_weight + w, t)) return longest n = int(readline()) edges = [set() for _ in range(n)] for _ in range(n - 1): s, t, w = map(int, readline().split()) edges[s].add((w, t)) edges[t].add((w, s)) _, ln = dfs(0) ld, _ = dfs(ln) print(ld) ```
output
1
79,908
13
159,817
Provide a correct Python 3 solution for this coding contest problem. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7
instruction
0
79,909
13
159,818
"Correct Solution: ``` import sys input = sys.stdin.readline from operator import itemgetter sys.setrecursionlimit(10000000) INF = 10**30 G = [] class Edge: def __init__(self, to, w): self.to = to self.w = w def dfs(s, d, fr, dist): dist[s] = d for edge in G[s]: if edge.to != fr: dfs(edge.to, d + edge.w, s, dist) def main(): global G n = int(input().strip()) G = [[] for _ in range(n)] d1 = [0] * n d2 = [0] * n for i in range(n-1): s, t, w = map(int, input().strip().split()) G[s].append(Edge(t, w)) G[t].append(Edge(s, w)) dfs(0, 0, -1, d1) j = d1.index(max(d1)) dfs(j, 0, -1, d2) print(max(d2)) if __name__ == '__main__': main() ```
output
1
79,909
13
159,819
Provide a correct Python 3 solution for this coding contest problem. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7
instruction
0
79,910
13
159,820
"Correct Solution: ``` import sys input = sys.stdin.readline class Tree(): def __init__(self,n,edge): self.n = n self.tree = [[] for _ in range(n)] for e in edge: self.tree[e[0]].append((e[1],e[2])) self.tree[e[1]].append((e[0],e[2])) def setroot(self,root): self.root = root self.parent = [None for _ in range(self.n)] self.parent[root] = -1 self.depth = [None for _ in range(self.n)] self.depth[root] = 0 self.distance = [None for _ in range(self.n)] self.distance[root] = 0 stack = [root] while stack: node = stack.pop() for adj,cost in self.tree[node]: if self.parent[adj] is None: self.parent[adj] = node self.depth[adj] = self.depth[node]+1 self.distance[adj] = self.distance[node]+cost stack.append(adj) def diam(self): u = self.distance.index(max(self.distance)) dist_u = [None for _ in range(N)] dist_u[u] = 0 stack = [u] while stack: node = stack.pop() for adj,cost in self.tree[node]: if dist_u[adj] is None: dist_u[adj] = dist_u[node]+cost stack.append(adj) return max(dist_u) N = int(input()) E = [list(map(int,input().split())) for _ in range(N-1)] t = Tree(N,E) t.setroot(0) print(t.diam()) ```
output
1
79,910
13
159,821
Provide a correct Python 3 solution for this coding contest problem. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7
instruction
0
79,911
13
159,822
"Correct Solution: ``` #!/usr/bin/env python3 # GRL_5_A: Tree - Diameter of a Tree class Edge: __slots__ = ('v', 'w') def __init__(self, v, w): self.v = v self.w = w def either(self): return self.v def other(self, v): if v == self.v: return self.w else: return self.v class WeightedEdge(Edge): __slots__ = ('v', 'w', 'weight') def __init__(self, v, w, weight): super().__init__(v, w) self.weight = weight class Graph: def __init__(self, v): self.v = v self._edges = [[] for _ in range(v)] def add(self, e): self._edges[e.v].append(e) self._edges[e.w].append(e) def adj(self, v): return self._edges[v] def edges(self): for es in self._edges: for e in es: yield e def diameter(graph): def dfs(s): visited = [False] * graph.v weights = [0] * graph.v stack = [(s, 0)] while stack: v, weight = stack.pop() if not visited[v]: visited[v] = True weights[v] = weight for e in graph.adj(v): w = e.other(v) if not visited[w]: stack.append((w, weight + e.weight)) return weights v0 = 0 ws0 = dfs(v0) v1 = max((wg, v) for v, wg in enumerate(ws0))[1] ws1 = dfs(v1) v2 = max((wg, v) for v, wg in enumerate(ws1))[1] return max(ws0[v2], ws1[v2]) def run(): n = int(input()) g = Graph(n) for _ in range(n-1): s, t, w = [int(i) for i in input().split()] g.add(WeightedEdge(s, t, w)) print(diameter(g)) if __name__ == '__main__': run() ```
output
1
79,911
13
159,823
Provide a correct Python 3 solution for this coding contest problem. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7
instruction
0
79,912
13
159,824
"Correct Solution: ``` import sys readline = sys.stdin.readline def dfs(root): visited = [False] * n queue = [(0, root)] longest = (-1, -1) while queue: total_weight, node = queue.pop() if visited[node]: continue visited[node] = True longest = max(longest, (total_weight, node)) for w, t in edges[node]: if not visited[t]: queue.append((total_weight + w, t)) return longest n = int(readline()) edges = [set() for _ in range(n)] for _ in range(n - 1): s, t, w = map(int, readline().split()) edges[s].add((w, t)) edges[t].add((w, s)) _, ln = dfs(0) ld, _ = dfs(ln) print(ld) ```
output
1
79,912
13
159,825
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7 Submitted Solution: ``` N = int(input()) G = [[] for i in range(N)] for i in range(N-1): s, t, w = map(int, input().split()) G[s].append((t, w)) G[t].append((s, w)) from collections import deque def bfs(s): dist = [None]*N que = deque([s]) dist[s] = 0 while que: v = que.popleft() d = dist[v] for w, c in G[v]: if dist[w] is not None: continue dist[w] = d + c que.append(w) d = max(dist) return dist.index(d), d u, _ = bfs(0) v, d = bfs(u) print(d) ```
instruction
0
79,913
13
159,826
Yes
output
1
79,913
13
159,827
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7 Submitted Solution: ``` import sys sys.setrecursionlimit(10**6) N = int(input()) G = [[] for i in range(N)] for i in range(N-1): s, t, w = map(int, input().split()) G[s].append([t, w]) G[t].append([s, w]) def dfs(n): visited = [False] * N stack = [[n, 0]] longest = [-1, -1] while stack: node, weight = stack.pop() if visited[node]: continue visited[node] = True if longest[1] < weight: longest = [node, weight] for n, w in G[node]: if not visited[n]: stack.append([n, w + weight]) return longest xn, xw = dfs(0) yn, yw = dfs(xn) print(yw) ```
instruction
0
79,914
13
159,828
Yes
output
1
79,914
13
159,829
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7 Submitted Solution: ``` from collections import deque n = int(input()) C = [[] for _ in range(n)] for _ in range(n-1): s,t,w = map(int,input().split()) C[s].append((t,w)) C[t].append((s,w)) INF = 10000000000 def BFS(start): D = [INF]*n q = deque() visited = [False]*n q.append(start) visited[start] = True D[start] = 0 while q: node = q.pop() visited[node] = True for adj,w in C[node]: if D[node] + w < D[adj]: D[adj] = D[node] + w if not visited[adj]: q.append(adj) return D D = BFS(0) max_ind1 = D.index(max(D)) D = BFS(max_ind1) print(max(D)) ```
instruction
0
79,915
13
159,830
Yes
output
1
79,915
13
159,831
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7 Submitted Solution: ``` from heapq import heapify, heappop, heappush, heappushpop, heapreplace def diameter(tonodes, n): visited = [False for _ in range(n)] queue = [] max_weight = 0 max_node = 0 for i, node in enumerate(tonodes): if len(node) > 0: visited[i] = True max_node = i for edge in node: heappush(queue, (-edge[0], edge[1])) break while len(queue) > 0: weight, node = heappop(queue) visited[node] = True if max_weight < -weight: max_weight = -weight max_node = node for edge in tonodes[node]: if not visited[edge[1]]: heappush(queue, (weight - edge[0], edge[1])) for i in range(n): visited[i] = False visited[max_node] = True for edge in tonodes[max_node]: heappush(queue, (-edge[0], edge[1])) max_weight = 0 while len(queue) > 0: weight, node = heappop(queue) visited[node] = True if max_weight < -weight: max_weight = -weight max_node = node for edge in tonodes[node]: if not visited[edge[1]]: heappush(queue, (weight - edge[0], edge[1])) return max_weight def main(): n = int(input()) tonodes = [[] for _ in range(n)] for _ in range(n - 1): s, t, w = map(int, input().split()) tonodes[s].append((w, t)) tonodes[t].append((w, s)) max_weight = diameter(tonodes, n) print(max_weight) if __name__ == "__main__": main() ```
instruction
0
79,916
13
159,832
Yes
output
1
79,916
13
159,833
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7 Submitted Solution: ``` n = int(input()) from collections import defaultdict from queue import deque g = defaultdict(list) d = [float('inf')] * n visited = [False] * n d[0] = 0 def bfs(v): s = deque([v]) visited[v] = True while len(s) > 0: t = s.pop() for c,w in g[t]: if not visited[c] and d[c] == float('inf'): d[c] = d[t] + w visited[c] = True s.append(c) for i in range(n-1): s,t,w = map(int, input().split()) g[s].append((t, w)) g[t].append((s, w)) bfs(0) mi = 0 md = 0 for i,k in enumerate(d): if md < k: mi = i d = [float('inf')] * n visited = [False] * n d[mi] = 0 bfs(mi) print(max(d)) ```
instruction
0
79,917
13
159,834
No
output
1
79,917
13
159,835
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7 Submitted Solution: ``` # Acceptance of input import sys f_i = sys.stdin n = int(f_i.readline()) edges = [[None] * n for i in range(n)] for l_i in f_i: s, t, w = map(int, l_i.split()) edges[s][t] = w edges[t][s] = w # Tree Walk and Output distance = [0] * n def tree_walk(u, d, p): for v, e in enumerate(edges[u]): if e != None and v != p: c_d = d + e distance[v] = c_d tree_walk(v, c_d, u) tree_walk(0, 0, None) end_point = distance.index(max(distance)) tree_walk(end_point, 0, None) print(max(distance)) ```
instruction
0
79,918
13
159,836
No
output
1
79,918
13
159,837
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7 Submitted Solution: ``` from heapq import heappush, heappop INF = 10000000000 def dijkstra(r, v, dic): dp = [] q = [] dp = [INF] * v dp[r] = 0 heappush(q, (0, r)) while q: cost, vtx = heappop(q) if dp[vtx] < cost: continue if vtx not in dic: continue for vtx1, cost1 in dic[vtx]: if cost + cost1 < dp[vtx1]: dp[vtx1] = cost + cost1 heappush(q, (cost + cost1, vtx1)) return dp dp = [] line = input() n = int(line) edge = {} for _ in range(0, n - 1): line = input() s, t, d = list(map(int, line.split())) if s not in edge: edge[s] = [[t, d]] else: edge[s] += [[t, d]] if t not in edge: edge[t] = [[s, d]] else: edge[t] += [[s, d]] diam = 0 for s in range(0, n - 1): dp = dijkstra(s, n, edge) diam = max(max(dp[i] if dp[i] != INF else 0 for i in range(0, n)), diam) print(diam) ```
instruction
0
79,919
13
159,838
No
output
1
79,919
13
159,839
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7 Submitted Solution: ``` # Acceptance of input import sys f_i = sys.stdin n = int(f_i.readline()) edges = [[None] * n for i in range(n)] for l_i in f_i: s, t, w = map(int, l_i.split()) edges[s][t] = w edges[t][s] = w # dfs tree walk 1 import collections path = collections.deque() path.append(0) distance = 0 max_distance = 0 unvisited = [False] + [True] * (n - 1) while True: u = path[-1] adj_e = edges[u] for v, e in enumerate(adj_e): if unvisited[v] and e != None: path.append(v) distance += e unvisited[v] = False if max_distance < distance: max_distance = distance end_point = v break if u == path[-1]: path.pop() if path: distance -= edges[u][path[-1]] else: break # Measurement of diameter(dfs tree walk 2) path.append(end_point) distance = 0 diameter = 0 unvisited = [True] * n unvisited[end_point] = False while True: u = path[-1] adj_e = edges[u] for v, e in enumerate(adj_e): if unvisited[v] and e != None: path.append(v) distance += e unvisited[v] = False if diameter < distance: diameter = distance end_point = v break if u == path[-1]: path.pop() if path: distance -= edges[u][path[-1]] else: break # output print(diameter) ```
instruction
0
79,920
13
159,840
No
output
1
79,920
13
159,841
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has got a tree consisting of n vertices. He wants to delete some (possibly zero) edges in this tree such that the maximum matching in the resulting graph is unique. He asks you to calculate the number of ways to choose a set of edges to remove. A matching in the graph is a subset of its edges such that there is no vertex incident to two (or more) edges from the subset. A maximum matching is a matching such that the number of edges in the subset is maximum possible among all matchings in this graph. Since the answer may be large, output it modulo 998244353. Input The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. Each of the next n − 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) denoting an edge between vertex u and vertex v. It is guaranteed that these edges form a tree. Output Print one integer — the number of ways to delete some (possibly empty) subset of edges so that the maximum matching in the resulting graph is unique. Print the answer modulo 998244353. Examples Input 4 1 2 1 3 1 4 Output 4 Input 4 1 2 2 3 3 4 Output 6 Input 1 Output 1 Note Possible ways to delete edges in the first example: * delete (1, 2) and (1, 3). * delete (1, 2) and (1, 4). * delete (1, 3) and (1, 4). * delete all edges. Possible ways to delete edges in the second example: * delete no edges. * delete (1, 2) and (2, 3). * delete (1, 2) and (3, 4). * delete (2, 3) and (3, 4). * delete (2, 3). * delete all edges. Submitted Solution: ``` import sys sys.setrecursionlimit(2*10**5) n = int(input()) from collections import defaultdict tree = defaultdict(list) for _ in range(n-1): a, b = [int(x) for x in input().split()] tree[a].append(b) tree[b].append(a) def remove_parents(nd, p): print(nd) if p in tree[nd]: idx = tree[nd].index(p) tree[nd].pop(idx) for b in tree[nd]: remove_parents(b, nd) remove_parents(1, None) # roots the tree at 1 MOD = 998244353 cache = [[None, None] for _ in range(n+3)] def rec_tree(node, match): if cache[node][match] != None: return cache[node][match] if not tree[node]: # leaf cache[node][match] = int(match == False) return cache[node][match] if not match: res = 1 for b in tree[node]: res *= rec_tree(b, True) + rec_tree(b, False) cache[node][match] = res return res # match is True tie_with_unmatched = {} for b in tree[node]: pd = 1 for bb in tree[b]: pd *= 2*rec_tree(bb, True) + rec_tree(bb, False) pd %= MOD tie_with_unmatched[b] = pd pd_all = 1 for b in tree[node]: pd_all *= 2*rec_tree(b, True) + rec_tree(b, False) pd_all %= MOD sm = 0 for b in tree[node]: sm += pd_all // (2*rec_tree(b, True) + rec_tree(b, False)) * tie_with_unmatched[b] sm %= MOD cache[node][match] = sm return sm # for i in range(n, 0, -1): # rec_tree(i, True) # rec_tree(i, False) # for i in range(1, n+1): # print("dp[{}][{}] = {}".format(i, True, rec_tree(i, True))) # print("dp[{}][{}] = {}".format(i, False, rec_tree(i, False))) print((rec_tree(1, True) + rec_tree(1, False)) % MOD) ```
instruction
0
79,953
13
159,906
No
output
1
79,953
13
159,907
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has got a tree consisting of n vertices. He wants to delete some (possibly zero) edges in this tree such that the maximum matching in the resulting graph is unique. He asks you to calculate the number of ways to choose a set of edges to remove. A matching in the graph is a subset of its edges such that there is no vertex incident to two (or more) edges from the subset. A maximum matching is a matching such that the number of edges in the subset is maximum possible among all matchings in this graph. Since the answer may be large, output it modulo 998244353. Input The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. Each of the next n − 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) denoting an edge between vertex u and vertex v. It is guaranteed that these edges form a tree. Output Print one integer — the number of ways to delete some (possibly empty) subset of edges so that the maximum matching in the resulting graph is unique. Print the answer modulo 998244353. Examples Input 4 1 2 1 3 1 4 Output 4 Input 4 1 2 2 3 3 4 Output 6 Input 1 Output 1 Note Possible ways to delete edges in the first example: * delete (1, 2) and (1, 3). * delete (1, 2) and (1, 4). * delete (1, 3) and (1, 4). * delete all edges. Possible ways to delete edges in the second example: * delete no edges. * delete (1, 2) and (2, 3). * delete (1, 2) and (3, 4). * delete (2, 3) and (3, 4). * delete (2, 3). * delete all edges. Submitted Solution: ``` w = input() print (w) ```
instruction
0
79,954
13
159,908
No
output
1
79,954
13
159,909
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has got a tree consisting of n vertices. He wants to delete some (possibly zero) edges in this tree such that the maximum matching in the resulting graph is unique. He asks you to calculate the number of ways to choose a set of edges to remove. A matching in the graph is a subset of its edges such that there is no vertex incident to two (or more) edges from the subset. A maximum matching is a matching such that the number of edges in the subset is maximum possible among all matchings in this graph. Since the answer may be large, output it modulo 998244353. Input The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. Each of the next n − 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) denoting an edge between vertex u and vertex v. It is guaranteed that these edges form a tree. Output Print one integer — the number of ways to delete some (possibly empty) subset of edges so that the maximum matching in the resulting graph is unique. Print the answer modulo 998244353. Examples Input 4 1 2 1 3 1 4 Output 4 Input 4 1 2 2 3 3 4 Output 6 Input 1 Output 1 Note Possible ways to delete edges in the first example: * delete (1, 2) and (1, 3). * delete (1, 2) and (1, 4). * delete (1, 3) and (1, 4). * delete all edges. Possible ways to delete edges in the second example: * delete no edges. * delete (1, 2) and (2, 3). * delete (1, 2) and (3, 4). * delete (2, 3) and (3, 4). * delete (2, 3). * delete all edges. Submitted Solution: ``` import sys sys.setrecursionlimit(2*10**5) n = int(input()) from collections import defaultdict tree = defaultdict(list) for _ in range(n-1): a, b = [int(x) for x in input().split()] tree[a].append(b) tree[b].append(a) def remove_parents(nd, p): #print(nd) if p in tree[nd]: idx = tree[nd].index(p) tree[nd].pop(idx) for b in tree[nd]: remove_parents(b, nd) remove_parents(1, None) # roots the tree at 1 MOD = 998244353 cache = [[None, None] for _ in range(n+3)] def rec_tree(node, match): if cache[node][match] != None: return cache[node][match] if not tree[node]: # leaf cache[node][match] = int(match == False) return cache[node][match] if not match: res = 1 for b in tree[node]: res *= rec_tree(b, True) + rec_tree(b, False) cache[node][match] = res return res # match is True tie_with_unmatched = {} for b in tree[node]: pd = 1 for bb in tree[b]: pd *= 2*rec_tree(bb, True) + rec_tree(bb, False) pd %= MOD tie_with_unmatched[b] = pd pd_all = 1 for b in tree[node]: pd_all *= 2*rec_tree(b, True) + rec_tree(b, False) pd_all %= MOD sm = 0 for b in tree[node]: sm += pd_all // (2*rec_tree(b, True) + rec_tree(b, False)) * tie_with_unmatched[b] sm %= MOD cache[node][match] = sm return sm # for i in range(n, 0, -1): # rec_tree(i, True) # rec_tree(i, False) # for i in range(1, n+1): # print("dp[{}][{}] = {}".format(i, True, rec_tree(i, True))) # print("dp[{}][{}] = {}".format(i, False, rec_tree(i, False))) print((rec_tree(1, True) + rec_tree(1, False)) % MOD) ```
instruction
0
79,955
13
159,910
No
output
1
79,955
13
159,911
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has got a tree consisting of n vertices. He wants to delete some (possibly zero) edges in this tree such that the maximum matching in the resulting graph is unique. He asks you to calculate the number of ways to choose a set of edges to remove. A matching in the graph is a subset of its edges such that there is no vertex incident to two (or more) edges from the subset. A maximum matching is a matching such that the number of edges in the subset is maximum possible among all matchings in this graph. Since the answer may be large, output it modulo 998244353. Input The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree. Each of the next n − 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) denoting an edge between vertex u and vertex v. It is guaranteed that these edges form a tree. Output Print one integer — the number of ways to delete some (possibly empty) subset of edges so that the maximum matching in the resulting graph is unique. Print the answer modulo 998244353. Examples Input 4 1 2 1 3 1 4 Output 4 Input 4 1 2 2 3 3 4 Output 6 Input 1 Output 1 Note Possible ways to delete edges in the first example: * delete (1, 2) and (1, 3). * delete (1, 2) and (1, 4). * delete (1, 3) and (1, 4). * delete all edges. Possible ways to delete edges in the second example: * delete no edges. * delete (1, 2) and (2, 3). * delete (1, 2) and (3, 4). * delete (2, 3) and (3, 4). * delete (2, 3). * delete all edges. Submitted Solution: ``` import sys sys.setrecursionlimit(2*10**5) n = int(input()) from collections import defaultdict tree = defaultdict(list) for _ in range(n-1): a, b = [int(x) for x in input().split()] tree[min(a, b)].append(max(a, b)) # makes sure root is '1'. MOD = 998244353 cache = [[None, None] for _ in range(n+3)] def rec_tree(node, match): if cache[node][match] != None: return cache[node][match] if not tree[node]: # leaf cache[node][match] = int(match == False) return cache[node][match] if not match: res = 1 for b in tree[node]: res *= rec_tree(b, True) + rec_tree(b, False) cache[node][match] = res return res # match is True tie_with_unmatched = {} for b in tree[node]: pd = 1 for bb in tree[b]: pd *= 2*rec_tree(bb, True) + rec_tree(bb, False) pd %= MOD tie_with_unmatched[b] = pd pd_all = 1 for b in tree[node]: pd_all *= 2*rec_tree(b, True) + rec_tree(b, False) pd_all %= MOD sm = 0 for b in tree[node]: sm += pd_all // (2*rec_tree(b, True) + rec_tree(b, False)) * tie_with_unmatched[b] sm %= MOD cache[node][match] = sm return sm # will be leaf-first topo-sorting: for i in range(n, 0, -1): rec_tree(i, True) rec_tree(i, False) # for i in range(1, n+1): # print("dp[{}][{}] = {}".format(i, True, rec_tree(i, True))) # print("dp[{}][{}] = {}".format(i, False, rec_tree(i, False))) print((rec_tree(1, True) + rec_tree(1, False)) % MOD) ```
instruction
0
79,956
13
159,912
No
output
1
79,956
13
159,913
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
80,003
13
160,006
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` def naiveSolve(n): return from collections import deque def main(): n=int(input()) a=readIntArr() setCnts=[0]*60 b=[] for x in a: cnt=0 for i in range(60): if (x&(1<<i))>0: cnt+=1 setCnts[i]+=1 if setCnts[i]==3: print(3) return if cnt>=2: b.append(x) m=len(b) adj=[[] for _ in range(m)] for i in range(m): for j in range(i+1,m): if (b[i]&b[j])>0: adj[i].append(j) adj[j].append(i) ans=inf for i in range(m): dist=[-1]*m parent=[-1]*m q=deque() q.append(i) dist[i]=0 while q: node=q.popleft() for nex in adj[node]: if nex==parent[node]: continue if dist[nex]==-1: # not visited dist[nex]=dist[node]+1 parent[nex]=node q.append(nex) else: ans=min(ans,dist[node]+dist[nex]+1) if ans==inf: print(-1) else: print(ans) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(i,j): print('? {} {}'.format(i,j)) sys.stdout.flush() return int(input()) def answerInteractive(ans): print('! {}'.format(' '.join([str(x) for x in ans]))) sys.stdout.flush() inf=float('inf') MOD=10**9+7 # MOD=998244353 from math import gcd,floor,ceil for _abc in range(1): main() ```
output
1
80,003
13
160,007
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
80,004
13
160,008
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` import sys input = sys.stdin.readline from collections import deque class Graph(object): """docstring for Graph""" def __init__(self,n,d): # Number of nodes and d is True if directed self.n = n self.graph = [[] for i in range(n)] self.parent = [-1 for i in range(n)] self.directed = d def addEdge(self,x,y): self.graph[x].append(y) if not self.directed: self.graph[y].append(x) def bfs(self, root): # NORMAL BFS queue = [root] queue = deque(queue) vis = [0]*self.n while len(queue)!=0: element = queue.popleft() vis[element] = 1 for i in self.graph[element]: if vis[i]==0: queue.append(i) self.parent[i] = element vis[i] = 1 def dfs(self, root): # Iterative DFS ans = [0]*n stack=[root] vis=[0]*self.n stack2=[] while len(stack)!=0: # INITIAL TRAVERSAL element = stack.pop() if vis[element]: continue vis[element] = 1 stack2.append(element) for i in self.graph[element]: if vis[i]==0: self.parent[i] = element stack.append(i) while len(stack2)!=0: # BACKTRACING. Modify the loop according to the question element = stack2.pop() m = 0 for i in self.graph[element]: if i!=self.parent[element]: m += ans[i] ans[element] = m return ans def shortestpath(self, source, dest): # Calculate Shortest Path between two nodes self.bfs(source) path = [dest] while self.parent[path[-1]]!=-1: path.append(parent[path[-1]]) return path[::-1] def detect_cycle(self): indeg = [0]*self.n for i in range(self.n): for j in self.graph[i]: indeg[j] += 1 q = deque() vis = 0 for i in range(self.n): if indeg[i]==0: q.append(i) while len(q)!=0: e = q.popleft() vis += 1 for i in self.graph[e]: indeg[i] -= 1 if indeg[i]==0: q.append(i) if vis!=self.n: return True return False def reroot(self, root, ans): stack = [root] vis = [0]*n while len(stack)!=0: e = stack[-1] if vis[e]: stack.pop() # Reverse_The_Change() continue vis[e] = 1 for i in graph[e]: if not vis[e]: stack.append(i) if self.parent[e]==-1: continue # Change_The_Answers() def eulertour(self, root): stack=[root] t = [] while len(stack)!=0: element = stack[-1] if vis[element]: t.append(stack.pop()) continue t.append(element) vis[element] = 1 for i in self.graph[element]: if not vis[i]: stack.append(i) return t def check(self, root): q = [root] q = deque(q) vis = [0]*self.n dist = {root:0} vis[root] = 1 self.parent = [-1]*n ans = 10**18 while q: e = q.popleft() for i in self.graph[e]: if i not in dist: dist[i] = dist[e] + 1 self.parent[i] = e q.append(i) elif self.parent[e]!=i and self.parent[i]!=e: ans = min(ans, dist[e] + dist[i] + 1) return ans def cycle(self): ans = 10**18 for i in range(n): x = self.check(i) ans = min(ans, x) return ans n = int(input()) b = list(map(int,input().split())) a = [b[i] for i in range(n) if b[i]!=0] n = len(a) if n==0: print (-1) exit() o = [] for i in range(n): if a[i]%2: o.append(i) if len(o)>=3: print (3) exit() count = [0]*64 for i in a: x = bin(i)[2:] x = "0"*(64-len(x))+x for j in range(64): if x[j]=="1": count[j] += 1 for i in count: if i>=3: print (3) exit() g = Graph(n, False) for i in range(n): for j in range(i+1, n): if a[i]&a[j]!=0: g.addEdge(i, j) root = i t = [0]*n ans = g.cycle() # print (g.graph) if ans==10**18: print (-1) else: print (ans) ```
output
1
80,004
13
160,009
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
80,005
13
160,010
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` from collections import deque input() h = [list(bin(int(i)))[2:] for i in input().split()] sas = min(map(len, h)) ans = 1e9 graf = [[] for _ in range(100000)] rebra = [] def bfs(assx, sasx): q = deque() q.append(assx) metka = [1 for _ in range(100000)] metka[assx] = 0 dis = [0 for _ in range(100000)] while q: x = q.popleft() for i in graf[x]: if i == sasx and x != assx: return dis[x] + 2 if metka[i] and (i != sasx or x != assx): metka[i] = 0 dis[i] = dis[x] + 1 q.append(i) return 0 for i in range(len(h)): h[i].reverse() for i in range(60): r = 0 ass = [] for j in range(len(h)): if len(h[j]) <= i: continue if int(h[j][i]): r += 1 ass.append(j) if r >= 3: print(3) exit() if len(ass) > 1: graf[ass[0]].append(ass[1]) graf[ass[1]].append(ass[0]) rebra.append(ass) for i in rebra: g = bfs(i[0], i[1]) if g: ans = min(ans, g) print(ans if ans != 1e9 else -1) ```
output
1
80,005
13
160,011
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
80,006
13
160,012
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` import sys #import math #import random #import time input = sys.stdin.readline # #start = time.time() n = int(input()) m = n a = list(map(int, input().split())) s = [list() for i in range(0, 61)] v = [] for _v in a: if _v: v.append(_v) a = v n = len(v) if n > 128: print(3) exit() # for i in range(0, len(a)): # for j in range(i+1, len(a)): # if a[i] & a[j] != 0: # print(a[i], a[j]) for i in range(0, len(a)): for j in range(0, 61): if a[i] & (1 << j) != 0: s[j].append(a[i]) if len(s[j]) > 2: print(3) exit() ans=1e10 dis = [[1e10 for _ in range(n)] for __ in range(n)] dp = [[1e10 for _ in range(n)] for __ in range(n)] for i in range(n): for j in range(n): if i != j and a[i] & a[j]: dp[i][j] = dis[i][j] = 1 #dis[i][j] = 1 for k in range(n): for i in range(k): for j in range(i+1,k): ans=min(ans,dp[i][j]+dis[i][k]+dis[k][j]) for i in range(n): for j in range(n): dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j]) # print([ans,-1]) # print([ans==1e10]) print([ans,-1][ans==1e10]) ```
output
1
80,006
13
160,013
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
80,007
13
160,014
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` # CODE BEGINS HERE................. from collections import deque def bfs(graph, root, prune_level): """make a pruned BFS search of the graph starting at root. returns the BFS tree, and possibly a traversal edge (u,v) that with the tree forms a cycle of some length. Complexity: O(V + E) """ n = len(graph) level = [-1] * n # -1 == not seen tree = [None] * n # pointers to predecessors toVisit = deque([root]) # queue for BFS level[root] = 0 tree[root] = root best_cycle = float('inf') # start with infinity best_u = None best_v = None while toVisit: u = toVisit.popleft() if level[u] > prune_level: break for v in graph[u]: if tree[u] == v: # ignore the tree edge continue if level[v] == -1: # new vertex - tree edge level[v] = level[u] + 1 toVisit.append(v) tree[v] = u else: # vertex already seen - traversal edge prune_level = level[v] - 1 cycle_len = level[u] + 1 + level[v] if cycle_len < best_cycle: # footnote (1) best_cycle = cycle_len best_u = u best_v = v return tree, best_cycle, best_u, best_v def path(tree, v): """returns the path in the tree from v to the root Complexity: O(V) """ P = [] while not P or P[-1] != v: P.append(v) v = tree[v] return P def shortest_cycle(graph): """Returns a shortest cycle if there is any Complexity: O(V * (V + E)) """ best_cycle = float('inf') best_u = None best_v = None best_tree = None V = list(range(len(graph))) for root in V: tree, cycle_len, u, v = bfs(graph, root, best_cycle // 2) if cycle_len < best_cycle: best_cycle = cycle_len best_u = u best_v = v best_tree = tree if best_cycle == float('inf'): return [] # no cycle found Pu = path(best_tree, best_u) Pv = path(best_tree, best_v) return Pu[::-1] + Pv n = int(input()) b = list(map(int, input().split())) a = [] for i in b: if i != 0: a.append(i) n = len(a) if(n > 200): print(3) else: graph = [[] for i in range(n)] for i in range(n): for j in range(i + 1, n): if a[i] & a[j]: graph[i].append(j) graph[j].append(i) # print(graph) print(len(shortest_cycle(graph)) - 1) # CODE ENDS HERE.................... ```
output
1
80,007
13
160,015
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
80,008
13
160,016
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` import sys, os, re, datetime from collections import * from bisect import * def mat(v, *dims): def submat(i): if i == len(dims)-1: return [v for _ in range(dims[-1])] return [submat(i+1) for _ in range(dims[i])] return submat(0) __cin__ = None def cin(): global __cin__ if __cin__ is None: __cin__ = iter(input().split(" ")) try: return next(__cin__) except StopIteration: __cin__ = iter(input().split(" ")) return next(__cin__) def iarr(n): return [int(cin()) for _ in range(n)] def farr(n): return [float(cin()) for _ in range(n)] def sarr(n): return [cin() for _ in range(n)] def carr(n): return input() def imat(n, m): return [iarr(m) for _ in range(n)] def fmat(n, m): return [farr(m) for _ in range(n)] def smat(n, m): return [sarr(m) for _ in range(n)] def cmat(n, m): return [input() for _ in range(n)] N = 64 n = int(cin()) tmp = iarr(n) t = mat(0, N) g = mat(0, N, 0) adj = [set() for _ in range(n)] INF = 100000 ans = INF a = list(filter(lambda x: x > 0, tmp)) n = len(a) for j in range(N): for i in range(n): v = a[i] t[j] += (v>>j)&1 if t[j] >= 3: print("3") exit(0) if ((v>>j)&1) == 1: g[j].append(i) for i in range(N): if len(g[i]) == 2: adj[g[i][0]].add(g[i][1]) adj[g[i][1]].add(g[i][0]) def bfs(i): dist = mat(INF, n) q = deque() q.append(i) dist[i] = 0 while len(q) > 0: u = q.popleft() for v in adj[u]: if dist[v] == INF: q.append(v) dist[v] = dist[u]+1 elif dist[v]+1 != dist[u]: return dist[v]+dist[u]+1 return INF for i in range(n): ans = min(ans, bfs(i)) print(-1 if ans == INF else ans) ```
output
1
80,008
13
160,017
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
80,009
13
160,018
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` # -*- coding: utf-8 -*- import math import collections import bisect import heapq import time import random import itertools import sys from typing import List """ created by shhuan at 2020/1/10 01:32 """ def shortest_path(u, v, g): q = [w for w in g[u] if w != v] vis = set(q) | {u} d = 0 while q: d += 1 nq = [] for w in q: if w == v: return d for x in g[w]: if x not in vis: vis.add(x) nq.append(x) q = nq return float('inf') def solve(N, A): b = 1 g = collections.defaultdict(list) edges = [] for i in range(64): connected = [i for i, v in enumerate(A) if v & b > 0] if len(connected) >= 3: return 3 for u in connected: for v in connected: if u != v: g[u].append(v) edges.append((u, v)) b <<= 1 # print(g) ans = float('inf') for u, v in edges: # remove edge u, v # print(u, v, shortest_path(u, v, g)) ans = min(ans, 1 + shortest_path(u, v, g)) return ans if ans < float('inf') else -1 N = int(input()) A = [int(x) for x in input().split()] print(solve(N, A)) ```
output
1
80,009
13
160,019
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example.
instruction
0
80,010
13
160,020
Tags: bitmasks, brute force, graphs, shortest paths Correct Solution: ``` # 1205B def do(): n = int(input()) nums = [int(c) for c in input().split(" ")] valid = set() for i in range(64): count = [] for j in range(n): if (1 << i) & nums[j]: count.append(nums[j]) if len(count) == 3: return 3 if len(count) == 2: valid.add(count[0]) valid.add(count[1]) # valid won't be that large hahaha at most 64*2 nv = len(valid) valid = list(valid) dis = [[float('inf')] * nv for _ in range(nv)] for i in range(nv): for j in range(nv): if i == j: dis[i][j] = 0 elif valid[i] & valid[j]: dis[i][j] = 1 mp = [[_ for _ in dis[i]] for i in range(len(dis))] res = nv + 1 for k in range(nv): for i in range(k): for j in range(k): if i != j: res = min(res, dis[i][j] + mp[j][k] + mp[k][i]) for i in range(nv): if k != i: for j in range(nv): dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]) return res if res <= nv else -1 print(do()) ```
output
1
80,010
13
160,021
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` """This code was written by Russell Emerine - linguist, mathematician, coder, musician, and metalhead.""" n = int(input()) a = [] for x in input().split(): x = int(x) if x: a.append(x) n = len(a) edges = set() for d in range(64): p = 1 << d c = [] for i in range(n): x = a[i] if x & p: c.append(i) if len(c) > 2: import sys print(3) sys.exit() if len(c) == 2: edges.add((c[0], c[1])) m = n + 1 adj = [[][:] for _ in range(n)] for u, v in edges: adj[u].append(v) adj[v].append(u) from collections import deque for r in range(n): v = [False] * n p = [-1] * n d = [n + 1] * n d[r] = 0 s = deque([r]) while len(s): h = s.popleft() v[h] = True for c in adj[h]: if p[h] == c: continue elif v[c]: m = min(d[h] + 1 + d[c], m) else: d[c] = d[h] + 1 v[c] = True p[c] = h s.append(c); if m == n + 1: m = -1 print(m) ```
instruction
0
80,011
13
160,022
Yes
output
1
80,011
13
160,023
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` from collections import deque n=int(input()) s=[int(x) for x in input().split()] b=[] mx=-1 for i in range(0,len(s)): t=bin(s[i]) t=t[2:] b.append(t) mx=max(mx,len(t)) for i in range(0,len(b)): b[i]='0'*(mx-len(b[i]))+b[i] flag=0 L=[] kk=dict() for i in range(0,mx): c=0 h=[] for j in range(0,len(b)): if(b[j][i]=='1'): c+=1 h.append(j) if(len(h)==2 and kk.get(tuple(h))==None): h=tuple(h) L.append(h) kk[h]=1 if(c>2): flag=1 break #print(L) if(flag==1): print(3) else: temp=1000000007 for i in range(0,len(L)): arr=[] for j in range(n): s1=[] arr.append(s1) for j in range(0,len(L)): if(j==i): src=L[j][0] dst=L[j][1] else: arr[L[j][0]].append(L[j][1]) arr[L[j][1]].append(L[j][0]) q=deque() q.append((src,0)) visited=[False]*n visited[src]=True while(q): r=q.popleft() visited[r[0]]=True if(r[0]==dst): temp=min(temp,r[1]+1) break for j in arr[r[0]]: if(visited[j]==False): q.append((j,r[1]+1)) if(temp==1000000007): print(-1) else: print(temp) ```
instruction
0
80,012
13
160,024
Yes
output
1
80,012
13
160,025
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` import sys, os, re, datetime, copy from collections import * from bisect import * def mat(v, *dims): def dim(i): return [copy.copy(v) for _ in range(dims[-1])] if i == len(dims)-1 else [dim(i+1) for _ in range(dims[i])] return dim(0) __cin__ = None def cin(): global __cin__ if __cin__ is None: __cin__ = iter(input().split(" ")) try: return next(__cin__) except StopIteration: __cin__ = iter(input().split(" ")) return next(__cin__) def iarr(n): return [int(cin()) for _ in range(n)] def farr(n): return [float(cin()) for _ in range(n)] def sarr(n): return [cin() for _ in range(n)] def carr(n): return input() def imat(n, m): return [iarr(m) for _ in range(n)] def fmat(n, m): return [farr(m) for _ in range(n)] def smat(n, m): return [sarr(m) for _ in range(n)] def cmat(n, m): return [input() for _ in range(n)] def bfs(i): dist = mat(INF, n) q = deque() q.append(i) dist[i] = 0 while len(q) > 0: u = q.popleft() for v in adj[u]: if dist[v] == INF: q.append(v) dist[v] = dist[u]+1 elif dist[v]+1 != dist[u]: return dist[v]+dist[u]+1 return INF N = 64 n = int(cin()) tmp = iarr(n) t = mat(0, N) g = mat([], N) adj = mat(set(), n) INF = 100000 ans = INF a = list(filter(lambda x: x > 0, tmp)) n = len(a) for j in range(N): for i in range(n): v = a[i] t[j] += (v>>j)&1 if t[j] >= 3: print("3") exit(0) if ((v>>j)&1) == 1: g[j].append(i) for i in range(N): if len(g[i]) == 2: adj[g[i][0]].add(g[i][1]) adj[g[i][1]].add(g[i][0]) for i in range(n): ans = min(ans, bfs(i)) print(-1 if ans == INF else ans) mmap = {0: "Hola", 1: "Mundo"} ```
instruction
0
80,013
13
160,026
Yes
output
1
80,013
13
160,027
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` class node(): def __init__(self, v, edges): self.value = v self.edges = edges n = int(input()) a = [int(i) for i in input().split(" ")] def fun(a): nodes = {} for i in range(60): k = 0 value = 1 << i i_edges = set() for j in a: if value&j > 0: # print(i+1) k += 1 if k > 2: del i_edges del nodes return 3 i_edges.add(j) for j in i_edges: if j not in nodes: if (i_edges.difference({j})) != 0: nodes[j] = node(j,i_edges.difference({j})) else: nodes[j].edges = nodes[j].edges.union(i_edges.difference({j})) return nodes def find_short_path(v1, v2): length = 0 v2 = {v2} setic = set() set_was = set() while (v1 not in setic): del setic setic = set() for i in v2: setic = setic.union(nodes[i].edges.difference(set_was)) set_was = set_was.union(setic) if len(setic) == 0: del v2 return 0 length += 1 del v2 v2 = setic.copy() del set_was del setic return length nodes = fun(a) if type(nodes) == int: print(3) else: mass = [] while len(nodes.keys()) != 0: # print(type(nodes.keys())) i = list(nodes.keys())[0] if len(nodes[i].edges) != 0: first_v = i second_v = nodes[first_v].edges.pop() nodes[second_v].edges.remove(first_v) length = 0 if len(nodes[first_v].edges) == 0: nodes.pop(first_v) elif len(nodes[second_v].edges) == 0: nodes.pop(second_v) else: length = find_short_path(first_v, second_v) if length: mass.append(length + 1) else: nodes.pop(i) if len(mass) != 0: print(min(mass)) else: print(-1) ```
instruction
0
80,014
13
160,028
Yes
output
1
80,014
13
160,029
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` import math n = int(input()) a = list(map(int, input().split())) MAX_A = 10 ** 18 n_bits = math.ceil(math.log(MAX_A, 2)) + 1 if n > n_bits*3: print(3) exit(0) comp = [[] for _ in range(n_bits)] G = {} def add(v): G[v] = set() v2, i = v, 0 while v2 != 0: if v2 % 2 == 1: comp[i].append(v) v2 //= 2 i += 1 for v in a: add(v) for c in comp: if len(c) >= 3: print(3) exit(0) elif len(c) == 2: v, w = c G[v].add(w) G[w].add(v) res = -1 for u in a: level = {v:-1 for v in a} level[u] = 0 l = [u] i = 0 while len(l) > 0 and (res < 0 or 2*i < res): l2 = [] for v in l: for w in G[v]: if level[w] == -1: l2.append(w) level[w] = i+1 elif level[w] >= i: res = min(res, i+1+level[w]) if res > 0 else i+1+level[w] l = l2 i += 1 print(res) ```
instruction
0
80,015
13
160,030
No
output
1
80,015
13
160,031
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` n=int(input()) x=list(map(int,input().split())) ansar=0 z=[0] ma=n for i in range(n): d=0 while x[i]>0: d+=x[i]%2 x[i]=x[i]//2 if(d==0): z.append(i) for j in range(len(z)-1): if(z[j+1]-z[j]<ma): ma=z[j+1]-z[j] if(ma>0): print(ma) if(ma==0): print(-1) ```
instruction
0
80,016
13
160,032
No
output
1
80,016
13
160,033
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` import sys import math lines = sys.stdin.read().split("\n") lines.pop(-1) n = int(lines[0].strip()) nodos_int = [ int(x) for x in lines[1].strip().split(" ")] nodos = [ "{0:b}".format(int(x)).zfill(60) for x in nodos_int] final = set() [print(x) for x in nodos] for bit in range(60): t = [] count=0 for index in range(n): if nodos[index][bit] == '1': t.append(index) count+=1 if count == 2: if t[1] in final and t[0] in final: break final.add(t[0]) final.add(t[1]) final_check = False for i in range(n): if nodos_int[i] & nodos_int[-1] and not nodos_int[i] == nodos_int[-1] : final_check = True if final_check: print(len(final)) else: print(-1) ```
instruction
0
80,017
13
160,034
No
output
1
80,017
13
160,035
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all. Input The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}). Output If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle. Examples Input 4 3 6 28 9 Output 4 Input 5 5 12 9 16 48 Output 3 Input 4 1 2 4 8 Output -1 Note In the first example, the shortest cycle is (9, 3, 6, 28). In the second example, the shortest cycle is (5, 12, 9). The graph has no cycles in the third example. Submitted Solution: ``` #def dfs function k andar #st.append kaam kar raha....lekin...st = st+[j] #kaam nhi kr rha def dfs(j) : visit[j] =1 for i in (gr[j]) : if (visit[i] == 0) : dfs(i) #print(j) st.append(j) def dfss(j , ans) : global maxx maxx = max(maxx , ans) visit[j] =1 for i in (gr[j]) : if (visit[i] == 0) : dfss(i , ans+1) #print(j) #st.append(j) def printt (p) : for i in p : print(*i) I = lambda : map(int,input().split()) st = [] n = int(input()) li = list(I()) dp = [ [0]*64 for i in range (n)] for i,j in enumerate(li) : temp = j c= 0 while temp : t = temp%2 temp = temp//2 dp[i][c] = t c+=1 '''for i in dp : print(*i)''' gr = [ [] for i in range (n) ] c = 0 for i in dp : d = {} for j in range (10) : if dp[c][j] == 1 : for k in range (n) : if k == c : continue if dp[k][j] == 1 : if k not in d : d[k] = 1 for j in d : gr[c] += [j] #print(d,c) c += 1 #print(gr) gr1 =[ [] for i in range (n)] for i,j in enumerate(gr) : for p in gr[i] : gr1[p] += [i] #print(gr) visit =[ 0 for i in range (n)] for i in range (n) : if (visit[i] == 0) : dfs(i) #print(st) maxx = 1 visit =[ 0 for i in range (n)] while len(st) : i = st.pop() if (visit[i] == 0) : ans = 0 dfss(i , ans+1) if maxx == 1 : exit(print("-1")) print(maxx) ```
instruction
0
80,018
13
160,036
No
output
1
80,018
13
160,037
Provide tags and a correct Python 3 solution for this coding contest problem. Boboniu has a directed graph with n vertices and m edges. The out-degree of each vertex is at most k. Each edge has an integer weight between 1 and m. No two edges have equal weights. Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u. Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that * 1≤ c_i≤ i for all i (1≤ i≤ k). * Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules. Input The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9). Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself. It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight. Output Print one integer: the number of tuples. Examples Input 4 6 3 4 2 1 1 2 2 2 4 3 4 1 4 4 3 5 3 1 6 Output 2 Input 5 5 1 1 4 1 5 1 2 2 5 3 4 3 4 3 2 5 Output 1 Input 6 13 4 3 5 1 2 5 2 6 3 3 1 4 4 2 6 5 5 3 6 4 1 7 4 3 8 5 2 9 4 2 10 2 1 11 6 1 12 4 6 13 Output 1 Note For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through. <image> For the third example, there's only one tuple: (1,2,2,2). <image> The out-degree of vertex u means the number of edges outgoing from u.
instruction
0
80,119
13
160,238
Tags: brute force, dfs and similar, graphs, hashing Correct Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip() N, M, K = map(int, input().split()) IN = [[] for _ in range(N)] OUT = [[] for _ in range(N)] t, m = 12345, (1 << 30) - 1 HASH = [] # s = 987654321 s = 97531 H = 0 for _ in range(N): s = (s * 17 + t) & m HASH.append(s) H ^= s for _ in range(M): u, v, w = map(int, input().split()) u, v = u-1, v-1 OUT[u].append((v, w)) X = [[0] * (i+2) for i in range(K+1)] for i in range(N): c = len(OUT[i]) for j, (v, w) in enumerate(sorted(OUT[i], key = lambda x: x[1])): X[c-1][j] ^= HASH[v] Y = [[x[j] ^ x[j+1] for j in range(i+1)] for i, x in enumerate(X)] s = 0 for i in range(K): s ^= X[i][0] X[0][0] = 0 ans = 0 A = [0] * (K + 1) f = 1 while f: if s == H: ans += 1 s ^= Y[1][A[1]] A[1] += 1 a = 1 while A[a] == a + 1: s ^= X[a][0] A[a] = 0 a += 1 if a >= K: f = 0 break s ^= Y[a][A[a]] A[a] += 1 print(ans if K > 1 else min(ans, 1)) ```
output
1
80,119
13
160,239
Provide tags and a correct Python 3 solution for this coding contest problem. Boboniu has a directed graph with n vertices and m edges. The out-degree of each vertex is at most k. Each edge has an integer weight between 1 and m. No two edges have equal weights. Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u. Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that * 1≤ c_i≤ i for all i (1≤ i≤ k). * Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules. Input The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9). Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself. It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight. Output Print one integer: the number of tuples. Examples Input 4 6 3 4 2 1 1 2 2 2 4 3 4 1 4 4 3 5 3 1 6 Output 2 Input 5 5 1 1 4 1 5 1 2 2 5 3 4 3 4 3 2 5 Output 1 Input 6 13 4 3 5 1 2 5 2 6 3 3 1 4 4 2 6 5 5 3 6 4 1 7 4 3 8 5 2 9 4 2 10 2 1 11 6 1 12 4 6 13 Output 1 Note For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through. <image> For the third example, there's only one tuple: (1,2,2,2). <image> The out-degree of vertex u means the number of edges outgoing from u.
instruction
0
80,120
13
160,240
Tags: brute force, dfs and similar, graphs, hashing Correct Solution: ``` import copy from itertools import permutations from collections import defaultdict import sys import io import os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def main(): n, m, k = map(int, input().split()) out = [[] for _ in range(n)] for _ in range(m): u, v, w = map(int, input().split()) u -= 1 v -= 1 out[u].append((w, v)) inc = [set() for _ in range(n)] forbidden = set() for u in range(n): for i, (_, v) in enumerate(sorted(out[u]), start=1): if (len(out[u]), i) in inc[v]: forbidden.add((len(out[u]), i)) else: inc[v].add((len(out[u]), i)) forbidden_follow = defaultdict(set) for v in range(n): for (c1, v1), (c2, v2) in permutations(inc[v], 2): if c1 < c2: forbidden_follow[(c1, v1)].add((c2, v2)) total = 0 cur_forbidden = set() def solve(cur_k): nonlocal k, total, forbidden, cur_forbidden if cur_k == k+1: total += 1 return for val in range(1, cur_k+1): if (cur_k, val) in forbidden or (cur_k, val) in cur_forbidden: continue old = copy.copy(cur_forbidden) cur_forbidden.update(forbidden_follow[(cur_k, val)]) solve(cur_k+1) cur_forbidden = old solve(1) print(total) main() ```
output
1
80,120
13
160,241
Provide tags and a correct Python 3 solution for this coding contest problem. Boboniu has a directed graph with n vertices and m edges. The out-degree of each vertex is at most k. Each edge has an integer weight between 1 and m. No two edges have equal weights. Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u. Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that * 1≤ c_i≤ i for all i (1≤ i≤ k). * Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules. Input The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9). Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself. It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight. Output Print one integer: the number of tuples. Examples Input 4 6 3 4 2 1 1 2 2 2 4 3 4 1 4 4 3 5 3 1 6 Output 2 Input 5 5 1 1 4 1 5 1 2 2 5 3 4 3 4 3 2 5 Output 1 Input 6 13 4 3 5 1 2 5 2 6 3 3 1 4 4 2 6 5 5 3 6 4 1 7 4 3 8 5 2 9 4 2 10 2 1 11 6 1 12 4 6 13 Output 1 Note For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through. <image> For the third example, there's only one tuple: (1,2,2,2). <image> The out-degree of vertex u means the number of edges outgoing from u.
instruction
0
80,121
13
160,242
Tags: brute force, dfs and similar, graphs, hashing Correct Solution: ``` import sys input = sys.stdin.buffer.readline n,m,k = map(int,input().split()) edge = [[] for _ in range(n)] dg = 10**6 MOD = 10**9+7 for _ in range(m): u,v,w = map(int,input().split()) edge[u-1].append(w*dg + v-1) num = [[] for i in range(k+1)] one = set() for i in range(n): num[len(edge[i])].append(i) edge[i].sort() q = [[0]*(k+1) for i in range(k+1)] q2 = [[0]*(k+1) for i in range(k+1)] for i in range(1,k+1): for j in range(i): for e in num[i]: go = edge[e][j]%dg q[i][j] = (q[i][j] + ((go*go*go%MOD + go +122312)%MOD)*1213 + 12316)%MOD q2[i][j] = (q2[i][j] + (go*go+12231312)*1213 + 12316)%MOD cor = 0 cor2 = 0 for i in range(n): cor = (cor + ((i*i*i%MOD + i +122312)%MOD)*1213 + 12316)%MOD cor2 = (cor2 + (i*i+12231312)*1213 + 12316)%MOD fac = 1 for i in range(2,k+1): fac *= i res = 0 for w in range(1,fac+1): tmp = w nxt = 0 nxt2 = 0 tank = [] for r in range(k,0,-1): tmp,c = divmod(tmp,r) tank.append(c) nxt = (nxt + q[r][c])%MOD nxt2 = (nxt2 + q2[r][c])%MOD if nxt == cor and nxt2 == cor2: res += 1 print(res) ```
output
1
80,121
13
160,243
Provide tags and a correct Python 3 solution for this coding contest problem. Boboniu has a directed graph with n vertices and m edges. The out-degree of each vertex is at most k. Each edge has an integer weight between 1 and m. No two edges have equal weights. Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u. Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that * 1≤ c_i≤ i for all i (1≤ i≤ k). * Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules. Input The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9). Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself. It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight. Output Print one integer: the number of tuples. Examples Input 4 6 3 4 2 1 1 2 2 2 4 3 4 1 4 4 3 5 3 1 6 Output 2 Input 5 5 1 1 4 1 5 1 2 2 5 3 4 3 4 3 2 5 Output 1 Input 6 13 4 3 5 1 2 5 2 6 3 3 1 4 4 2 6 5 5 3 6 4 1 7 4 3 8 5 2 9 4 2 10 2 1 11 6 1 12 4 6 13 Output 1 Note For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through. <image> For the third example, there's only one tuple: (1,2,2,2). <image> The out-degree of vertex u means the number of edges outgoing from u.
instruction
0
80,122
13
160,244
Tags: brute force, dfs and similar, graphs, hashing Correct Solution: ``` import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from operator import itemgetter n,m,k=map(int,input().split()) e=[[] for i in range(n+1)] for i in range(m): u,v,w=map(int,input().split()) e[u].append((w,v)) come=[[0 for j in range(10)] for i in range(10)] d=[[0 for j in range(10)] for i in range(10)] hash_=[4343434343439+(10**9+7)*i for i in range(n+1)] h=hash_[0] for i in hash_: h^=i for i in range(1,n+1): e[i].sort(key=itemgetter(0)) l=len(e[i]) for j in range(l): come[l][j]^=hash_[e[i][j][1]] d[l][j]+=1 ans=[0] def dfs(number,l): if number==k+1: c,dx=0,0 for i in range(k): c^=come[i+1][l[i]] dx+=d[i+1][l[i]] if c==h and dx==n: ans[0]+=1 return for i in range(number): dfs(number+1,l+[i]) dfs(1,[]) print(ans[0]) ```
output
1
80,122
13
160,245
Provide tags and a correct Python 3 solution for this coding contest problem. Boboniu has a directed graph with n vertices and m edges. The out-degree of each vertex is at most k. Each edge has an integer weight between 1 and m. No two edges have equal weights. Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u. Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that * 1≤ c_i≤ i for all i (1≤ i≤ k). * Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules. Input The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9). Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself. It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight. Output Print one integer: the number of tuples. Examples Input 4 6 3 4 2 1 1 2 2 2 4 3 4 1 4 4 3 5 3 1 6 Output 2 Input 5 5 1 1 4 1 5 1 2 2 5 3 4 3 4 3 2 5 Output 1 Input 6 13 4 3 5 1 2 5 2 6 3 3 1 4 4 2 6 5 5 3 6 4 1 7 4 3 8 5 2 9 4 2 10 2 1 11 6 1 12 4 6 13 Output 1 Note For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through. <image> For the third example, there's only one tuple: (1,2,2,2). <image> The out-degree of vertex u means the number of edges outgoing from u.
instruction
0
80,123
13
160,246
Tags: brute force, dfs and similar, graphs, hashing Correct Solution: ``` from random import randrange import sys input = sys.stdin.buffer.readline def solve(digit, res): ans = 0 if digit == k: return int(res == zob_all) for i in range(digit + 1): ans += solve(digit + 1, res^zob[digit][i]) return ans n, m, k = map(int, input().split()) edges = [list(map(int, input().split())) for i in range(m)] LIMIT = (1 << 31) - 1 OFFSET = 10 ** 6 graph = [[] for i in range(n)] for u, v, cost in edges: u -= 1 v -= 1 graph[u].append(cost * OFFSET + v) hashes = [randrange(0, LIMIT + 1) for i in range(n)] zob = [[0] * k for i in range(k)] zob_all = 0 for i in range(n): zob_all ^= hashes[i] for v in range(n): deg = len(graph[v]) graph[v] = sorted(graph[v]) for i, tmp in enumerate(graph[v]): nxt_v = tmp % OFFSET zob[deg - 1][i] ^= hashes[nxt_v] print(solve(0, 0)) ```
output
1
80,123
13
160,247