message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects the vertices p_i and q_i. Among the sequences of distinct vertices v_1, v_2, ..., v_M that satisfy the following condition, find the maximum value of M. * For every 1 \leq i < M, the path connecting the vertices v_i and v_{i+1} do not contain any vertex in v, except for v_i and v_{i+1}. Constraints * 2 \leq N \leq 10^5 * 1 \leq p_i, q_i \leq N * The given graph is a tree. Input The input is given from Standard Input in the following format: N p_1 q_1 p_2 q_2 : p_{N-1} q_{N-1} Output Print the maximum value of M, the number of elements, among the sequences of vertices that satisfy the condition. Examples Input 4 1 2 2 3 2 4 Output 3 Input 10 7 9 1 2 6 4 8 1 3 7 6 5 2 10 9 6 2 6 Output 8
instruction
0
12,387
13
24,774
"Correct Solution: ``` import sys readline = sys.stdin.readline readlines = sys.stdin.readlines sys.setrecursionlimit(10 ** 7) """ ・次数3以上の点は使わないとしてよい ・次数1の点は全て回収できる。次数2の点を、パスとなる形で回収する。 """ N = int(readline()) PQ = [tuple(int(x)-1 for x in line.split()) for line in readlines()] graph = [[] for _ in range(N)] for p,q in PQ: graph[p].append(q) graph[q].append(p) deg = [len(x) for x in graph] cnt_deg1 = sum(x==1 for x in deg) deg2_path = 0 def dfs(x,parent): global deg2_path # 部分木で完結する場合、しない場合 arr = [dfs(y,x) for y in graph[x] if y != parent] if len(arr) == 0: return 0 if len(arr) == 1: return arr[0] + (deg[x] == 2) arr.sort() deg2_path = max(deg2_path, arr[-1] + arr[-2] + (deg[x]==2)) return arr[-1] + (deg[x] == 2) dfs(0,-1) answer = cnt_deg1 + deg2_path print(answer) ```
output
1
12,387
13
24,775
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects the vertices p_i and q_i. Among the sequences of distinct vertices v_1, v_2, ..., v_M that satisfy the following condition, find the maximum value of M. * For every 1 \leq i < M, the path connecting the vertices v_i and v_{i+1} do not contain any vertex in v, except for v_i and v_{i+1}. Constraints * 2 \leq N \leq 10^5 * 1 \leq p_i, q_i \leq N * The given graph is a tree. Input The input is given from Standard Input in the following format: N p_1 q_1 p_2 q_2 : p_{N-1} q_{N-1} Output Print the maximum value of M, the number of elements, among the sequences of vertices that satisfy the condition. Examples Input 4 1 2 2 3 2 4 Output 3 Input 10 7 9 1 2 6 4 8 1 3 7 6 5 2 10 9 6 2 6 Output 8 Submitted Solution: ``` #!/usr/bin/env python3 import sys sys.setrecursionlimit(10**8) input = sys.stdin.readline n = int(input()) edge = [[] for i in range(n)] for i in range(n-1): p, q = [int(item) - 1 for item in input().split()] edge[p].append(q) edge[q].append(p) order1 = 0 for e in edge: if len(e) == 1: order1 += 1 max_order = 0 def dfs(v, prev): global max_order if len(edge[v]) == 1: return 0 order2 = 0 od = [] for nv in edge[v]: if nv == prev: continue ret = dfs(nv, v) od.append(ret) order2 = max(order2, ret) od.sort(reverse=True) if len(edge[v]) == 2: order2 += 1 if len(od) > 1: max_order = max(max_order, od[0] + od[1] + 1) elif len(edge[v]) > 2: max_order = max(max_order, od[0] + od[1]) return order2 ret = dfs(0, -1) print(order1 + max_order) ```
instruction
0
12,388
13
24,776
No
output
1
12,388
13
24,777
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects the vertices p_i and q_i. Among the sequences of distinct vertices v_1, v_2, ..., v_M that satisfy the following condition, find the maximum value of M. * For every 1 \leq i < M, the path connecting the vertices v_i and v_{i+1} do not contain any vertex in v, except for v_i and v_{i+1}. Constraints * 2 \leq N \leq 10^5 * 1 \leq p_i, q_i \leq N * The given graph is a tree. Input The input is given from Standard Input in the following format: N p_1 q_1 p_2 q_2 : p_{N-1} q_{N-1} Output Print the maximum value of M, the number of elements, among the sequences of vertices that satisfy the condition. Examples Input 4 1 2 2 3 2 4 Output 3 Input 10 7 9 1 2 6 4 8 1 3 7 6 5 2 10 9 6 2 6 Output 8 Submitted Solution: ``` #!/usr/bin/env python3 import sys sys.setrecursionlimit(10**8) input = sys.stdin.readline n = int(input()) edge = [[] for i in range(n)] for i in range(n-1): p, q = [int(item) - 1 for item in input().split()] edge[p].append(q) edge[q].append(p) order1 = 0 for e in edge: if len(e) == 1: order1 += 1 def dfs(v, prev): if len(edge[v]) == 1: return 0 order2 = 0 for nv in edge[v]: if nv == prev: continue order2 = max(order2, dfs(nv, v)) if len(edge[v]) == 2: order2 += 1 return order2 ret = dfs(0, -1) print(order1 + ret) ```
instruction
0
12,389
13
24,778
No
output
1
12,389
13
24,779
Provide a correct Python 3 solution for this coding contest problem. Problem statement Modulo is very good at drawing trees. Over the years, Modulo has drawn a picture of a tree with $ N $ vertices. The vertices of this tree are numbered from $ 1 $ to $ N $, and the vertices $ a_i $ and $ b_i $$ (1 \ leq i \ leq N-1) $ are directly connected by edges. All vertices are not yet painted. This wooden painting by Mr. Modulo impressed many people and was decided to be displayed in a famous museum. This museum is visited by $ N $ people in turn. Modulo decided to give each person a $ 1 $ copy of the wood painting as a bonus for the visitors. In addition, to satisfy the visitors, we decided to paint all the vertices of the tree paintings to be distributed. Visitors to the $ k $ th $ (1 \ leq k \ leq N) $ will only be satisfied if a picture that meets both of the following two conditions is distributed. * Any two vertices whose shortest distance is a multiple of $ k $ are painted in the same color. * Any two vertices whose shortest distance is not a multiple of $ k $ are painted in different colors. Modulo has an infinite number of colors. Also, each copy may be painted differently. For each visitor, determine if you can paint the vertices to satisfy them. Constraint * $ 1 \ leq N \ leq 10 ^ 5 $ * $ 1 \ leq a_i, b_i \ leq N $ * All inputs are integers * It is guaranteed that the graph given by the input is a tree. * * * input Input is given from standard input in the following format. $ N $ $ a_1 $ $ b_1 $ $ a_2 $ $ b_2 $ $ \ vdots $ $ a_ {N-1} $ $ b_ {N-1} $ * The $ 1 $ line is given the integer $ N $, which represents the number of vertices in the tree. * From the $ 2 $ line to the $ N $ line, information on the edges of the tree is given. Of these, the $ i + 1 (1 \ leq i \ leq N-1) $ line is given two integers $ a_i, b_i $ indicating that the vertices $ a_i $ and $ b_i $ are connected by edges. Be done. output Output the string $ S = s_1 s_2 \ ldots s_N $ consisting of `0` or` 1` that satisfies the following. * $ s_k = 1 $: $ k $ Can be colored at the top of a given tree picture to satisfy the third visitor * $ s_k = 0 $: $ k $ Cannot color the vertices of a given tree picture to satisfy the third visitor * * * Input example 1 7 13 twenty three 3 4 4 5 4 6 6 7 Output example 1 1100111 The tree of input example 1 is as shown in the figure below. sample_picture_1_0 For example, when $ k = 2 $, the condition is satisfied by painting as follows. sample_picture_1_2 Also, when $ k = 5 $, the condition is satisfied by painting as follows. sample_picture_1_1 * * * Input example 2 6 1 2 twenty three 3 4 4 5 5 6 Output example 2 111111 * * * Input example 3 1 Output example 3 1 Example Input 7 1 3 2 3 3 4 4 5 4 6 6 7 Output 1100111
instruction
0
12,451
13
24,902
"Correct Solution: ``` import sys from collections import deque readline = sys.stdin.readline def parorder(Edge, p): N = len(Edge) par = [0]*N par[p] = -1 stack = [p] order = [] visited = set([p]) ast = stack.append apo = order.append while stack: vn = stack.pop() apo(vn) for vf in Edge[vn]: if vf in visited: continue visited.add(vf) par[vf] = vn ast(vf) return par, order def getcld(p): res = [[] for _ in range(len(p))] for i, v in enumerate(p[1:], 1): res[v].append(i) return res def bfs(s): Q = deque(s) used = set(s) dist = [0]*N while Q: vn = Q.pop() for vf in Edge[vn]: if vf not in used: used.add(vf) dist[vf] = 1 + dist[vn] Q.appendleft(vf) return dist N = int(readline()) Edge = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, readline().split()) a -= 1 b -= 1 Edge[a].append(b) Edge[b].append(a) dist0 = bfs([0]) st = dist0.index(max(dist0)) dists = bfs([st]) en = dists.index(max(dists)) diste = bfs([en]) D = dists[en] path = [i for i in range(N) if dists[i] + diste[i] == D] distp = bfs(path) table = [1]*(N+5) mini = 0 for i in range(N): if distp[i] == 0: continue fi = dists[i] if 2*distp[i] == fi: mini = max(mini, fi-1) else: mini = max(mini, fi) fi = diste[i] if 2*distp[i] == fi: mini = max(mini, fi-1) else: mini = max(mini, fi) for i in range(mini+1): table[i] = 0 table[1] = 1 table[2] = 1 for i in range(D+1, N+1): table[i] = 1 print(''.join(map(str, table[1:N+1]))) ```
output
1
12,451
13
24,903
Provide a correct Python 3 solution for this coding contest problem. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2
instruction
0
12,452
13
24,904
"Correct Solution: ``` # -*- coding: utf-8 -*- import sys sys.setrecursionlimit(1000000) class weightRtree: def __init__(self, num): self.num = num self.weight = [0] * (num+1) def add(self, v, w): if v == 0: return 0 while v <= self.num: self.weight[v] += w v += (-v) & v def getSum(self, u): temp = 0 while u > 0: temp += self.weight[u] u -= (-u) & u return temp N = int(input()) left = [0] * N right = [0] * N Tree = [set(map(int, input().split()[1:])) for i in range(N)] def DFS(count, source): count += 1 left[source] = count for item in Tree[source]: count = DFS(count, item) count += 1 right[source] = count return count Object = weightRtree(DFS(1, 0)) Q = int(input()) for i in range(Q): alist = list(map(int, input().split())) if not alist[0]: Object.add(left[alist[1]], alist[2]) Object.add(right[alist[1]], -alist[2]) else: print(Object.getSum(right[alist[1]] - 1)) ```
output
1
12,452
13
24,905
Provide a correct Python 3 solution for this coding contest problem. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2
instruction
0
12,453
13
24,906
"Correct Solution: ``` import sys sys.setrecursionlimit(200000) class BIT(object): def __init__(self, n: int) -> None: self.n = n self.data = [0] * (n + 1) def get_sum(self, i: int) -> int: ret = 0 while i > 0: ret += self.data[i] i -= (i & -i) return ret def add(self, i: int, w: int) -> None: if i == 0: return while i <= self.n: self.data[i] += w i += (i & -i) def dfs(u: int, cnt: int) -> int: global left, right cnt += 1 left[u] = cnt for c in tree[u]: cnt = dfs(c, cnt) cnt += 1 right[u] = cnt return cnt if __name__ == "__main__": n = int(input()) left, right = [0] * n, [0] * n tree = [] for _ in range(n): _, *children = map(lambda x: int(x), input().split()) tree.append(set(children)) bit = BIT(dfs(0, 1)) q = int(input()) for _ in range(q): query = list(map(lambda x: int(x), input().split())) if query[0]: print(bit.get_sum(right[query[1]] - 1)) else: bit.add(left[query[1]], query[2]) bit.add(right[query[1]], -query[2]) ```
output
1
12,453
13
24,907
Provide a correct Python 3 solution for this coding contest problem. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2
instruction
0
12,454
13
24,908
"Correct Solution: ``` import sys sys.setrecursionlimit(1000000) # The class of range query on a Tree class RQT: # The initialization of node def __init__(self, num): self.num = num self.weight = [0] * (num + 1) # weight add operation def add(self, v, w): if v == 0: return 0 while v <= self.num: self.weight[v] += w v += (-v) & v # weight sum operation def getSum(self, u): temp = 0 while u > 0: temp += self.weight[u] u -= (-u) & u return temp N = int(input()) left = [0] * N right = [0] * N # use set to construct the tree Tree = [set(map(int, input().split()[1:])) for i in range(N)] # use DFS to search the target node def DFS(count, source): count += 1 left[source] = count for item in Tree[source]: count = DFS(count, item) count += 1 right[source] = count return count Object = RQT(DFS(1, 0)) # read the operation code Q = int(input()) for i in range(Q): alist = list(map(int, input().split())) if not alist[0]: Object.add(left[alist[1]], alist[2]) Object.add(right[alist[1]], -alist[2]) else: print(Object.getSum(right[alist[1]] - 1)) ```
output
1
12,454
13
24,909
Provide a correct Python 3 solution for this coding contest problem. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2
instruction
0
12,455
13
24,910
"Correct Solution: ``` #!/usr/bin/env python3 # GRL_5_D: Tree - Range Query on Tree # Eular Tour Technique # DFSの結果でサブツリーの範囲がわかるので、range add queryを利用して # add/getを行う 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 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 class RAQ: """Segment Tree """ def __init__(self, n, initial=0): size = 1 while size < n: size *= 2 self.size = 2*size - 1 self.data = [initial] * self.size def add(self, i, j, v): def _add(r, lo, hi): if hi < i or lo > j: return elif i <= lo and hi <= j: self.data[r] += v else: mid = lo + (hi - lo)//2 _add(r*2 + 1, lo, mid) _add(r*2 + 2, mid+1, hi) return _add(0, 0, self.size//2) def get(self, i): def _get(r, lo, hi, v): v += self.data[r] if lo == hi: return v mid = lo + (hi - lo)//2 if mid >= i: return _get(r*2 + 1, lo, mid, v) else: return _get(r*2 + 2, mid+1, hi, v) return _get(0, 0, self.size//2, 0) class PathSum: def __init__(self, graph, root): self.seg = RAQ(graph.v) self._in = [0] * graph.v self._out = [0] * graph.v self.dfs(graph, root) def dfs(self, graph, root): visited = [False] * graph.v stack = [root] i = 0 while stack: v = stack.pop() if not visited[v]: visited[v] = True self._in[v] = i i += 1 stack.append(v) for e in graph.adj(v): w = e.other(v) if not visited[w]: stack.append(w) else: self._out[v] = i - 1 def add(self, v, val): i = self._in[v] j = self._out[v] self.seg.add(i, j, val) def get(self, v): return self.seg.get(self._in[v]) def run(): n = int(input()) g = Graph(n) for i in range(n): k, *cs = [int(i) for i in input().split()] if k > 0: for j in cs: g.add(Edge(i, j)) raq = PathSum(g, 0) q = int(input()) for _ in range(q): com, *args = [int(i) for i in input().split()] if com == 0: u, val = args raq.add(u, val) elif com == 1: u, = args print(raq.get(u)) else: raise ValueError('invalid command') if __name__ == '__main__': run() ```
output
1
12,455
13
24,911
Provide a correct Python 3 solution for this coding contest problem. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2
instruction
0
12,456
13
24,912
"Correct Solution: ``` #!/usr/bin/env python3 # GRL_5_D: Tree - Range Query on 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 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 class RAQ: """Segment Tree """ def __init__(self, n, initial=0): size = 1 while size < n: size *= 2 self.size = 2*size - 1 self.data = [initial] * self.size def add(self, i, j, v): def _add(r, lo, hi): if i <= lo and hi <= j: data[r] += v elif i <= hi and lo <= j: mid = lo + (hi - lo)//2 _add(r*2 + 1, lo, mid) _add(r*2 + 2, mid+1, hi) data = self.data return _add(0, 0, self.size//2) def get(self, i): def _get(r, lo, hi, v): v += self.data[r] if lo == hi: return v mid = lo + (hi - lo)//2 if mid >= i: return _get(r*2 + 1, lo, mid, v) else: return _get(r*2 + 2, mid+1, hi, v) return _get(0, 0, self.size//2, 0) class PathSum: def __init__(self, graph, root): self.seg = RAQ(graph.v) self._dfs(graph, root) def _dfs(self, graph, root): visited = [False] * graph.v pos = [None] * graph.v stack = [root] n = 0 ns = [] while stack: v = stack.pop() if not visited[v]: visited[v] = True ns.append(n) n += 1 stack.append(v) for e in graph.adj(v): w = e.other(v) if not visited[w]: stack.append(w) else: pos[v] = (ns.pop(), n - 1) self._pos = pos def add(self, v, val): i, j = self._pos[v] self.seg.add(i, j, val) def get(self, v): return self.seg.get(self._pos[v][0]) def run(): n = int(input()) g = Graph(n) for i in range(n): k, *cs = [int(i) for i in input().split()] if k > 0: for j in cs: g.add(Edge(i, j)) raq = PathSum(g, 0) q = int(input()) for _ in range(q): com, *args = [int(i) for i in input().split()] if com == 0: u, val = args raq.add(u, val) elif com == 1: u, = args print(raq.get(u)) else: raise ValueError('invalid command') if __name__ == '__main__': run() ```
output
1
12,456
13
24,913
Provide a correct Python 3 solution for this coding contest problem. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2
instruction
0
12,457
13
24,914
"Correct Solution: ``` import sys sys.setrecursionlimit(int(1e6)) class BIT: def __init__(self, n): self.n = n self.data = [0] * (n + 1) def get_sum(self, i): ret = 0 while i > 0: ret += self.data[i] i -= (i & -i) return ret def add(self, i, w): if i == 0: return while i <= self.n: self.data[i] += w i += (i & -i) def dfs(u, cnt): cnt += 1 l[u] = cnt for c in tree[u]: cnt = dfs(c, cnt) cnt += 1 r[u] = cnt return cnt n = int(input()) l, r = [0] * n, [0] * n tree = [set(map(int, input().split()[1:])) for _ in range(n)] bit = BIT(dfs(0, 1)) q = int(input()) for _ in range(q): line = list(map(int, input().split())) if line[0]: print(bit.get_sum(r[line[1]] - 1)) else: bit.add(l[line[1]], line[2]) bit.add(r[line[1]], -line[2]) ```
output
1
12,457
13
24,915
Provide a correct Python 3 solution for this coding contest problem. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2
instruction
0
12,458
13
24,916
"Correct Solution: ``` from collections import deque import sys sys.setrecursionlimit(10**6) readline = sys.stdin.readline write = sys.stdout.write N = int(readline()) G = [None]*N for i in range(N): k, *c = map(int, readline().split()) G[i] = c H = [0]*N prv = [None]*N def dfs(v): s = 1; heavy = None; m = 0 for w in G[v]: prv[w] = v c = dfs(w) if m < c: heavy = w m = c s += c H[v] = heavy return s dfs(0) SS = [] D = [] L = [0]*N I = [0]*N que = deque([(0, 0)]) while que: v, d = que.popleft() S = [] k = len(SS) while v is not None: I[v] = len(S) S.append(v) L[v] = k h = H[v] for w in G[v]: if h == w: continue que.append((w, d+1)) v = h SS.append(S) D.append(d) C = list(map(len, SS)) DS = [[0]*(c+1) for c in C] def add(K, data, k, x): while k <= K: data[k] += x k += k & -k def get(K, data, k): s = 0 while k: s += data[k] k -= k & -k return s def query_add(v, x): l = L[v] add(C[l], DS[l], I[v]+1, x) v = prv[SS[l][0]] def query_sum(v): s = 0 while v is not None: l = L[v] s += get(C[l], DS[l], I[v]+1) v = prv[SS[l][0]] return s Q = int(readline()) ans = [] for q in range(Q): t, *cmd = map(int, readline().split()) if t: ans.append(str(query_sum(cmd[0]))) else: v, w = cmd query_add(v, w) write("\n".join(ans)) write("\n") ```
output
1
12,458
13
24,917
Provide a correct Python 3 solution for this coding contest problem. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2
instruction
0
12,459
13
24,918
"Correct Solution: ``` import sys sys.setrecursionlimit(int(1e6)) class B_I_T: def __init__(self, n): self.n = n self.data = [0] * (n + 1) def get_sum(self, i): ret = 0 while i > 0: ret += self.data[i] i -= (i & -i) return ret def add(self, i, w): if i == 0: return while i <= self.n: self.data[i] += w i += (i & -i) def dfs(u, cnt): cnt += 1 l[u] = cnt for c in tree[u]: cnt = dfs(c, cnt) cnt += 1 r[u] = cnt return cnt n = int(input()) l, r = [0] * n, [0] * n tree = [set(map(int, input().split()[1:])) for _ in range(n)] bit = B_I_T(dfs(0, 1)) q = int(input()) for _ in range(q): line = list(map(int, input().split())) if line[0]: print(bit.get_sum(r[line[1]] - 1)) else: bit.add(l[line[1]], line[2]) bit.add(r[line[1]], -line[2]) ```
output
1
12,459
13
24,919
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2 Submitted Solution: ``` #!/usr/bin/env python3 # GRL_5_D: Tree - Range Query on 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 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 class RAQ: """Segment Tree """ def __init__(self, n, initial=0): size = 1 while size < n: size *= 2 self.size = 2*size - 1 self.data = [initial] * self.size def add(self, i, j, v): def _add(r, lo, hi): if hi < i or lo > j: return elif i <= lo and hi <= j: self.data[r] += v else: mid = lo + (hi - lo)//2 _add(r*2 + 1, lo, mid) _add(r*2 + 2, mid+1, hi) return _add(0, 0, self.size//2) def get(self, i): def _get(r, lo, hi, v): v += self.data[r] if lo == hi: return v mid = lo + (hi - lo)//2 if mid >= i: return _get(r*2 + 1, lo, mid, v) else: return _get(r*2 + 2, mid+1, hi, v) return _get(0, 0, self.size//2, 0) class PathSum: def __init__(self, graph, root): self.seg = RAQ(graph.v * 2) self._in = [0] * graph.v self._out = [0] * graph.v self.dfs(graph, root) def dfs(self, graph, root): visited = [False] * graph.v stack = [root] i = 0 while stack: v = stack.pop() if not visited[v]: visited[v] = True self._in[v] = i i += 1 stack.append(v) for e in graph.adj(v): w = e.other(v) if not visited[w]: stack.append(w) else: self._out[v] = i i += 1 def add(self, v, val): i = self._in[v] j = self._out[v] self.seg.add(i, j, val) def get(self, v): return self.seg.get(self._in[v]) def run(): n = int(input()) g = Graph(n) for i in range(n): k, *cs = [int(i) for i in input().split()] if k > 0: for j in cs: g.add(Edge(i, j)) raq = PathSum(g, 0) q = int(input()) for _ in range(q): com, *args = [int(i) for i in input().split()] if com == 0: u, val = args raq.add(u, val) elif com == 1: u, = args print(raq.get(u)) else: raise ValueError('invalid command') if __name__ == '__main__': run() ```
instruction
0
12,460
13
24,920
Yes
output
1
12,460
13
24,921
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2 Submitted Solution: ``` N = 10 ** 5 prt = [0] * (N + 1) left = [-1] + [0] * N right = [-1] + [0] * N sz = [0] + [1] * N key = [0] * (N + 1) val = [0] * (N + 1) rev = [0] * (N + 1) def update(i, l, r): # assert 1 <= i <= N sz[i] = 1 + sz[l] + sz[r] val[i] = key[i] + val[l] + val[r] def swap(i): if i: left[i], right[i] = right[i], left[i] rev[i] ^= 1 def prop(i): swap(left[i]) swap(right[i]) rev[i] = 0 return 1 def splay(i): # assert 1 <= i <= N x = prt[i] rev[i] and prop(i) li = left[i]; ri = right[i] while x and not left[x] != i != right[x]: y = prt[x] if not y or left[y] != x != right[y]: if rev[x] and prop(x): li, ri = ri, li swap(li); swap(ri) if left[x] == i: left[x] = ri prt[ri] = x update(x, ri, right[x]) ri = x else: right[x] = li prt[li] = x update(x, left[x], li) li = x x = y break rev[y] and prop(y) if rev[x] and prop(x): li, ri = ri, li swap(li); swap(ri) z = prt[y] if left[y] == x: if left[x] == i: v = left[y] = right[x] prt[v] = y update(y, v, right[y]) left[x] = ri; right[x] = y prt[ri] = x update(x, ri, y) prt[y] = ri = x else: left[y] = ri prt[ri] = y update(y, ri, right[y]) right[x] = li prt[li] = x update(x, left[x], li) li = x; ri = y else: if right[x] == i: v = right[y] = left[x] prt[v] = y update(y, left[y], v) left[x] = y; right[x] = li prt[li] = x update(x, y, li) prt[y] = li = x else: right[y] = li prt[li] = y update(y, left[y], li) left[x] = ri prt[ri] = x update(x, ri, right[x]) li = y; ri = x x = z if left[z] == y: left[z] = i update(z, i, right[z]) elif right[z] == y: right[z] = i update(z, left[z], i) else: break update(i, li, ri) left[i] = li; right[i] = ri prt[li] = prt[ri] = i prt[i] = x rev[i] = prt[0] = 0 def expose(i): p = 0 cur = i while cur: splay(cur) right[cur] = p update(cur, left[cur], p) p = cur cur = prt[cur] splay(i) return i def cut(i): expose(i) p = left[i] left[i] = prt[p] = 0 return p def link(i, p): expose(i) expose(p) prt[i] = p right[p] = i def evert(i): expose(i) swap(i) rev[i] and prop(i) def query(v): r = expose(v + 1) return val[r] def query_add(v, w): key[v + 1] += w expose(v + 1) readline = open(0).readline writelines = open(1, 'w').writelines N = int(readline()) for i in range(N): k, *C = map(int, readline().split()) # for c in C: # link(c+1, i+1) if k: expose(i + 1) for c in C: expose(c + 1) prt[c + 1] = i + 1 right[i + 1] = C[0] + 1 Q = int(readline()) ans = [] for q in range(Q): t, *args = map(int, readline().split()) if t: ans.append("%d\n" % query(args[0])) else: query_add(*args) writelines(ans) ```
instruction
0
12,461
13
24,922
Yes
output
1
12,461
13
24,923
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2 Submitted Solution: ``` class Tree(): def __init__(self, n, edge): self.n = n self.tree = [[] for _ in range(n)] for e in edge: self.tree[e[0] - 1].append(e[1] - 1) self.tree[e[1] - 1].append(e[0] - 1) 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.order = [] self.order.append(root) self.size = [1 for _ in range(self.n)] stack = [root] while stack: node = stack.pop() for adj in self.tree[node]: if self.parent[adj] is None: self.parent[adj] = node self.depth[adj] = self.depth[node] + 1 self.order.append(adj) stack.append(adj) for node in self.order[::-1]: for adj in self.tree[node]: if self.parent[node] == adj: continue self.size[node] += self.size[adj] def heavylight_decomposition(self): self.order = [None for _ in range(self.n)] self.head = [None for _ in range(self.n)] self.head[self.root] = self.root self.next = [None for _ in range(self.n)] stack = [self.root] order = 0 while stack: node = stack.pop() self.order[node] = order order += 1 maxsize = 0 for adj in self.tree[node]: if self.parent[node] == adj: continue if maxsize < self.size[adj]: maxsize = self.size[adj] self.next[node] = adj for adj in self.tree[node]: if self.parent[node] == adj or self.next[node] == adj: continue self.head[adj] = adj stack.append(adj) if self.next[node] is not None: self.head[self.next[node]] = self.head[node] stack.append(self.next[node]) def range_hld(self, u, v, edge=False): res = [] while True: if self.order[u] > self.order[v]: u, v = v, u if self.head[u] != self.head[v]: res.append((self.order[self.head[v]], self.order[v] + 1)) v = self.parent[self.head[v]] else: res.append((self.order[u] + edge, self.order[v] + 1)) return res def subtree_hld(self, u): return self.order[u], self.order[u] + self.size[u] def lca_hld(self, u, v): while True: if self.order[u] > self.order[v]: u, v = v, u if self.head[u] != self.head[v]: v = self.parent[self.head[v]] else: return u class SegmentTree(): def __init__(self, arr, func=min, ie=2**63): self.h = (len(arr) - 1).bit_length() self.n = 2**self.h self.ie = ie self.func = func self.tree = [ie for _ in range(2 * self.n)] for i in range(len(arr)): self.tree[self.n + i] = arr[i] for i in range(1, self.n)[::-1]: self.tree[i] = func(self.tree[2 * i], self.tree[2 * i + 1]) def set(self, idx, x): idx += self.n self.tree[idx] = x while idx: idx >>= 1 self.tree[idx] = self.func(self.tree[2 * idx], self.tree[2 * idx + 1]) def query(self, lt, rt): lt += self.n rt += self.n vl = vr = self.ie while rt - lt > 0: if lt & 1: vl = self.func(vl, self.tree[lt]) lt += 1 if rt & 1: rt -= 1 vr = self.func(self.tree[rt], vr) lt >>= 1 rt >>= 1 return self.func(vl, vr) import sys input = sys.stdin.readline from operator import add N = int(input()) E = [] for i in range(N): k, *c = map(int, input().split()) for j in range(k): E.append((i + 1, c[j] + 1)) t = Tree(N, E) t.setroot(0) t.heavylight_decomposition() st = SegmentTree([0] * N, add, 0) res = [] Q = int(input()) for _ in range(Q): q, *p = map(int, input().split()) if q == 0: v, w = p st.set(t.order[v], st.query(t.order[v], t.order[v] + 1) + w) else: s = 0 u, = p for lt, rt in t.range_hld(0, u, edge=True): s += st.query(lt, rt) res.append(s) print('\n'.join(map(str, res))) ```
instruction
0
12,462
13
24,924
Yes
output
1
12,462
13
24,925
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2 Submitted Solution: ``` # -*- coding: utf-8 -*- class weightRtree: def __init__(self, num): self.num = num self.weight = [0] * (num+1) def add(self, v, w): if v == 0: return 0 while v <= self.num: self.weight[v] += w v += (-v) & v def getSum(self, u): temp = 0 while u > 0: temp += self.weight[u] u -= (-u) & u return temp N = int(input()) left = [0] * N right = [0] * N Tree = [set(map(int, input().split()[1:])) for i in range(N)] def DFS(count, source): count += 1 left[source] = count for item in Tree[source]: count = DFS(count, item) count += 1 right[source] = count return count Object = weightRtree(DFS(1, 0)) Q = int(input()) for i in range(Q): alist = list(map(int, input().split())) if not alist[0]: Object.add(left[alist[1]], alist[2]) Object.add(right[alist[1]], -alist[2]) else: print(Object.getSum(right[alist[1]] - 1)) ```
instruction
0
12,463
13
24,926
No
output
1
12,463
13
24,927
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2 Submitted Solution: ``` # -*- coding: utf-8 -*- class weightRtree: def __init__(self, num): self.num = num self.weight = [0]*(num+1) def add(self, v, w): if v == 0: return 0 while v <= self.num: self.weight[v] += w v += (-v)&v def getSum(self, u): temp = 0 while u > 0: temp += self.weight[u] u -= (-u)&u return temp N = int(input()) left = [0]*N right = [0]*N Tree = [set(map(int, input().split()[1:])) for i in range(N)] def DFS(count, source): count += 1 left[source] = count for item in Tree[source]: count = DFS(count, item) count += 1 right[source] = count return count Object = weightRtree(DFS(1, 0)) Q = int(input()) for i in range(Q): alist = list(map(int, input().split())) if not alist[0]: Object.add(left[alist[1]], alist[2]) Object.add(left[alist[1]], -alist[2]) else: print(Object.getSum(right[alist[1]] - 1)) ```
instruction
0
12,464
13
24,928
No
output
1
12,464
13
24,929
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2 Submitted Solution: ``` # -*- coding: utf-8 -*- N = int(input()) G = [None for i in range(N)] for i in range(N): temp = list(map(int, input().split())) G[i] = temp[1:] INF = 2**31 -1 temp = 1 while temp < N: temp *= 2 lis = [INF for i in range(2*temp-1)] def getSum(x): x += temp-1 w_sum = lis[x] while x > 0: x = (x-1) // 2 w_sum += lis[x] return w_sum def add(a, b, x, k=0, l=0, r=temp): if r <= a or b <= l: return 0 if a <= l and r <= b: lis[k] += x return 0 add(a, b, k*2+1, l, (l+r)//2) add(a, b, k*2+2, (l+r)//2, r) arr = [[0,0] for i in range(200010)] def dfs(k, a=0): arr[0][k] = a a += 1 for i in range(len(G[k])): dfs(G[k][i]) arr[1][k] = a dfs() Q = int(intput()) for i in range(Q): querry = list(map(int, input().split())) if querry[0] == 0: add() else: print(getSum() ```
instruction
0
12,465
13
24,930
No
output
1
12,465
13
24,931
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which manipulates a weighted rooted tree $T$ with the following operations: * $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent * $getSum(u)$: report the sum of weights of all edges from the root to node $u$ The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero. Constraints * All the inputs are given in integers * $ 2 \leq n \leq 100000 $ * $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$ * $ 2 \leq q \leq 200000 $ * $ 1 \leq u,v \leq n-1 $ * $ 1 \leq w \leq 10000 $ Input The input is given in the following format. $n$ $node_0$ $node_1$ $node_2$ $:$ $node_{n-1}$ $q$ $query_1$ $query_2$ $:$ $query_{q}$ The first line of the input includes an integer $n$, the number of nodes in the tree. In the next $n$ lines,the information of node $i$ is given in the following format: ki c1 c2 ... ck $k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$. In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format: 0 v w or 1 u The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$. Output For each $getSum$ query, print the sum in a line. Examples Input 6 2 1 2 2 3 5 0 0 0 1 4 7 1 1 0 3 10 1 2 0 4 20 1 3 0 5 40 1 4 Output 0 0 10 60 Input 4 1 1 1 2 1 3 0 6 0 3 1000 0 2 1000 0 1 1000 1 1 1 2 1 3 Output 1000 2000 3000 Input 2 1 1 0 4 0 1 1 1 1 0 1 1 1 1 Output 1 2 Submitted Solution: ``` # -*- coding: utf-8 -*- N = int(input()) G = [None for i in range(N)] for i in range(N): temp = list(map(int, input().split())) G[i] = temp[1:] INF = 2**31 -1 temp = 1 while temp < N: temp *= 2 lis = [INF for i in range(2*temp-1)] def getSum(x): x += temp-1 w_sum = lis[x] while x > 0: x = (x-1) // 2 w_sum += lis[x] return w_sum def add(a, b, x, k=0, l=0, r=temp): if r <= a or b <= l: return 0 if a <= l and r <= b: lis[k] += x return 0 add(a, b, k*2+1, l, (l+r)//2) add(a, b, k*2+2, (l+r)//2, r) def dfs(k, a=0): arr[0][k] = a a += 1 for i in range(len(G[k])): dfs(G[k][i]) arr[1][k] = a arr = [[0,0] for i in range(200010)] dfs() Q = int(input()) for i in range(Q): querry = list(map(int, input().split())) if querry[0] == 0: add(arr[0][querry[1]], arr[1][querry[1]],w) else: print(getSum(arr[0][querry[1]]) ```
instruction
0
12,466
13
24,932
No
output
1
12,466
13
24,933
Provide tags and a correct Python 3 solution for this coding contest problem. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image>
instruction
0
12,521
13
25,042
Tags: constructive algorithms, greedy, math, number theory Correct Solution: ``` n = int(input()) odp = [] for i in range(n - 1): odp.append([i + 1, i + 2]) odp.append([n, 1]) k = n def prime(x): i = 2 while i ** 2 <= x: if x % i == 0: return False i += 1 return True primes = [0] * 50000 for i in range(50000): primes[i] = (1 if prime(i) else 0) w = (n + 2) // 2 m = 1 while w <= n: if primes[k] == 1: break else: odp.append([m, w]) m += 1 w += 1 k += 1 print(len(odp)) for i in range(len(odp)): print(odp[i][0], odp[i][1]) ```
output
1
12,521
13
25,043
Provide tags and a correct Python 3 solution for this coding contest problem. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image>
instruction
0
12,522
13
25,044
Tags: constructive algorithms, greedy, math, number theory Correct Solution: ``` import sys read = lambda: sys.stdin.readline().strip() readi = lambda: map(int, read().split()) from collections import * n = int(read()) nearestPrime = None for i in range(n, 1010): for j in range(2, int(i**0.5)+1): if i % j == 0: break else: nearestPrime = i break print(nearestPrime) for i in range(1, n): print(i, i+1) print(n, 1) for i in range(1, nearestPrime - n + 1): print(i, n//2 + i) ```
output
1
12,522
13
25,045
Provide tags and a correct Python 3 solution for this coding contest problem. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image>
instruction
0
12,523
13
25,046
Tags: constructive algorithms, greedy, math, number theory Correct Solution: ``` from bisect import * l = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109] z = [1, 2, 5, 6, 9, 10, 13, 14, 17, 18, 21, 22, 25, 26, 29, 30, 33, 34, 37, 38] x = [3, 4, 7, 8, 11, 12, 15, 16, 19, 20, 23, 24, 27, 28, 31, 32, 35, 36, 39, 40] n = int(input()) idx = bisect_left(l,n) rem = l[idx]-n ans = [] for i in range(1,n): ans.append([i,i+1]) ans.append([1,n]) for i in range(1,rem+1): ans.append([z[i-1],x[i-1]]) print(len(ans)) for i in ans: print(*i) ```
output
1
12,523
13
25,047
Provide tags and a correct Python 3 solution for this coding contest problem. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image>
instruction
0
12,524
13
25,048
Tags: constructive algorithms, greedy, math, number theory Correct Solution: ``` prost = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009] n = int(input()) for i in prost: if i>=n: m=i break raz = m-n if n<3: print(-1) elif n==3: print(3) print(1,2) print(2,3) print(1,3) elif n==4: print(5) print(1,2) print(2,3) print(3,4) print(1,4) print(1,3) elif n==5: print(5) print(1,2) print(2,3) print(3,4) print(4,5) print(1,5) elif n==6: print(7) print(1,2) print(2,3) print(3,4) print(4,5) print(5,6) print(6,1) print(2,5) else: print(m) arr = [] for i in range(1,n+1): arr.append(i) if n%4==3: now = arr[:7] arr = arr[7:] for i in range(7): print(now[i],now[(i+1)%7]) if raz>0: print(now[0],now[2]) raz-=1 if raz>0: print(now[3],now[5]) raz-=1 if raz>0: print(now[4],now[6]) raz-=1 n-=7 elif n%4==2: now=arr[:6] arr=arr[6:] for i in range(6): print(now[i],now[(i+1)%6]) if raz>0: print(now[0],now[2]) raz-=1 if raz>0: print(now[3],now[5]) raz-=1 if raz>0: print(now[1],now[4]) raz-=1 n-=6 elif n%4==1: now = arr[:5] arr=arr[5:] for i in range(5): print(now[i],now[(i+1)%5]) if raz>0: print(now[1],now[3]) raz-=1 if raz>0: print(now[2],now[4]) raz-=1 n-=5 while raz>=2: now=arr[:4] arr=arr[4:] for i in range(4): print(now[i],now[(i+1)%4]) print(now[0],now[2]) print(now[1],now[3]) raz-=2 if len(arr)>0: now=arr[:4] arr=arr[4:] for i in range(4): print(now[i],now[(i+1)%4]) if raz>0: print(now[0],now[2]) raz-=1 if raz>0: print(now[1],now[3]) raz-=1 while len(arr)>0: now=arr[:4] arr=arr[4:] for i in range(4): print(now[i],now[(i+1)%4]) ```
output
1
12,524
13
25,049
Provide tags and a correct Python 3 solution for this coding contest problem. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image>
instruction
0
12,525
13
25,050
Tags: constructive algorithms, greedy, math, number theory Correct Solution: ``` import bisect import decimal from decimal import Decimal import os from collections import Counter import bisect from collections import defaultdict import math import random import heapq from math import sqrt import sys from functools import reduce, cmp_to_key from collections import deque import threading from itertools import combinations from io import BytesIO, IOBase from itertools import accumulate from random import randint # sys.setrecursionlimit(200000) # mod = 10**9+7 # mod = 998244353 decimal.getcontext().prec = 46 def primeFactors(n): prime = set() while n % 2 == 0: prime.add(2) n = n//2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: prime.add(i) n = n//i if n > 2: prime.add(n) return list(prime) def getFactors(n) : factors = [] i = 1 while i <= math.sqrt(n): if (n % i == 0) : if (n // i == i) : factors.append(i) else : factors.append(i) factors.append(n//i) i = i + 1 return factors def modefiedSieve(): mx=10**7+1 sieve=[-1]*mx for i in range(2,mx): if sieve[i]==-1: sieve[i]=i for j in range(i*i,mx,i): if sieve[j]==-1: sieve[j]=i return sieve def SieveOfEratosthenes(n): prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 num = [] for p in range(2, n+1): if prime[p]: num.append(p) return num def lcm(a,b): return (a*b)//math.gcd(a,b) def sort_dict(key_value): return sorted(key_value.items(), key = lambda kv:(kv[1], kv[0])) def list_input(): return list(map(int,input().split())) def num_input(): return map(int,input().split()) def string_list(): return list(input()) def decimalToBinary(n): return bin(n).replace("0b", "") def binaryToDecimal(n): return int(n,2) def DFS(n,s,adj): visited = [False for i in range(n+1)] stack = [] stack.append(s) while (len(stack)): s = stack[-1] stack.pop() if (not visited[s]): visited[s] = True for node in adj[s]: if (not visited[node]): stack.append(node) def maxSubArraySum(a,size): maxint = 10**10 max_so_far = -maxint - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True def solve(): n = int(input()) N = n if isPrime(n): print(n) for i in range(n-1): print(i+1,i+2) print(n,1) else: for i in range(n+1,2000): if isPrime(i): n = i break print(n) for i in range(N-1): print(i+1,i+2) print(N,1) u,v = 1,N-1 for i in range(n-N): print(u,v) u += 1 v -= 1 t = 1 #t = int(input()) for _ in range(t): solve() ```
output
1
12,525
13
25,051
Provide tags and a correct Python 3 solution for this coding contest problem. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image>
instruction
0
12,526
13
25,052
Tags: constructive algorithms, greedy, math, number theory Correct Solution: ``` prime=[True]*1501 prime[0]=False prime[1]=False for i in range(2,1501): if prime[i]: for j in range(i*i,1501,i): prime[j]=False n=int(input()) degree=[2]*n ans=[] edges=n for i in range(n-1): ans.append([i+1,i+2]) ans.append([1,n]) c=0 while(not prime[edges]): ans.append([c+1,c+n//2+1]) #print(edges,c,c+n//2) degree[c]+=1 degree[c+n//2]+=1 c+=1 edges+=1 print(len(ans)) for i in ans: print(i[0],i[1]) ```
output
1
12,526
13
25,053
Provide tags and a correct Python 3 solution for this coding contest problem. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image>
instruction
0
12,527
13
25,054
Tags: constructive algorithms, greedy, math, number theory Correct Solution: ``` import math n = int(input()) def isPrime(x): if x in [2, 3, 5, 7]: return True if x == 1: return False for i in range(2, int(math.sqrt(x)) + 1): if x % i == 0: return False return True ans = [] for i in range(1, n): ans.append([i, i + 1]) ans.append([n, 1]) k = 1 if isPrime(n) == False: while True: ans.append([k, k + n // 2]) if isPrime(n + k): break k += 1 print(len(ans)) for x in ans: print(*x) ```
output
1
12,527
13
25,055
Provide tags and a correct Python 3 solution for this coding contest problem. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image>
instruction
0
12,528
13
25,056
Tags: constructive algorithms, greedy, math, number theory Correct Solution: ``` from sys import stdin,stdout,setrecursionlimit from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush,nlargest from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm , accumulate from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction import copy import time setrecursionlimit(10**9) starttime = time.time() mod = int(pow(10, 9) + 7) mod2 = 998244353 # from sys import stdin # input = stdin.readline #def data(): return sys.stdin.readline().strip() def data(): return input() def num():return int(input()) def L(): return list(sp()) def LF(): return list(spf()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def spf(): return map(int, input.readline().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] def pmat(A): for ele in A: print(*ele,end="\n") def pmat2(A): for ele in A: for j in ele: print(j,end='') print() def iseven(n): return n%2==0 def seive(r): prime=[1 for i in range(r+1)] prime[0]=0 prime[1]=0 for i in range(r+1): if(prime[i]): for j in range(2*i,r+1,i): prime[j]=0 return prime #solution #ACPC #remeber cut ribbon problem # set data structures faster than binary search sometimes #bipartite match dfs #think in problems with recursive manner. def isprime(x): if x==2:return True elif x%2==0:return False sq=int(sqrt(x))+1 for i in range(3,sq,2): if x%i==0: return False return True n=int(input());m=n while not isprime(m):m+=1 print(m) print(1,n) for i in range(n-1): print(i+1,i+2) for i in range(m-n): print(i+1,i+1+n//2) endtime = time.time() #print(f"Runtime of the program is {endtime - starttime}") ```
output
1
12,528
13
25,057
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image> Submitted Solution: ``` n = int(input()) def pr(x): for i in range(2, x): if x % i == 0: return False return True e = [] for i in range(n): e += [[i, (i+1) % n]] x = n u = 0 v = n // 2 while not pr(x): e += [[u, v]] x += 1 u += 1 v += 1 print(x) for g in e: print(g[0]+1, g[1]+1) ```
instruction
0
12,529
13
25,058
Yes
output
1
12,529
13
25,059
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image> Submitted Solution: ``` from sys import stdin, stdout, exit huge_p = 998244353 N = 10**6 ps = [True]*N for i in range(2,N): if ps[i]: for k in range(2*i, N, i): ps[k] = False def opp(i): return (i + (n // 2)) % n n = int(input()) for i in range(n//2): if ps[n+i]: stdout.write(str(n+i) + "\n") for j in range(n): stdout.write(str(j+1) + " " + str((j+1)%n + 1) + "\n") for j in range(i): stdout.write(str(j + 1) + " " + str(opp(j) + 1) + "\n") exit() print(-1) ```
instruction
0
12,530
13
25,060
Yes
output
1
12,530
13
25,061
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image> Submitted Solution: ``` line = input() tmp = int(line) def is_prime(x): for i in range(2, x): if x % i == 0: return False return True def find_next_prime(x): x = x + 3 while not is_prime(x): x = x + 1 return x def find_last_prime(x): while not is_prime(x): x = x - 1 return x if tmp == 4: print(5) print('1 2') print('1 3') print('2 3') print('2 4') print('3 4') elif tmp == 6: print(7) print('1 2') print('1 3') print('2 3') print('4 5') print('5 6') print('4 6') print('1 4') elif is_prime(tmp): print(tmp) print(1, tmp) for i in range(1, tmp): print(i, i + 1) else: np = find_next_prime(tmp) m = np-tmp print(np) print(1, m) for i in range(1, m): print(i, i + 1) c = m + 1 print(c, tmp) for i in range(c, tmp): print(i, i + 1) for i in range(m): print(1 + i, 1 + i + m) ```
instruction
0
12,531
13
25,062
Yes
output
1
12,531
13
25,063
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image> Submitted Solution: ``` data = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097] key = int(input()) if key in data: print(key) for each in range(key): print(each % key + 1,(each + 1) % key + 1) else: ans = 0 for each in data: if(each > key): ans = each break print(ans) x = (ans - key) * 2 y = key - x index_start = 1 index_mid = 2 index_end = key flag = [] for each in range(key): flag.append(0) for each_1 in range(key): if(each_1 < x): sub = flag[index_start - 1] for each_2 in range(3 - sub): if(index_start >= index_mid): index_mid = index_start + 1 print(index_start,index_mid) flag[index_start - 1] = flag[index_start - 1] + 1 flag[index_mid - 1] = flag[index_mid - 1] + 1 index_mid = index_mid + 1 if(index_mid > index_end): index_mid = index_start + 1 index_start = index_start + 1 else: sub = flag[index_start - 1] for each_2 in range(2 - sub): if(index_start >= index_mid): index_mid = index_start + 1 print(index_start,index_mid) flag[index_start - 1] = flag[index_start - 1] + 1 flag[index_mid - 1] = flag[index_mid - 1] + 1 index_mid = index_mid + 1 if(index_mid > index_end): index_mid = index_start + 1 index_start = index_start + 1 ```
instruction
0
12,532
13
25,064
Yes
output
1
12,532
13
25,065
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image> Submitted Solution: ``` n = int(input()) arr = [i for i in range(1,n+1)] ans = [] while len(arr)-5>0: a,b,c,d = arr[0],arr[1],arr[2],arr[3] arr = arr[4:] ans.append((a,b)) ans.append((b,c)) ans.append((c,d)) ans.append((d,a)) ans.append((a,c)) if len(arr)==1: print(-1) elif len(arr)<=5: if len(arr)==5: a,b,c,d,e = arr[0],arr[1],arr[2],arr[3],arr[4] ans.append((a,b)) ans.append((b,c)) ans.append((a,c)) ans.append((d,e)) elif len(arr)==4: a,b,c,d = arr[0],arr[1],arr[2],arr[3] ans.append((a,b)) ans.append((b,c)) ans.append((c,d)) ans.append((d,a)) ans.append((a,c)) elif len(arr)==3: a,b,c, = arr[0],arr[1],arr[2] ans.append((a,b)) ans.append((b,c)) ans.append((a,c)) elif len(arr)==2: a,b = arr[0],arr[1] ans.append((a,b)) print(len(ans)) for k in ans: print(" ".join([str(k[0]),str(k[1])])) ```
instruction
0
12,533
13
25,066
No
output
1
12,533
13
25,067
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image> Submitted Solution: ``` import sys input = sys.stdin.readline def isPrime(n): # a prime(except 2 or 3) is of the form 6k-1 or 6k+1 if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 w = 2 sqN = int(pow(n, .5)) while i <= sqN: if n % i == 0: return False i += w w = 6 - w return True n = int(input()) edges = [] for i in range(1, n): edges.append((i, i+1)) edges.append((n, 1)) ind = 1 while not isPrime(n): edges.append((ind, ind+2)) ind = (ind+2)%n + 1 n += 1 print(len(edges)) for edge in edges: print(*edge) ```
instruction
0
12,534
13
25,068
No
output
1
12,534
13
25,069
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image> Submitted Solution: ``` n = int(input()) for i in range(n - 1): print(i + 1, i + 2) print(n, 1) k = n def prime(x): i = 2 while i ** 2 <= x: if x % i == 0: return False i += 1 return True primes = [0] * 50000 for i in range(50000): primes[i] = (1 if prime(i) else 0) w = (n + 1) // 2 m = 1 while w <= n: if primes[k] == 1: break else: print(m, w) m += 1 w += 1 k += 1 ```
instruction
0
12,535
13
25,070
No
output
1
12,535
13
25,071
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to be satisfied: * It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. * The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. * The total number of edges must be prime. * The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. <image> Note that the graph can be disconnected. Please help Bob to find any such graph! Input The input consists of a single integer n (3 ≤ n ≤ 1 000) — the number of vertices. Output If there is no graph satisfying the conditions, print a single line containing the integer -1. Otherwise, first print a line containing a prime number m (2 ≤ m ≤ (n(n-1))/(2)) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 ≤ u_i, v_i ≤ n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected. Examples Input 4 Output 5 1 2 1 3 2 3 2 4 3 4 Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 Note The first example was described in the statement. In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied. <image> Submitted Solution: ``` n=int(input()) ans=[] i=1 if n==3: print(3) print(1,2) print(2,3) print(3,1) exit() while n-4>=4: ans.append([i,i+1]) ans.append([i+1,i+2]) ans.append([i+2,i+3]) ans.append([i+3,i]) ans.append([i+1,i+3]) ans.append([i+2,i+4]) n-=4 i+=4 if n==4: ans.append([i, i + 1]) ans.append([i + 1, i + 2]) ans.append([i + 2, i + 3]) ans.append([i + 3, i]) ans.append([i+1,i+3]) elif n==5: ans.append([i, i + 1]) ans.append([i + 1, i + 2]) ans.append([i + 2, i + 3]) ans.append([i + 3, i]) ans.append([i + 1, i + 3]) ans.append([i,i+4]) ans.append([i+4,i+2]) elif n==6: ans.append([i, i + 1]) ans.append([i + 2, i + 3]) ans.append([i + 3, i]) ans.append([i+1,i+4]) ans.append([i+2,i+4]) ans.append([i,i+5]) ans.append([i+3,i+5]) else: ans.append([i, i + 1]) ans.append([i + 1, i + 2]) ans.append([i + 2, i + 3]) ans.append([i + 3, i]) i+=4 ans.append([i,i+1]) ans.append([i+1,i+2]) ans.append([i+2,i]) print(len(ans)) for i in range(len(ans)): print(*ans[i]) ```
instruction
0
12,536
13
25,072
No
output
1
12,536
13
25,073
Provide tags and a correct Python 3 solution for this coding contest problem. We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem. Given an undirected labeled tree consisting of n vertices, find a set of segments such that: 1. both endpoints of each segment are integers from 1 to 2n, and each integer from 1 to 2n should appear as an endpoint of exactly one segment; 2. all segments are non-degenerate; 3. for each pair (i, j) such that i ≠ j, i ∈ [1, n] and j ∈ [1, n], the vertices i and j are connected with an edge if and only if the segments i and j intersect, but neither segment i is fully contained in segment j, nor segment j is fully contained in segment i. Can you solve this problem too? Input The first line contains one integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of vertices in the tree. Then n - 1 lines follow, each containing two integers x_i and y_i (1 ≤ x_i, y_i ≤ n, x_i ≠ y_i) denoting the endpoints of the i-th edge. It is guaranteed that the given graph is a tree. Output Print n pairs of integers, the i-th pair should contain two integers l_i and r_i (1 ≤ l_i < r_i ≤ 2n) — the endpoints of the i-th segment. All 2n integers you print should be unique. It is guaranteed that the answer always exists. Examples Input 6 1 2 1 3 3 4 3 5 2 6 Output 9 12 7 10 3 11 1 5 2 4 6 8 Input 1 Output 1 2
instruction
0
12,585
13
25,170
Tags: constructive algorithms, dfs and similar, divide and conquer, trees Correct Solution: ``` def main(): import sys input = sys.stdin.buffer.readline N = int(input()) adj = [[] for _ in range(N+1)] for _ in range(N-1): a, b = map(int, input().split()) adj[a].append(b) adj[b].append(a) st = [1] seen = [0] * (N+1) seen[1] = 1 LL = [0] * (2 * N + 3) LL[-1] = 1 LL[1] = 0 LL_rev = [0] * (2 * N + 3) LL_rev[1] = -1 LL_rev[-1] = 0 st_append = st.append while st: v = st.pop() for u in adj[v]: if not seen[u]: seen[u] = 1 st_append(u) v_next = LL[v] v_prev = LL_rev[v] LL[v] = u LL[u] = v_next LL_rev[v_next] = u LL_rev[u] = v u_ = -u LL_rev[v] = u_ #LL_rev[u_] = v_prev LL[v_prev] = u_ LL[u_] = v s = -1 ans1 = [0] * (N + 1) ans2 = [0] * (N + 1) for i in range(1, 2 * N + 1): if s < 0: ans1[-s] = i else: ans2[s] = i s = LL[s] ans = '\n'.join([' '.join(map(str, [ans1[i], ans2[i]])) for i in range(1, N + 1)]) sys.stdout.write(ans) if __name__ == '__main__': main() ```
output
1
12,585
13
25,171
Provide tags and a correct Python 3 solution for this coding contest problem. Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex. You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree. Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree. Input The first line contains integer n (2 ≤ n ≤ 5·105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree. Output Print the only integer t — the minimal time required for all ants to be in the root of the tree. Examples Input 12 1 2 1 3 1 4 2 5 2 6 3 7 3 8 3 9 8 10 8 11 8 12 Output 6 Input 2 2 1 Output 1
instruction
0
12,923
13
25,846
Tags: dfs and similar, greedy, sortings, trees Correct Solution: ``` import sys def main(): n = int(sys.stdin.buffer.readline().decode('utf-8')) adj = [[] for _ in range(n)] deg = [0]*n for u, v in (map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer): adj[u-1].append(v-1) adj[v-1].append(u-1) deg[u-1] += 1 deg[v-1] += 1 ans = 0 for x in adj[0]: depth = [] stack = [(x, 0, 1)] while stack: v, par, d = stack.pop() if deg[v] == 1: depth.append(d) else: for dest in adj[v]: if dest != par: stack.append((dest, v, d+1)) depth.sort() for i in range(1, len(depth)): depth[i] = max(depth[i], depth[i-1]+1) ans = max(ans, depth[-1]) print(ans) if __name__ == '__main__': main() ```
output
1
12,923
13
25,847
Provide tags and a correct Python 3 solution for this coding contest problem. Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex. You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree. Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree. Input The first line contains integer n (2 ≤ n ≤ 5·105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree. Output Print the only integer t — the minimal time required for all ants to be in the root of the tree. Examples Input 12 1 2 1 3 1 4 2 5 2 6 3 7 3 8 3 9 8 10 8 11 8 12 Output 6 Input 2 2 1 Output 1
instruction
0
12,924
13
25,848
Tags: dfs and similar, greedy, sortings, trees Correct Solution: ``` import sys def read_input(): n = int(sys.stdin.buffer.readline().decode('utf-8')) graph = [[] for _ in range(n)] tree = [0] * n for u, v in (map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer): graph[u-1].append(v-1) graph[v-1].append(u-1) tree[u-1] += 1 tree[v-1] += 1 return graph, tree def main(): graph, tree = read_input() ans = 0 for x in graph[0]: depth = [] stack = [(x, 0, 1)] while stack: v, par, d = stack.pop() if tree[v] == 1: depth.append(d) else: for dest in graph[v]: if dest != par: stack.append((dest, v, d+1)) depth.sort() for i in range(1, len(depth)): depth[i] = max(depth[i], depth[i-1]+1) ans = max(ans, depth[-1]) print(ans) if __name__ == '__main__': main() ```
output
1
12,924
13
25,849
Provide tags and a correct Python 3 solution for this coding contest problem. Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex. You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree. Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree. Input The first line contains integer n (2 ≤ n ≤ 5·105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree. Output Print the only integer t — the minimal time required for all ants to be in the root of the tree. Examples Input 12 1 2 1 3 1 4 2 5 2 6 3 7 3 8 3 9 8 10 8 11 8 12 Output 6 Input 2 2 1 Output 1
instruction
0
12,925
13
25,850
Tags: dfs and similar, greedy, sortings, trees Correct Solution: ``` import sys n = int(sys.stdin.buffer.readline().decode('utf-8')) adj = [[] for _ in range(n)] deg = [0]*n for u, v in (map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer): adj[u-1].append(v-1) adj[v-1].append(u-1) deg[u-1] += 1 deg[v-1] += 1 ans = 0 for x in adj[0]: depth = [] stack = [(x, 0, 1)] while stack: v, par, d = stack.pop() if deg[v] == 1: depth.append(d) else: for dest in adj[v]: if dest != par: stack.append((dest, v, d+1)) depth.sort() for i in range(1, len(depth)): depth[i] = max(depth[i], depth[i-1]+1) ans = max(ans, depth[-1]) print(ans) ```
output
1
12,925
13
25,851
Provide tags and a correct Python 3 solution for this coding contest problem. Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex. You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree. Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree. Input The first line contains integer n (2 ≤ n ≤ 5·105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree. Output Print the only integer t — the minimal time required for all ants to be in the root of the tree. Examples Input 12 1 2 1 3 1 4 2 5 2 6 3 7 3 8 3 9 8 10 8 11 8 12 Output 6 Input 2 2 1 Output 1
instruction
0
12,926
13
25,852
Tags: dfs and similar, greedy, sortings, trees Correct Solution: ``` import sys def read_input(): n = int(sys.stdin.buffer.readline().decode('utf-8')) graph = [[] for _ in range(n)] tree = [0] * n for u, v in (map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer): graph[u-1].append(v-1) graph[v-1].append(u-1) tree[u-1] += 1 tree[v-1] += 1 return graph, tree def go_to_root(graph, tree): res = 0 for i in graph[0]: depths = [] st = [(i, 0, 1)] while st: leaf, terminal, depth = st.pop() if tree[leaf] == 1: depths.append(depth) else: for j in graph[leaf]: if j != terminal: st.append((j, leaf, depth + 1)) depths.sort() for i in range(1, len(depths)): depths[i] = max(depths[i], depths[i - 1] + 1) res = max(res, depths[-1]) return res def main(): graph, tree = read_input() res = go_to_root(graph, tree) print(res) if __name__ == '__main__': main() ```
output
1
12,926
13
25,853
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex. You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree. Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree. Input The first line contains integer n (2 ≤ n ≤ 5·105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree. Output Print the only integer t — the minimal time required for all ants to be in the root of the tree. Examples Input 12 1 2 1 3 1 4 2 5 2 6 3 7 3 8 3 9 8 10 8 11 8 12 Output 6 Input 2 2 1 Output 1 Submitted Solution: ``` g = {} def dfs(i, par): tt=[] xx=[] count= 0 if len(g[i]) == 1: return [0] for j in range(len(g[i])): if g[i][j] != par: temp = dfs(g[i][j], i) #print(temp) for k in range(len(temp)): xx.append(temp[k] + 1) xx.sort() if i == 1: return [xx[-1]] #print(xx) for j in range(len(xx)): while len(tt) > 0 and count > 0 and tt[-1] <= xx[j] - 1: count -= 1 tt.append(tt[-1] + 1) if len(tt) > 0 and tt[-1] == xx[j]: count += 1 continue tt.append(xx[j]) while count > 0 : tt.append(tt[-1] + 1) count -= 1 #print(tt) return tt def main(): mode="filee" if mode=="file":f=open("test.txt","r") get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()] [n]=get() for i in range(n-1): [x,y]=get() if x not in g: g[x] = [] if y not in g: g[y] = [] g[x].append(y) g[y].append(x) #print(g) t = dfs(1,0) print(t[-1]) if mode=="file":f.close() if __name__=="__main__": main() ```
instruction
0
12,927
13
25,854
No
output
1
12,927
13
25,855
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex. You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree. Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree. Input The first line contains integer n (2 ≤ n ≤ 5·105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree. Output Print the only integer t — the minimal time required for all ants to be in the root of the tree. Examples Input 12 1 2 1 3 1 4 2 5 2 6 3 7 3 8 3 9 8 10 8 11 8 12 Output 6 Input 2 2 1 Output 1 Submitted Solution: ``` n = int(input()) class Node: def __init__(self): self.start = 0 self.end = 0 self.level = 0 self.parent = None self.children = [] nodes = [Node() for _ in range(n)] levels = [[nodes[0]]] for _ in range(n-1): x, y = [int(x) - 1 for x in input().split()] nodes[x].children.append(nodes[y]) nodes[y].children.append(nodes[x]) current = set([nodes[0]]) while current: new_current = set() for node in current: for child in node.children: if child == node.parent: continue new_current.add(child) child.parent = node child.level = node.level + 1 if child.level == len(levels): levels.append([]) levels[child.level].append(child) current = new_current for level in reversed(levels[1:]): for node in level: if len(node.children) != 1: node.start = min(c.start for c in node.children if c != node.parent) + 1 count = sum(c.end - c.start + 1 for c in node.children if c != node.parent) max_end = max(c.end for c in node.children if c != node.parent) node.end = max(max_end + 1, node.start + count - 1) root_end = max(c.end for c in nodes[0].children) + 1 print(root_end) ```
instruction
0
12,928
13
25,856
No
output
1
12,928
13
25,857
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex. You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree. Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree. Input The first line contains integer n (2 ≤ n ≤ 5·105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree. Output Print the only integer t — the minimal time required for all ants to be in the root of the tree. Examples Input 12 1 2 1 3 1 4 2 5 2 6 3 7 3 8 3 9 8 10 8 11 8 12 Output 6 Input 2 2 1 Output 1 Submitted Solution: ``` import sys sys.setrecursionlimit(500050) def T(nivel, A2, a2): if len(a2) == 1: return [nivel] L = [] for e2 in range(1, len(a2)): L += T(nivel + 1, A2, A2[a2[e2] - 1]) return L def aux(L): if type(L) is int: return L c = 0 L.sort() for e2 in L: if e2 > c: c = e2 else: c += 1 return c N = int(input()) A = N * [[]] for i in range(N-1): x, y = map(int, input().split()) A[x-1] = A[x-1] + [y] A[y-1] = A[y-1] + [x] t = 0 for e in A[0]: k = aux(T(1, A, A[e - 1])) if k > t: t = k print(t) # 1502636712417 ```
instruction
0
12,929
13
25,858
No
output
1
12,929
13
25,859
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex. You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree. Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree. Input The first line contains integer n (2 ≤ n ≤ 5·105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree. Output Print the only integer t — the minimal time required for all ants to be in the root of the tree. Examples Input 12 1 2 1 3 1 4 2 5 2 6 3 7 3 8 3 9 8 10 8 11 8 12 Output 6 Input 2 2 1 Output 1 Submitted Solution: ``` n = int(input()) class Node: def __init__(self, start, count): self.start = start self.count = count self.level = 0 self.parent = -1 self.children = [] nodes = [Node(-1, 0) for _ in range(n)] levels = [[nodes[0]]] for _ in range(n-1): x, y = [int(x) - 1 for x in input().split()] nodes[x].children.append(nodes[y]) nodes[y].children.append(nodes[x]) current = set([nodes[0]]) while current: new_current = set() for node in current: for child in node.children: if child == node.parent: continue new_current.add(child) child.parent = node child.level = node.level + 1 if child.level == len(levels): levels.append([]) levels[node.level + 1].append(child) current = new_current for level in reversed(levels[1:]): for node in level: if len(node.children) == 1: node.start = 0 node.count = 1 else: node.start = min(c.start for c in node.children if c != node.parent) + 1 node.count = sum(c.count for c in node.children if c != node.parent) root = max(c.start + c.count for c in nodes[0].children) print(root) ```
instruction
0
12,930
13
25,860
No
output
1
12,930
13
25,861
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. I see a pink boar and I want it painted black. Black boars look much more awesome and mighty than the pink ones. Since Jaggy became the ruler of the forest, he has been trying his best to improve the diplomatic relations between the forest region and the nearby ones. Some other rulers, however, have requested too much in return for peace between their two regions, so he realized he has to resort to intimidation. Once a delegate for diplomatic relations of a neighboring region visits Jaggy’s forest, if they see a whole bunch of black boars, they might suddenly change their mind about attacking Jaggy. Black boars are really scary, after all. Jaggy’s forest can be represented as a tree (connected graph without cycles) with n vertices. Each vertex represents a boar and is colored either black or pink. Jaggy has sent a squirrel to travel through the forest and paint all the boars black. The squirrel, however, is quite unusually trained and while it traverses the graph, it changes the color of every vertex it visits, regardless of its initial color: pink vertices become black and black vertices become pink. Since Jaggy is too busy to plan the squirrel’s route, he needs your help. He wants you to construct a walk through the tree starting from vertex 1 such that in the end all vertices are black. A walk is a sequence of vertices, such that every consecutive pair has an edge between them in a tree. Input The first line of input contains integer n (2 ≤ n ≤ 200 000), denoting the number of vertices in the tree. The following n lines contains n integers, which represent the color of the nodes. If the i-th integer is 1, if the i-th vertex is black and - 1 if the i-th vertex is pink. Each of the next n - 1 lines contains two integers, which represent the indexes of the vertices which are connected by the edge. Vertices are numbered starting with 1. Output Output path of a squirrel: output a sequence of visited nodes' indexes in order of visiting. In case of all the nodes are initially black, you should print 1. Solution is guaranteed to exist. If there are multiple solutions to the problem you can output any of them provided length of sequence is not longer than 107. Example Input 5 1 1 -1 1 -1 2 5 4 3 2 4 4 1 Output 1 4 2 5 2 4 3 4 1 4 1 Note At the beginning squirrel is at node 1 and its color is black. Next steps are as follows: * From node 1 we walk to node 4 and change its color to pink. * From node 4 we walk to node 2 and change its color to pink. * From node 2 we walk to node 5 and change its color to black. * From node 5 we return to node 2 and change its color to black. * From node 2 we walk to node 4 and change its color to black. * We visit node 3 and change its color to black. * We visit node 4 and change its color to pink. * We visit node 1 and change its color to pink. * We visit node 4 and change its color to black. * We visit node 1 and change its color to black. Submitted Solution: ``` from collections import defaultdict import sys input = sys.stdin.readline adj = {} path = [] state = [] # Paints the subtree of x def paint(x, p): if x != 0: state[x] *= -1 path.append(x) for neigh in adj[x]: # Not retracting if neigh != p: # You reach this node again, flip if paint(neigh, x) == True: return True path.append(x) state[x] *= -1 # After painting tree, paint x black # Requires a few steps if not already painted if state[x] == -1: state[x] = 1 print(path) path.extend([p, x]) if p >= 0: state[p] *= -1 if state.count(1) == n: return True else: return False # num of nodes n = int(input()) for i in range(n): state.append(int(input())) for _ in range(1, n): a, b = map(int, input().strip(' ').split()) a -= 1 b -= 1 if a not in adj: adj[a] = [] if b not in adj: adj[b] = [] adj[a].append(b) adj[b].append(a) if state.count(1) != n: paint(0, -2) for node in path: print(node + 1, end=" ", flush=True) else: print(1) ```
instruction
0
12,963
13
25,926
No
output
1
12,963
13
25,927
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. I see a pink boar and I want it painted black. Black boars look much more awesome and mighty than the pink ones. Since Jaggy became the ruler of the forest, he has been trying his best to improve the diplomatic relations between the forest region and the nearby ones. Some other rulers, however, have requested too much in return for peace between their two regions, so he realized he has to resort to intimidation. Once a delegate for diplomatic relations of a neighboring region visits Jaggy’s forest, if they see a whole bunch of black boars, they might suddenly change their mind about attacking Jaggy. Black boars are really scary, after all. Jaggy’s forest can be represented as a tree (connected graph without cycles) with n vertices. Each vertex represents a boar and is colored either black or pink. Jaggy has sent a squirrel to travel through the forest and paint all the boars black. The squirrel, however, is quite unusually trained and while it traverses the graph, it changes the color of every vertex it visits, regardless of its initial color: pink vertices become black and black vertices become pink. Since Jaggy is too busy to plan the squirrel’s route, he needs your help. He wants you to construct a walk through the tree starting from vertex 1 such that in the end all vertices are black. A walk is a sequence of vertices, such that every consecutive pair has an edge between them in a tree. Input The first line of input contains integer n (2 ≤ n ≤ 200 000), denoting the number of vertices in the tree. The following n lines contains n integers, which represent the color of the nodes. If the i-th integer is 1, if the i-th vertex is black and - 1 if the i-th vertex is pink. Each of the next n - 1 lines contains two integers, which represent the indexes of the vertices which are connected by the edge. Vertices are numbered starting with 1. Output Output path of a squirrel: output a sequence of visited nodes' indexes in order of visiting. In case of all the nodes are initially black, you should print 1. Solution is guaranteed to exist. If there are multiple solutions to the problem you can output any of them provided length of sequence is not longer than 107. Example Input 5 1 1 -1 1 -1 2 5 4 3 2 4 4 1 Output 1 4 2 5 2 4 3 4 1 4 1 Note At the beginning squirrel is at node 1 and its color is black. Next steps are as follows: * From node 1 we walk to node 4 and change its color to pink. * From node 4 we walk to node 2 and change its color to pink. * From node 2 we walk to node 5 and change its color to black. * From node 5 we return to node 2 and change its color to black. * From node 2 we walk to node 4 and change its color to black. * We visit node 3 and change its color to black. * We visit node 4 and change its color to pink. * We visit node 1 and change its color to pink. * We visit node 4 and change its color to black. * We visit node 1 and change its color to black. Submitted Solution: ``` res=[] n=int(input()) g=[[] for x in range(n)] l=[] def go(v,p): res.append(v) l[v]=-l[v] for i in g[v]: if i!=p: go(i,v) l[v]=-l[v] res.append(v) for i in g[v]: if i!=p: if l[i]==-1: res.append(i) res.append(v) l[v]=-l[v] return s=0 for i in range(n): l.append(int(input())) s+=l[i] if s==n: print(1) else: for i in range(n-1): a,b=map(int,input().split(' ')) g[a-1].append(b-1) g[b-1].append(a-1) go(0,-1) q=str() for i in res: q+=str(i+1)+' ' print(q) ```
instruction
0
12,964
13
25,928
No
output
1
12,964
13
25,929
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. I see a pink boar and I want it painted black. Black boars look much more awesome and mighty than the pink ones. Since Jaggy became the ruler of the forest, he has been trying his best to improve the diplomatic relations between the forest region and the nearby ones. Some other rulers, however, have requested too much in return for peace between their two regions, so he realized he has to resort to intimidation. Once a delegate for diplomatic relations of a neighboring region visits Jaggy’s forest, if they see a whole bunch of black boars, they might suddenly change their mind about attacking Jaggy. Black boars are really scary, after all. Jaggy’s forest can be represented as a tree (connected graph without cycles) with n vertices. Each vertex represents a boar and is colored either black or pink. Jaggy has sent a squirrel to travel through the forest and paint all the boars black. The squirrel, however, is quite unusually trained and while it traverses the graph, it changes the color of every vertex it visits, regardless of its initial color: pink vertices become black and black vertices become pink. Since Jaggy is too busy to plan the squirrel’s route, he needs your help. He wants you to construct a walk through the tree starting from vertex 1 such that in the end all vertices are black. A walk is a sequence of vertices, such that every consecutive pair has an edge between them in a tree. Input The first line of input contains integer n (2 ≤ n ≤ 200 000), denoting the number of vertices in the tree. The following n lines contains n integers, which represent the color of the nodes. If the i-th integer is 1, if the i-th vertex is black and - 1 if the i-th vertex is pink. Each of the next n - 1 lines contains two integers, which represent the indexes of the vertices which are connected by the edge. Vertices are numbered starting with 1. Output Output path of a squirrel: output a sequence of visited nodes' indexes in order of visiting. In case of all the nodes are initially black, you should print 1. Solution is guaranteed to exist. If there are multiple solutions to the problem you can output any of them provided length of sequence is not longer than 107. Example Input 5 1 1 -1 1 -1 2 5 4 3 2 4 4 1 Output 1 4 2 5 2 4 3 4 1 4 1 Note At the beginning squirrel is at node 1 and its color is black. Next steps are as follows: * From node 1 we walk to node 4 and change its color to pink. * From node 4 we walk to node 2 and change its color to pink. * From node 2 we walk to node 5 and change its color to black. * From node 5 we return to node 2 and change its color to black. * From node 2 we walk to node 4 and change its color to black. * We visit node 3 and change its color to black. * We visit node 4 and change its color to pink. * We visit node 1 and change its color to pink. * We visit node 4 and change its color to black. * We visit node 1 and change its color to black. Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Wed Apr 10 11:09:20 2019 @author: slappy """ N = int(2e5 + 22) adj, color, res = [[] for _ in range(N + 1)], [N + 1], [] def _dfs(cur, par): for el in adj[cur]: if el != par: res.append(el) color[el] = -color[el] _dfs(el, cur) res.append(cur) color[cur] = -color[cur] if color[el] == 1: continue # visit el then back to cur res.extend([el, cur]), color[el], color[cur] = -color[el], -color[cur] def _solve(): n = int(input()) #color = list(map(int, input().split('\n'))) [int(x) for x in input().split('\n')] for i in range(n): color.append(int(input())); for i in range(1, n): x, y = map(int, input().split()) adj[x].append(y) adj[y].append(x) res.append(1) _dfs(1, 0) if color[1] == -1: res.extend([adj[1][0], 1, adj[1][0]]) print(res) _solve() ```
instruction
0
12,965
13
25,930
No
output
1
12,965
13
25,931
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree T with N vertices and an undirected graph G with N vertices and M edges. The vertices of each graph are numbered 1 to N. The i-th of the N-1 edges in T connects Vertex a_i and Vertex b_i, and the j-th of the M edges in G connects Vertex c_j and Vertex d_j. Consider adding edges to G by repeatedly performing the following operation: * Choose three integers a, b and c such that G has an edge connecting Vertex a and b and an edge connecting Vertex b and c but not an edge connecting Vertex a and c. If there is a simple path in T that contains all three of Vertex a, b and c in some order, add an edge in G connecting Vertex a and c. Print the number of edges in G when no more edge can be added. It can be shown that this number does not depend on the choices made in the operation. Constraints * 2 \leq N \leq 2000 * 1 \leq M \leq 2000 * 1 \leq a_i, b_i \leq N * a_i \neq b_i * 1 \leq c_j, d_j \leq N * c_j \neq d_j * G does not contain multiple edges. * T is a tree. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{N-1} b_{N-1} c_1 d_1 : c_M d_M Output Print the final number of edges in G. Examples Input 5 3 1 2 1 3 3 4 1 5 5 4 2 5 1 5 Output 6 Input 7 5 1 5 1 4 1 7 1 2 2 6 6 3 2 5 1 3 1 6 4 6 4 7 Output 11 Input 13 11 6 13 1 2 5 1 8 4 9 7 12 2 10 11 1 9 13 7 13 11 8 10 3 8 4 13 8 12 4 7 2 3 5 11 1 4 2 11 8 10 3 5 6 9 4 10 Output 27 Submitted Solution: ``` print("5") ```
instruction
0
13,156
13
26,312
No
output
1
13,156
13
26,313
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree T with N vertices and an undirected graph G with N vertices and M edges. The vertices of each graph are numbered 1 to N. The i-th of the N-1 edges in T connects Vertex a_i and Vertex b_i, and the j-th of the M edges in G connects Vertex c_j and Vertex d_j. Consider adding edges to G by repeatedly performing the following operation: * Choose three integers a, b and c such that G has an edge connecting Vertex a and b and an edge connecting Vertex b and c but not an edge connecting Vertex a and c. If there is a simple path in T that contains all three of Vertex a, b and c in some order, add an edge in G connecting Vertex a and c. Print the number of edges in G when no more edge can be added. It can be shown that this number does not depend on the choices made in the operation. Constraints * 2 \leq N \leq 2000 * 1 \leq M \leq 2000 * 1 \leq a_i, b_i \leq N * a_i \neq b_i * 1 \leq c_j, d_j \leq N * c_j \neq d_j * G does not contain multiple edges. * T is a tree. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{N-1} b_{N-1} c_1 d_1 : c_M d_M Output Print the final number of edges in G. Examples Input 5 3 1 2 1 3 3 4 1 5 5 4 2 5 1 5 Output 6 Input 7 5 1 5 1 4 1 7 1 2 2 6 6 3 2 5 1 3 1 6 4 6 4 7 Output 11 Input 13 11 6 13 1 2 5 1 8 4 9 7 12 2 10 11 1 9 13 7 13 11 8 10 3 8 4 13 8 12 4 7 2 3 5 11 1 4 2 11 8 10 3 5 6 9 4 10 Output 27 Submitted Solution: ``` import queue SIZE = 2000 vec = [[] for _ in range(SIZE)] par = [[-1] * SIZE for _ in range(SIZE)] id_ = [[-1] * SIZE for _ in range(SIZE)] ans = 0 def dfs(v: int, p: int, rt: int): par[rt][v] = p for to in vec[v]: if to == p: continue dfs(to, v, rt) def dfs2(v: int, p: int, b: int): global ans if id_[b][v] == v: ans += 1 b = v for to in vec[v]: if to == p: continue dfs2(to, v, b) def add(a: int, b: int): if id_[a][b] == b or id_[b][a] == a: return if id_[a][b] != -1: add(id_[a][b], b) return if id_[b][a] != -1: add(id_[b][a], a) return id_[a][b] = b id_[b][a] = a nxt = [] que = queue.Queue() que.put(b) while not que.empty(): v = que.get() for to in vec[v]: if to == par[a][v]: continue if id_[a][to] != -1: nxt.append((to, b)) else: id_[a][to] = b que.put(to) que.put(a) while not que.empty(): v = que.get() for to in vec[v]: if to == par[b][v]: continue if id_[b][to] != -1: nxt.append((to, a)) else: id_[b][to] = a que.put(to) for u, v in nxt: add(u, v) def adding_edges(N: int, M: int, T: list, G: list)->int: global ans for a, b in T: vec[a-1].append(b-1) vec[b-1].append(a-1) for i in range(N): dfs(i, -1, i) for c, d in G: add(c-1, d-1) for i in range(N): for to in vec[i]: dfs2(to, i, i) return ans//2 if __name__ == "__main__": N = 0 M = 0 N, M = map(int, input().split()) T = [tuple(int(s) for s in input().split()) for _ in range(N-1)] G = [tuple(int(s) for s in input().split()) for _ in range(M)] ans = adding_edges(N, M, T, G) print(ans) ```
instruction
0
13,157
13
26,314
No
output
1
13,157
13
26,315
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree T with N vertices and an undirected graph G with N vertices and M edges. The vertices of each graph are numbered 1 to N. The i-th of the N-1 edges in T connects Vertex a_i and Vertex b_i, and the j-th of the M edges in G connects Vertex c_j and Vertex d_j. Consider adding edges to G by repeatedly performing the following operation: * Choose three integers a, b and c such that G has an edge connecting Vertex a and b and an edge connecting Vertex b and c but not an edge connecting Vertex a and c. If there is a simple path in T that contains all three of Vertex a, b and c in some order, add an edge in G connecting Vertex a and c. Print the number of edges in G when no more edge can be added. It can be shown that this number does not depend on the choices made in the operation. Constraints * 2 \leq N \leq 2000 * 1 \leq M \leq 2000 * 1 \leq a_i, b_i \leq N * a_i \neq b_i * 1 \leq c_j, d_j \leq N * c_j \neq d_j * G does not contain multiple edges. * T is a tree. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{N-1} b_{N-1} c_1 d_1 : c_M d_M Output Print the final number of edges in G. Examples Input 5 3 1 2 1 3 3 4 1 5 5 4 2 5 1 5 Output 6 Input 7 5 1 5 1 4 1 7 1 2 2 6 6 3 2 5 1 3 1 6 4 6 4 7 Output 11 Input 13 11 6 13 1 2 5 1 8 4 9 7 12 2 10 11 1 9 13 7 13 11 8 10 3 8 4 13 8 12 4 7 2 3 5 11 1 4 2 11 8 10 3 5 6 9 4 10 Output 27 Submitted Solution: ``` from collections import deque a=[] def bfs(maze, visited, sy, sx): queue = deque([[sy, sx]]) visited[sy][sx] = 0 while queue: y, x = queue.popleft() if queue == False: return visited[y][x] for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]): new_y, new_x = y+j, x+k if maze[new_y][new_x] == "." and \ visited[new_y][new_x] == -1: visited[new_y][new_x] = visited[y][x] + 1 queue.append([new_y, new_x]) if __name__ == "__main__": R, C = map(int, input().split()) for h in range(R): k=input() a.append(k) for p in k: p="#" maze = [input() for i in range(R)] visited = [[-1]*C for j in range(R)] print(bfs(maze, visited, sy, sx)) ```
instruction
0
13,158
13
26,316
No
output
1
13,158
13
26,317